开发者

addMouseListener or addActionListener or JButton?

开发者 https://www.devze.com 2023-01-13 19:24 出处:网络
When defining the behaviour of a simple clic开发者_运维知识库k on a JButton, which is the right way to do it? And, what\'s the difference?

When defining the behaviour of a simple clic开发者_运维知识库k on a JButton, which is the right way to do it? And, what's the difference?

JButton but = new JButton();
but.addActionListener(new ActionListener() {          
    public void actionPerformed(ActionEvent e) {
         System.out.println("You clicked the button, using an ActionListener");
    }
}); 

or

JButton but = new JButton();
but.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
        System.out.println("You clicked the button, using a MouseListenr");
    }
});


MouseListener is a low-level event listener in Swing (and AWT by the way).

ActionListener is higher-level and should be used.

Better than ActionListener though, one should use a javax.swing.Action (which is actually an ActionListener).

Using an Action allows to share it among several widgets (eg JButton, JMenuItem...); not only do you share the code that is triggered when the button/menu is pushed, but also the state is shared, in particular the fact whether the action (and its associated widgets) is enabled or not.


You should be able to press that button using keyboard also. So, if you add just the mouse listener you will not get the 'press' event if using keyboard.

I would go for the action listener, it's more clear.


A registered ActionListener is invoked when the Button fires an Action event, the MouseListener is invoked when the widget detects a mouse click.

In your example both approaches show the same behaviour when you use a mouse to click on the button. But give focus to the button and press SPACE, this should fire an action event and trigger the Action Listener but not the mouse listener.

It is advisable to use the ActionListener on Buttons, otherwise you'll not be able to control the application with a keyboard or you would be in the need to add another key event listener.


If you want to do something when a Jbutton is clicked, action listener is better because mouse listener does not recognize that a mouse is clicked on a button if a user presses the mouse on a JButton and then moves the mouse a little bit before releasing the mouse button while remaining within the button the whole time, but action listener does. MouseListener requires that mouse clicks have no movement between mouse press and mouse release, which is not the case for my users.

0

精彩评论

暂无评论...
验证码 换一张
取 消