Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check that JButton is pressed? If the isEnable() is not work?

How can I check that JButton is pressed? I know that there is a method that its name is "isEnabled"

So I try to write a code to test.

  1. this code have 2 Jbuttons which are "Add" Button and "Checkout" button.
  2. the code will show the "Add button is pressed" message when I press "Checkout" button after I press "Add" button but If the "Add" Button is not pressed before the "Checkout" Button is pressed, the code will show the "Add Button is not pressed" message.

Here 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 give only the " Add button is pressed" although I didn't press the "Add" Button. Why does it occur like that?

like image 467
Dexter Moregan Avatar asked Dec 27 '13 10:12

Dexter Moregan


People also ask

Which method is used to change the text displayed in JButton?

By default, we can create a JButton with a text and also can change the text of a JButton by input some text in the text field and click on the button, it will call the actionPerformed() method of ActionListener interface and set an updated text in a button by calling setText(textField.

Which event is generated by JButton?

A JButton object draws itself and processes mouse, keyboard, and focus events on its own. You only hear from the JButton when the user triggers it by clicking on it or pressing the space bar while the button has the input focus. When this happens, the JButton object creates an event object belonging to the class java.


2 Answers

JButton has a model which answers these question:

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

etc. Hence you can ask the model for the answer you are seeking:

     if(jButton1.getModel().isPressed())
        System.out.println("the button is pressed");
like image 86
Sage Avatar answered Nov 14 '22 22:11

Sage


Seems you need to use 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");
    }
});
like image 22
alex2410 Avatar answered Nov 14 '22 21:11

alex2410