Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...