gpt4 book ai didi

java - 是否可以从坐标生成对 JButton 的引用?

转载 作者:行者123 更新时间:2023-12-01 23:50:52 25 4
gpt4 key购买 nike

我正在创建的游戏使用 JButton 网格作为 UI,

public static JButton b11 = new JButton(".");
public static JButton b21 = new JButton(".");

其中b11和b21分别是代表(1,1)和(2,1)的按钮。我正在使用 ActionListener 系统来处理运行时事件,并且想知道是否有一种方法可以仅使用坐标来引用这些按钮之一。 (也就是说,如果游戏说对 (1,1) 处的单位造成 10 点伤害,我如何从坐标中引用 b11?)

最佳答案

有很多方法可以实现这一目标。首先是创建 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);
});
}
}

要求用户提供 XY并且具有这些坐标的按钮被选中。运行它,你就会看到。

另一种方法是创建一个新的 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;
}
}

关于java - 是否可以从坐标生成对 JButton 的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58221244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com