我正在尝试创建一个自定义 JPanel,将其添加到 GUI 设置中的卡片布局中。在此自定义布局中,我使用网格布局并将按钮直接添加到容器中。我现在需要向这些按钮添加 Action 监听器,但不知道如何操作。任何帮助将不胜感激,请找到下面的自定义类。
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class PuzzleSudokuPanel extends JPanel{
int[][] grid =
{{0, 0, 0, 5, 0, 0, 8, 3, 1},
{0, 5, 3, 0, 0, 8, 7, 0, 0},
{7, 0, 0, 0, 4, 2, 0, 6, 0},
{0, 0, 9, 0, 3, 0, 0, 7, 8},
{0, 0, 2, 4, 0, 6, 1, 0, 0},
{6, 3, 0, 0, 9, 0, 2, 0, 0},
{0, 1, 0, 7, 6, 0, 0, 0, 9},
{0, 0, 4, 9, 0, 0, 5, 8, 0},
{2, 9, 7, 0, 0, 3, 0, 0, 0}};
Container myGrid = new Container();
public PuzzleSudokuPanel ()throws NullPointerException{
try{
for(int i = 0; i<9; i++){
for(int j = 0; j<9; j++){
String appropriateNumber = convertSimple(grid[i][j]);
myGrid.add(new JButton(appropriateNumber));
}
}
}
catch(NullPointerException e){
}
myGrid.setLayout(new GridLayout(9, 9));
myGrid.setPreferredSize (new Dimension(400, 400));
add(myGrid);
}
public static String convertSimple(int a){
return ("" + a);
}
}
[编辑]
calkuro代码:
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class PuzzleCalkuroPanel extends JPanel{
String[][] grid =
{{"3/", "3/", "3-", "8x"},
{"9+", "9+", "3-", "8x"},
{"9+", "9+2", "9+2", "8x"},
{"1", "9+2", "1-", "1-"}};
Container myGrid = new Container();
public PuzzleCalkuroPanel ()throws NullPointerException{
try{
for(int i = 0; i<4; i++){
for(int j = 0; j<4; j++){
JButton button = new JButton(grid[i][j]);
button.addActionListener(new calkuroListener());
myGrid.add(new JButton(grid[i][j]));
}
}
}
catch(NullPointerException e){
}
myGrid.setLayout(new GridLayout(4, 4));
myGrid.setPreferredSize (new Dimension(400, 400));
add(myGrid);
}
private class calkuroListener implements ActionListener{
public void actionPerformed (ActionEvent event){
String numStr = JOptionPane.showInputDialog("Enter a number to change to: ");
JOptionPane.showMessageDialog(null, numStr);
}
}
}
最佳答案
而不是...
myGrid.add(new JButton(appropriateNumber));
做...
JButton button = new JButton(appropriateNumber);
button.addActionListener(...);
myGrid.add(button);
已更新
这就是你正在做的事情...
JButton button = new JButton(grid[i][j]); // Create button here, good...
button.addActionListener(new calkuroListener()); // Add listener here, good...
myGrid.add(new JButton(grid[i][j])); // Create a new button here, bad...
这就是你应该做的
JButton button = new JButton(grid[i][j]); // Create button here, good...
button.addActionListener(new calkuroListener()); // Add listener here, good...
myGrid.add(button); // Add button here, good...
关于java - 将 ActionListener 添加到直接添加到容器中的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12986069/