按钮网格ActionListener [英] Grid of Buttons ActionListener

查看:195
本文介绍了按钮网格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);
            }
        });

我有一个按钮的网格,当我尝试添加一个actionListener时,它给了我一个错误,说OutOfBoundsException
我只是希望它是如此,当我点击任何按钮,它会打印你好,它会变成红色。
请帮助

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

推荐答案

您需要将ActionListener添加到每个按钮,因此您需要将ActionListener添加到按钮当你创建按钮。

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

更好的方法是创建一个ActionListener,因为每个按钮的代码都是一样的。例如:

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;

这篇关于按钮网格ActionListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆