public ButtonGrid(int width, int length){
Random r=new Random();
int w=r.nextInt(13-1)+1;
JTextField g = new JTextField();
Scanner u=new Scanner(System.in);
frame.setSize(500, 500);
frame.setLayout(new GridLayout(width,length));
grid=new JButton[width][length];
for(y=0;y<length;y++){
for(x=0;x<width;x++){
//if (y < 4) {
//grid[x][y]=new JButton("x");
//}
//else if (y>5){
//grid[x][y]=new JButton(""+u.nextInt());
//frame.setVisible(true);;
//}
//else{
grid[x][y]=new JButton(" ");
//}
frame.add(grid[x][y]);
}
}
grid[x][y].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Hello");
((JButton)e.getSource()).setBackground(Color.red);
}
});
我有一个按钮网格,当我尝试添加 actionListener 时,它给我一个错误,说 OutOfBoundsException我只是希望它是这样,当我单击任何按钮时,它会打印 hello 并且它会变成红色。请帮忙
您需要将
ActionListener 添加到每个按钮,因此在创建按钮时需要将 ActionListener 添加到按钮。
grid[x][y]=new JButton(" ");
grid[x][y].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Hello");
((JButton)e.getSource()).setBackground(Color.red);
}
});
更好的方法是只创建一个 ActionListener,因为每个按钮的代码都是相同的。像这样:
ActionListener al = new ActionListener()
{
public void actionPerformed(ActionEvent e){
System.out.println("Hello");
((JButton)e.getSource()).setBackground(Color.red);
}
});
...
for (y...)
for (x....)
JButton button = new JButton(...);
button.addActionListener(al);
grid[x][y] = button;