2
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 が出力され、赤に変わります。助けてください

4

1 に答える 1

2

すべてのボタンに 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;
于 2013-09-13T20:04:11.633 に答える