How to check that JButton is pressed? I know that there is a method that has the name "isEnabled"
Therefore, I am trying to write code for testing.
Here is the code:
final JButton btnAdd = new JButton("Add"); btnAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { } }); panel.add(btnAdd); JButton btnConfirm = new JButton("Check Out"); btnConfirm.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (btnAdd.isEnabled()) { System.out.println("Add Button is pressed"); } if (!btnAdd.isEnabled()) { System.out.println("Add Button is not pressed"); } } });
When I run this code, the code only gives the Add button, although I did not click the Add button. Why is this happening like this?
JButton model, :
JButton
isArmed()
isPressed()
isRollOVer()
... , , :
if(jButton1.getModel().isPressed()) System.out.println("the button is pressed");
, JToggleButton:
JToggleButton
JToggleButton tb = new JToggleButton("push me"); tb.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JToggleButton btn = (JToggleButton) e.getSource(); btn.setText(btn.isSelected() ? "pushed" : "push me"); } });
JButton#isEnabled , , ( ) .
JButton#isEnabled
JButton actionPerformed.
actionPerformed
Add button is pressed, , . , .
Add button is pressed
, "" ActionListener, , , ActionListener.
ActionListener
, , JCheckBox, JCheckBox#isSelected, , .
JCheckBox
JCheckBox#isSelected
.
System.out.println(e.getActionCommand()); actionPerformed(ActionEvent e). , .
System.out.println(e.getActionCommand());
actionPerformed(ActionEvent e)
if(e.getActionCommand().equals("Add")){ System.out.println("Add button pressed"); }
, , :
btnAdd.isEnabled()
When enabled, any component associated with this object is active and is able to run this method of the actionPerformed object.
This method does not check if a button is pressed.
If I understand your question correctly, you want to disable the "Add" button after the user clicks "Departure".
Try disabling your button at startup: btnAdd.setEnabled(false)or after the user clicks the Check Out button
btnAdd.setEnabled(false)