JPanel动作侦听器 [英] JPanel Action Listener

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

问题描述

我有一个带有一堆不同复选框和文本字段的JPanel,我有一个禁用的按钮,需要在设置特定配置时启用。
我需要的是整个JPanel上的监听器,只要有任何变化,就会查找事件。
我相信我需要一个动作监听器,但我找不到任何东西来连接监听器与JPanel的动作

I have a JPanel with a bunch of different check boxes and text fields, I have a button that's disabled, and needs to be enabled when specific configurations are setup. What I need is a listener on the the whole JPanel looking for events, whenever anything changes. I believe I need an action listener but I can't find anything to bridge the action Listener with the JPanel

JPanel Window = new JPanel();
Window.addActionListener(new ActionListener(){
//Check if configurations is good
}

我想我可以将代码复制并粘贴到面板中的每个监听器中,但这对我来说似乎是不好的编码习惯。

I figure I can copy and paste my code a bunch of times into every listener in the panel, but that seems like bad coding practice to me.

推荐答案

首先在他的评论中提及@Sage JPanel 是一个容器而不是一个做动作的组件。所以你不能附上一个 ActionListener JPanel

First off as @Sage mention in his comment a JPanel is rather a container than a component which do action. So you can't attach an ActionListener to a JPanel.


我想我可以将我的代码复制并粘贴到面板中的每个
监听器中,但这对我来说似乎是糟糕的编码习惯。

I figure I can copy and paste my code a bunch of times into every listener in the panel, but that seems like bad coding practice to me.

你是完全正确的,这根本不是一个好习惯(参见 DRY原则)。而不是你可以只定义一个 ActionListener 并将它附加到你的 JCheckBox es,如下所示:

You're totally right about that, it's not a good practice at all (see DRY principle). Instead of that you can define just a single ActionListener and attach it to your JCheckBoxes like this:

final JCheckBox check1 = new JCheckBox("Check1");
final JCheckBox check2 = new JCheckBox("Check2");
final JCheckBox check3 = new JCheckBox("Check3");

final JButton buttonToBeEnabled = new JButton("Submit");
buttonToBeEnabled.setEnabled(false);

ActionListener actionListener = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        boolean enable = check1.isSelected() && check3.isSelected();
        buttonToBeEnabled.setEnabled(enable);
    }
};

check1.addActionListener(actionListener);
check2.addActionListener(actionListener);
check3.addActionListener(actionListener);

这意味着:如果 check1 check3 都被选中,然后必须启用该按钮,否则必须禁用。当然,只有你知道应该选择哪些复选框组合才能设置按钮。

This means: if check1 and check3 are both selected, then the button must be enabled, otherwise must be disabled. Of course only you know what combination of check boxes should be selected in order to set the button enabled.

看看如何使用按钮,复选框和单选按钮教程。

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

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