【问题标题】:Grid of Buttons ActionListener按钮网格 ActionListener
【发布时间】:2013-09-13 20:01:32
【问题描述】:
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 我只是希望它是这样,当我单击任何按钮时,它会打印你好,它会变成红色。 请帮忙

【问题讨论】:

  • 你来自javascript 背景,不是吗?
  • 我相信如果您将代码放在循环内的 addActionListener() 中,您的代码会起作用。这是必要的,以便每个按钮都获得一个 ActionListener 并且 x 和 y 是有效的数组索引。我相信当你写“OutOfBoundsExcepton”时,你一定是指“ArrayIndexOutOfBoundsException”。当您遇到任何异常时,您会得到所谓的“堆栈跟踪”:bit.ly/160JEO2 了解如何解释堆栈跟踪可以帮助您。我认为在它们的循环之外使用 x 和 y,它们都太大而不能成为有效的数组索引。
  • 这里是如何在 for 循环中正确声明循环索引的演示代码链接:gist.github.com/kaydell/6565783

标签: java swing grid jbutton actionlistener


【解决方案1】:

每个按钮都需要添加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;

【讨论】:

  • +1 应该可以解决眼前的问题。在循环之前创建监听器可能会更好,因为它们的代码都是相同的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
  • 2017-10-26
  • 2017-04-07
  • 2017-02-21
  • 2011-12-13
  • 1970-01-01
相关资源
最近更新 更多