是否可以将ActionListener添加到未明确定义的JButton中? [英] Can I add an ActionListener to a JButton that is not explicitely defined?

查看:91
本文介绍了是否可以将ActionListener添加到未明确定义的JButton中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个棋盘式的东西,每个图块都是一个JButton. 我想将相同的actionListener添加到每个按钮.这是代码:

I'm trying to make a chess-board kind of thing with each tile being a JButton. I want to add the same actionListener to every button. Here's the code:

package checker;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class mainClass extends JFrame   {

JPanel board = new JPanel();
ActionListener btnPrs = new btnPressed();


    public mainClass()
    {

        board.setLayout(new GridLayout(8,8,0,0));
        for(int i = 0; i<8; i++)
            for(int j = 0; j<8; j++)
            {
                if( i%2 == 0 && j%2 == 0 || i%2 == 1 && j%2 == 1)
                {   
                    board.add(new DrawWhite());
                    //board.add(new DrawWhite().addActionListener(btnPrs));

                }
                else board.add(new DrawBlack());
            }

        add(board);
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        mainClass frame = new mainClass();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400,400);
        frame.setVisible(true);
        frame.setTitle("Checker");
        frame.setLocationRelativeTo(null);

    }

    class DrawWhite extends JButton
    {
        protected void paintComponent(Graphics g)
        {
            super.paintComponent(g);

            g.setColor(Color.WHITE);
            g.fillRect(0,0, 50,50);
            }       
    }

    class DrawBlack extends JButton
    {
    protected void paintComponent(Graphics g)
        {
            super.paintComponent(g);

            g.setColor(Color.BLACK);
            g.fillRect(0, 0, 50, 50);

        }
    }


    class btnPressed implements ActionListener
    {

        @Override
        public void actionPerformed(ActionEvent e) {

            System.out.println("pressed!");

        }
     }

     }

我不想显式定义64个按钮,并手动将ActionListeners添加到每个按钮.我尝试过将它们包含在第23行的注释中.是否有适当的方法来做到这一点?

I don't want to explicitly define 64 buttons and add ActionListeners to each of them manually. I tried they way that is included as a comment on line 23. Is there a proper way to do it?

任何帮助将不胜感激.

Any help would be highly appreciated.

推荐答案

只需将按钮存储在一个临时变量中即可:

Just store the button in a temporary variable:

DrawWhite dw = new DrawWhite();
dw.addActionListener(btnPrs);
board.add(dw);

这篇关于是否可以将ActionListener添加到未明确定义的JButton中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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