如何在java中禁用javax.swing.JButton? [英] How to disable javax.swing.JButton in java?

查看:1727
本文介绍了如何在java中禁用javax.swing.JButton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个swings应用程序,GUI上有一个开始按钮。我希望每当我点击开始按钮时,应该禁用启动按钮并启用停止按钮。

I have created a swings application and there is a "Start" button on the GUI. I want that whenever I clicked on that "Start" button, the start button should be disabled and the "Stop" button be enabled.

为此,我写了以下内容开始按钮的ActionPeformed(...)方法中的代码

For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button

startButton.setEnabled(false);
stopButton.setEnabled(true);

但是上面的代码没有在GUI上创建所需的效果。

But the above code is not creating the desired affect on the GUI.

以上代码是否符合我的要求?

Is the above code correct for what I want to do?

它也不适用于repaint()。

It's not working with "repaint()" too.

编辑:

代码很长,所以我无法粘贴所有代码。我可以告诉我更多关于代码的信息。

The code is very long so I can't paste all the code. I can tell, though, more about the code.

在开始按钮的ActionPeformed方法中,在调用上述两个语句后,我正在执行 SwingWorkerthread。

In the "ActionPeformed" method of "start" button, after calling the above two statements, I am executing a "SwingWorker" thread.

这个线程是否会产生任何问题?

Is this thread creating any problem?

推荐答案


为此,我在开始按钮的ActionPeformed(...)方法中编写了以下代码

For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button

您需要该代码位于 ActionListener 注册的 actionPerformed(...)中使用开始按钮,而不是开始按钮本身。

You need that code to be in the actionPerformed(...) of the ActionListener registered with the Start button, not for the Start button itself.

您可以添加一个简单的 ActionListener ,如下所示: / p>

You can add a simple ActionListener like this:

JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent ae) {
        startButton.setEnabled(false);
        stopButton.setEnabled(true);
     }
   }
 );

请注意,上面的startButton需要 final 在上面的示例中,如果要在本地范围内创建匿名侦听器。

note that your startButton above will need to be final in the above example if you want to create the anonymous listener in local scope.

这篇关于如何在java中禁用javax.swing.JButton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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