Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable javax.swing.JButton in java?

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?

like image 219
Yatendra Avatar asked Oct 26 '09 16:10

Yatendra


People also ask

What is javax swing JButton?

The class JButton is an implementation of a push button. This component has a label and generates an event when pressed. It can also have an Image.

How do you disable and enable a button in Java?

addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { // first disable all other buttons DownButton. setEnabled(false); LeftButton. setEnabled(false); RightButton. setEnabled(false); System.


1 Answers

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.

like image 122
akf Avatar answered Oct 14 '22 18:10

akf