How to disable javax.swing.JButton in java?

Yatendra Goel picture Yatendra Goel · Oct 26, 2009 · Viewed 134.9k times · Source

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.

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

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

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

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

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

Edit:

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

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?

Answer

akf picture akf · Oct 26, 2009

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

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

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);
     }
   }
 );

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.