user2774713
user2774713

Reputation: 77

Grid of Buttons ActionListener

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);
            }
        });

I have a grid of buttons and when I try to add an actionListener it gives my an error saying OutOfBoundsException I just wanted it to be so when I click any button it will print hello and it will turn red. Please Help

Upvotes: 2

Views: 1617

Answers (1)

camickr
camickr

Reputation: 324118

You need to add the ActionListener to every button, so you need to the ActionListener to the button when you create the button.

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);
    }
});

An even better approach is to just create a single ActionListener, since the code is the same for every button. Something like:

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;

Upvotes: 2

Related Questions