addMouseListener or addActionListener or JButton?

前端 未结 4 836
小蘑菇
小蘑菇 2021-01-18 14:24

When defining the behaviour of a simple click on a JButton, which is the right way to do it? And, what\'s the difference?

JButton but = new JButton();
but.ad         


        
4条回答
  •  盖世英雄少女心
    2021-01-18 15:02

    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.

提交回复
热议问题