如何将字符串中的变量放入数组中?

How to put variables from a string into an array?

我正在制作一个项目,其中有一个 JButton 网格,我希望能够将这些按钮中的哪些被单击保存到一个数组中。我知道如何获取每个按钮的坐标,但对于如何制作数组并在单击 JButton 时更改存储在其中的坐标一无所知。 我的代码如下:

public ButtonGrid(int width, int length, String coords) {
    frame.setLayout(new GridLayout(width, length));
    grid = new JButton[width][length];
    state = new HashMap<JButton, String>();

    for (int y = 0; y < length; y++) {
        for (int x = 0; x < width; x++) {
            final JButton nb = new JButton();
            nb.setPreferredSize(new Dimension(50, 50));
            grid[x][y] = nb;
            state.put(grid[x][y], "blank");

            nb.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    Object source = e.getSource();
                    for (int i = 0; i < grid.length; i++) {
                        for (int j = 0; j < grid.length; j++) {
                            if (source == grid[i][j]) {
                                String coords = String.valueOf(grid[i][j]);
                                System.out.println(
                                        Stream.of(coords.split("\D+")).limit(3).collect(Collectors.toList()));
                            }
                        }
                    }

                    if (state.get(nb).equals("blank"))
                        mapButtonToColor(nb, "red");
                    else if (state.get(nb).equals("red"))
                        mapButtonToColor(nb, "blank");
                    setButtonColors();
                }
            });
            frame.add(grid[x][y]);
        }
    }

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

}

首先,我建议你使用继承

public class GridButton extends JButton {
    int x, y;
   // String state; // probably put this here instead 
    public GridButton(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    } 
}

然后,您将需要一个列表而不是一个数组,因为数组具有固定的大小,您应该可以随心所欲地点击

List<int[]> list = new ArrayList<>();

有了上面的class,当你点击时,你可以立即访问这些位置,而不是检查整个网格

首先,使用class,所以替换

final JButton nb = new JButton();

final JButton nb = new GridButton(x, y);

并且在动作侦听器中,访问值并添加到列表中

@Override 
public void actionPerformed(ActionEvent e) {
    GridButton source = (GridButton) e.getSource();
    list.add(new int[] {source.x, source.y});
}

changing the coordinates stored inside whenever a JButton is clicked

我不确定你为什么要这样做,但你必须通过 setter 方法修改按钮本身 class 以及 swap/reset 按钮具有新定位的数组