gpt4 book ai didi

Java:我可以导入禁用 swing 组件的 Action 监听器吗?

转载 作者:行者123 更新时间:2023-12-01 22:44:59 24 4
gpt4 key购买 nike

我在名为 MyForm 的 JForm 扩展上有一个 JButton。该按钮执行相当长的代码。此代码中的“MyForm.this.setEnabled(false)”用于在执行按钮方法时禁用表单。 (随后是“MyForm.this.setEnabled(true)”。)

(我这样做是因为这是我找到的唯一解决方案,可以确保忽略按钮执行期间的任何鼠标单击。否则,我发现它们会排队并立即执行)。

我可以将此按钮的代码导出到其他文件,以便导入到各种其他表单中吗?

编辑:代码:

JButton myButton = new JButton("Button Text");
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
MyForm.this.setEnabled(false);
...
MyForm.this.setEnabled(true);
}
});

最佳答案

将要禁用的表单作为参数传递给监听器的构造函数:

public class FormDisablingActionListener implements ActionListener {
private final Form formToDisable;

public FormDisablingActionListener(Form formToDisable) {
this.formToDisable = formToDisable;
}

@Override
public void actionPerformed(ActionEvent e){
this.formToDisable.setEnabled(false);
...
this.formToDisable.setEnabled(true);
}
}

顺便说一句,这就是编译器在使用匿名类引用其外部类实例(就像您所做的那样)时为您生成的内容。

然后按以下方式使用它:

JButton myButton = new JButton("Button Text");
myButton.addActionListener(new FormDisablingActionListener(this));

关于Java:我可以导入禁用 swing 组件的 Action 监听器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25507649/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com