Elc*_*apo 1 java arrays swing jbutton
基本上我正在尝试制作一个Lightout游戏!我想创建一个JButton数组,以便我可以跟踪每个按钮的索引(原因是每个按钮的状态取决于其他按钮的状态)
到目前为止我有:
JPanel panel = new JPanel();
setTitle("Memory");
setContentPane(panel);
setPreferredSize(new Dimension(300, 300));
panel.setLayout(new GridLayout(5,5));
JButton[][] buttons = new JButton[5][5] ;
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++) {
buttons[i][j] = new JButton();
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
Run Code Online (Sandbox Code Playgroud)
但这并不像我期望的那样.当我运行它时,我刚刚得到了一个空白的JFrame.任何帮助,将不胜感激
附加的代码应该修复它.您正在创建按钮,但不将其添加到JFrame.我编辑了代码来添加动作监听器,当你点击它时,它会访问JButton的id并显示它.
public class CodeSample extends JFrame {
private static final long serialVersionUID = -8134989438964195251L;
public CodeSample() {
JPanel panel = new JPanel();
setTitle("Memory");
setContentPane(panel);
setPreferredSize(new Dimension(300, 300));
panel.setLayout(new GridLayout(5, 5));
ButtonListener listener = new ButtonListener();
JButton[][] buttons = new JButton[5][5];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
buttons[i][j] = new JButton();
buttons[i][j].setBackground(Color.black);
buttons[i][j].putClientProperty("id",
String.valueOf(i).concat(String.valueOf(j)));
buttons[i][j].addActionListener(listener);
panel.add(buttons[i][j]);
}
}
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(((JButton) e.getSource())
.getClientProperty("id"));
}
}
public static void main(String[] args) {
new CodeSample();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |