Common Action Listener for 3 Buttons(3个按钮的通用动作监听器)
问题描述
我的代码设计有问题.我有 3 个按钮不在按钮组中.我想 - 基于选定的按钮 - 执行一个动作.现在该操作需要修改类中的对象.这意味着我不能使用内部类,因为它无法访问外部.如果我可以将事件侦听器添加到按钮组,这会容易得多,但正如我所见,我将需要每个单选按钮的事件处理程序,这是正确的吗?如果不是,我还能怎么做?谢谢
I am having trouble with the design of my code. I have 3 buttons not in a button group. I want to - based on the selected button - perform an action. Now the action requires a modification of an object in the class. This means i cannot use an inner class because this does not have access to the outer. If i could add an event listener to a button group this would be much easier but as i see it i will need an event handler for each radio button, is this correct? If not how else can i do it? Thanks
一个简单的例子
public class Test(){
RadioButton 1 = new RadoButton();
RadioButton 2 = new RadoButton();
RadioButton 3 = new RadoButton();
Object myObject = new Object();
public void clickEvent(){
if(1.isSelected()){
myObject.doOne();
}else if(2.isSelected()){
myObject.doTwo();
}.....
}
}
推荐答案
您可以为所有按钮设置相同的侦听器.
You can set the same listener to all your buttons.
伪代码:
radioButton1 = new RadioButton();
radioButton2 = new RadioButton();
radioButton3 = new RadioButton();
listener = new ActionListener() {
...
}
radioButton1.addActionListener(listener);
radioButton2.addActionListener(listener);
radioButton3.addActionListener(listener);
这篇关于3个按钮的通用动作监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:3个按钮的通用动作监听器


基础教程推荐
- Java Swing计时器未清除 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01