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 我只是希望它是这样,所以当我单击任何按钮时它会打印你好,它会变成红色。请帮忙