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.
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?
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.
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.
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");
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");
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With