Есть много способов добиться этого. Сначала есть решение, где вы создаете HashMap<Point,JButton>
и удерживаете каждую кнопку с ее координатой. Поэтому, когда пользователь вводит 2,3
, например, вы просто hashmap.get(new Point(2,3));
, и это дает вам JButton
. Пример, чтобы полностью проиллюстрировать, что я имею в виду:
public class PointButtonTest extends JFrame {
private HashMap<Point, JToggleButton> buttons;
public PointButtonTest() {
super("test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
buttons = new HashMap<>();
createButtons();
setLayout(new GridLayout(5, 5));
pack();
setLocationRelativeTo(null);
String xString = JOptionPane.showInputDialog("Give the X of the coordinate:");
String yString = JOptionPane.showInputDialog("Give the Y of the coordinate:");
int x = Integer.parseInt(xString) - 1;
int y = Integer.parseInt(yString) - 1;
JToggleButton button = buttons.get(new Point(x, y));
button.setSelected(true);
}
private void createButtons() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
JToggleButton button = new JToggleButton((i + 1) + "," + (j + 1)); //more human
Point p = new Point(i, j);
buttons.put(p, button);
add(button);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new PointButtonTest().setVisible(true);
});
}
}
Где пользователя просят дать X
и Y
, и выбирается кнопка с этими координатами. Запустите его, и вы увидите.
Другой способ - создать новый класс JButton
, в котором есть поле с именем coordinates
(или что-то еще). Затем вы сохраняете все кнопки в более простую структуру (возможно, ArrayList<PointButton>
) и просто перебираете ее, чтобы найти кнопку с этими координатами.
Что-то вроде:
private static class PointButton extends JButton {
private Point coordinates;
public PointButton(Point coordinates) {
this.coordinates = coordinates;
}
public PointButton(int x, int y) {
this.coordinates = new Point(x, y);
}
public Point getCoordinates() {
return coordinates;
}
}