java - 按钮网格 ActionListener

标签 java swing grid jbutton 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 我只是希望它是这样的,当我单击任何按钮时,它会打印“hello”并且会变成红色。 请帮忙

最佳答案

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

关于java - 按钮网格 ActionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18794324/

相关文章:

java - VisualVM Sampler CPU swing Paint() 怪异

grid - Ag-Grid : How to get the focused cell value

javascript - Kendo TreeList 绑定(bind)不会保留在行编辑上

java - 如何强制 JScrollPane 仅垂直滚动?

java - 我应该如何为该类的每个实例声明一个可见的常量集?

java - 如何使用 Logback 仅更改当前线程的日志级别

Java RMI 客户端和远程服务器连接被拒绝到本地主机

java - Jtable java.lang.NullPointerException

html - 何时在网格布局中使用行或语义标签

Java Files.copy 完全替换现有的删除文件