How to enable / disable buttons in java, eclipse?
How about using Command
objects? Each command object might have execute()
and canExecute()
methods at least. Then;
btnA.setEnabled( cmdA.canExecute() );
btnA.addActionListener( event-> {
cmdA.execute();
btnB.setEnabled( cmdA.canExecute() );
});
Admin
Updated on October 28, 2020Comments
-
Admin over 3 years
How can I disable buttons with the press of one button and when the task that the button which has been pressed was assigned to has been done then I want all the buttons to be enabled. for example;
UpButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { DownButton.setEnabled(false); LeftButton.setEnabled(false); RightButton.setEnabled(false); System.out.printline("Up Button"); } }); DownButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { UpButton.setEnabled(false); LeftButton.setEnabled(false); RightButton.setEnabled(false); System.out.printline("Down Button"); } }); LeftButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { DownButton.setEnabled(false); UpButton.setEnabled(false); RightButton.setEnabled(false); System.out.printline("Left Button"); } }); RightButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { DownButton.setEnabled(false); LeftButton.setEnabled(false); UpButton.setEnabled(false); System.out.printline("Right Button"); } });
I have tried to do it but it does not work. What I want is, for example, my Upbutton is printing out ("Up button"), so when a user presses this button I want all the other buttons to be disabled until it has finished doing the command that it was suppose to do, in this case print out a text but later on I will be adding things like adding up two user inputs e.g. I will have a button that will ask the user to type number 1 and then number 2 and then the computer will add them up and during this process I want all the buttons to be disabled expect the one that has been clicked on, until the user has given all numbers and the computer has given the output.
I hope I have explained myself properly, if not please let me know and I will try my best to give more information. Thanks in advance.
-
Admin over 10 yearsHi, Rafael both with my method DownButton.setEnabled(false); and your method DownButton.setVisible(false); it says the buttons cannot be resolved. I want the buttons to be visible but disabled if one button is pressed.
-
Rafael Carvalhido over 10 yearsAre the buttons declared(private javax.swing.JButton UpButton;)? Have you imported javax.swing.JButton? Probably so, right?