for(gbc.gridy = 3; gbc.gridy > 0; gbc.gridy--)
for(gbc.gridx = 0; gbc.gridx < 3;gbc.gridx++)
{
grid[btnNum] = new JButton("" + (btnNum+1));
grid[btnNum].setPreferredSize(new Dimension(75,75));
frame.add(grid[btnNum], gbc);
grid[btnNum].addActionListener(this);
grid[btnNum].addKeyListener(this);
btnNum++;
}
我有一个以3x3网格显示的按钮数组,每个按钮都有一个动作监听器。
public void actionPerformed(ActionEvent e){
String output = "";
if(e.getSource() == grid[0]){
System.out.println("button 1");
}
}
这不正确吗?
上下文中的完整示例:
public class ButtonGrid implements ActionListener, KeyListener{
JFrame frame=new JFrame(); //creates frame
JButton[] grid; //names the grid of buttons
public ButtonGrid(){ //constructor
frame.setTitle("MPC");
frame.setLayout(new GridBagLayout()); //set layout
JButton[] grid=new JButton[12]; //allocate the size of grid
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
int btnNum = 0;
grid[9] = new JButton("0");
grid[9].setPreferredSize(new Dimension(75,75));
grid[10] = new JButton("-");
grid[10].setPreferredSize(new Dimension(75,75));
grid[11] = new JButton("=");
grid[11].setPreferredSize(new Dimension(75,75));
frame.add(grid[9], gbc);
gbc.gridx++;
frame.add(grid[10], gbc);
gbc.gridx++;
frame.add(grid[11], gbc);
for(gbc.gridy = 3; gbc.gridy > 0; gbc.gridy--)
for(gbc.gridx = 0; gbc.gridx < 3;gbc.gridx++){
grid[btnNum] = new JButton("" + (btnNum+1));
grid[btnNum].setPreferredSize(new Dimension(75,75));
frame.add(grid[btnNum], gbc);
grid[btnNum].addActionListener(this);
grid[btnNum].addKeyListener(this);
btnNum++;
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); //sets appropriate size for frame
frame.setVisible(true); //makes frame visible
}
public static void main(String[] args) {
new ButtonGrid();//makes new ButtonGrid with 2 parameters
}
public void actionPerformed(ActionEvent e){
String output = "";
if(e.getSource() == grid[0]){
System.out.println("button one");
//playSound(abc.kick);
}}
答案 0 :(得分:6)
您的网格变量在ActionListener中为null。我的赌注 - 你正在掩盖变量。
解决方案:确保初始化网格字段,而不是本地网格变量
public class ButtonGrid implements ActionListener, KeyListener{
JFrame frame=new JFrame();
JButton[] grid; // grid field remains null
public ButtonGrid(){
frame.setTitle("MPC");
frame.setLayout(new GridBagLayout());
JButton[] grid=new JButton[12]; // ****** a LOCAL variable ******
在指定的行处创建阴影变量。这意味着因为您在构造函数中重新声明了网格,所以只初始化局部变量,而不初始化类中声明的字段,使字段为null。解决方案:不要重新声明网格。将其更改为:
public class ButtonGrid implements ActionListener, KeyListener{
JFrame frame = new JFrame();
JButton[] grid;
public ButtonGrid(){
frame.setTitle("MPC");
frame.setLayout(new GridBagLayout());
grid = new JButton[12]; // ***** this initializes the field ******
答案 1 :(得分:2)
试试这个。
public void actionPerformed(ActionEvent e){
String output = "";
for(int i=0; i<=grid.length; i++){
if(e.getSource() == grid[i]){
System.out.println("button "+i);
}
}
}