How can I verify that JButton is clicked? If isEnable () doesn't work?

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.

  • This code has 2 buttons, which are the “Add” and “Place an order” buttons.
  • The code will show the message “Add Click” when I click the “Checkout” button after clicking the “Add” button, but if the “Add” button was not pressed before clicking the “Checkout” button, the code will display the message “Add button not pressed”.

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?

+4
5

JButton model, :

  • isArmed(),
  • isPressed(),
  • isRollOVer()

... , , :

     if(jButton1.getModel().isPressed())
        System.out.println("the button is pressed");
+12

, 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");
    }
});
+3

JButton#isEnabled , , ( ) .

JButton actionPerformed.

Add button is pressed, , . , .

, "" ActionListener, , , ActionListener.

, , JCheckBox, JCheckBox#isSelected, , .

.

+2

System.out.println(e.getActionCommand()); actionPerformed(ActionEvent e). , .

if(e.getActionCommand().equals("Add")){

   System.out.println("Add button pressed");
}
+1

, , :

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

0
source

All Articles