多个单选按钮的动作侦听器 [英] Action listener for multiple radio buttons

查看:113
本文介绍了多个单选按钮的动作侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算编写一个程序,让用户选择从8 * 8矩阵中进行选择.因为我的声誉低于10,所以我无法添加图片,但请放心,它只是一个普通的8 * 8矩阵.我计划在Java程序中使用8 * 8 = 64单选按钮将其可视化.用户一次只能选择一个单选按钮,这意味着所有64个按钮将属于同一按钮组.

I intend to write a program where I will give the user a choice to choose from a 8*8 matrix. Because my reputation is below 10 I can not include an image but rest assured its just a normal 8*8 matrix. I plan to visualize it in my Java program with 8*8=64 radio buttons. the user can choose only one radio button at a time so it means all 64 buttons will be of the same button group.

现在,我该如何管理动作侦听器?为64个单选按钮中的每个按钮设置64个单独的动作侦听器是不可能的(真的很累又无聊).由于所有64个单选按钮都在同一个按钮组中,我有什么办法可以设置仅一个事件监听器来检查选择了哪个按钮?

Now, how can I manage the action listeners? it is impossible (really tiresome and boring) to set up 64 individual action listener for each of the 64 radio buttons. since all 64 radio buttons are in the same button group, is there any way I can set up only one event listener to check which button is selected?

如果我提供的任何信息不清楚,请告诉我:)

If any of my given info is unclear then please let me know :)

PS :我正在使用Netbeans设计工具

PS: I am using Netbeans design tools

推荐答案

创建像

        JRadioButton[][] jRadioButtons = new JRadioButton[8][];
        ButtonGroup bg = new ButtonGroup();
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(8, 8));
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                JRadioButton btn = new JRadioButton();
                btn.addActionListener(listener);
                btn.setName("Btn[" + i + "," + j + "]");
                bg.add(btn);
                panel.add(btn);
                // can be used for other operations
                jRadioButtons[i][j] = btn;
            }
        }

这里所有JRadioButton都是单个ActionListener

Here is single ActionListener for all JRadioButtons

    ActionListener listener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JRadioButton btn = (JRadioButton) e.getSource();
            System.out.println("Selected Button = " + btn.getName());
        }
    };

这篇关于多个单选按钮的动作侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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