这是我在这里的第一篇文章,希望我能做对!
我做了什么我创建了一个带有 JButtons 的 NxN 板,指示从 [0, 0] 到 [9, 9] 的坐标。每次单击按钮时,控制台都会显示坐标,我试图将这些坐标保存在 ArrayList 中,通过在另一个窗口中按下第二个按钮将显示该坐标……没什么特别的,抱歉,只是绕着我的头基本概念...
问题是我无法将要保存的值保存到 ArrayList 中,一旦按下第二个按钮,我就无法调用它...附上我的课程的代码...每个都在不同的文件中.
Board.java
public class Board{
public Board(){
JFrame win = new JFrame ();
GridLayout layout = new GridLayout(10, 10);
win.setLayout(layout);
for (int row1 = 0; row1 < 10 ; row1 = row1+1){
for (int col1 = 0; col1 < 10; col1 = col1+1){
JPanel jp = new JPanel();
JButton jb = new JButton("[" + row1 + "," + col1 + "]");
jb.addActionListener(new ButtonEventHandler(row1, col1));
jp.add(jb);
win.add(jp);
}
win.setVisible(true);
win.pack();
}
JFrame win2 = new JFrame("Stored values");
win2.setVisible(true);
JPanel jp2 = new JPanel();
win2.add(jp2);
JButton jb2 = new JButton("Check Log");
jb2.addActionListener(new Position(win2, jb2));
jp2.add(jb2);
win2.pack();
}}
ButtonEventHandler.java
public class ButtonEventHandler implements ActionListener {
private int _row1;
private int _col1;
private ArrayList<Number> _list;
public ButtonEventHandler(int row1, int col1){
_row1 = row1;
_col1 = col1;
_list = new ArrayList<Number>();
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Position: " + _row1 + ", " + _col1);
_list.add(_row1);
_list.add(_col1);
}
public ArrayList<Number> getList(){
return _list;
}}
位置.java
public class Position implements ActionListener {
private JFrame _win2;
private JButton _jb2;
private int _row1;
private int _col1;
private ArrayList<Number> _list;
private ButtonEventHandler beh = new ButtonEventHandler(_row1, _col1);
public Position(JFrame win2, JButton jb2){
_win2 = win2;
_jb2 = jb2;
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(beh.getList());
}
}
非常感谢你的帮忙!!
塞布