addMouseListener将或addActionListener方法或JButton的? [英] addMouseListener or addActionListener or JButton?

查看:2458
本文介绍了addMouseListener将或addActionListener方法或JButton的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在定义上一个JButton一个简单的点击,这是做的正确方法的行为?而且,有什么区别?

 的JButton但是=的新的JButton();
but.addActionListener(新的ActionListener(){
    公共无效的actionPerformed(ActionEvent的五){
         的System.out.println(你单击该按钮,使用一个ActionListener);
    }
});

 的JButton但是=的新的JButton();
but.addMouseListener(新java.awt.event.MouseAdapter(){
    公共无效的mouseClicked(java.awt.event.MouseEvent中EVT){
        的System.out.println(你单击该按钮,使用MouseListenr);
    }
});


解决方案

的MouseListener 是在Swing(以及AWT的方式)一个低级别的事件侦听器。

的ActionListener 是更高层次的,应该被使用。

的ActionListener 更好虽然,人们应该使用 javax.swing.Action中的(这实际上是一个<$是C $ C>的ActionListener )。

使用动作允许几个小部件(如的JButton 的JMenuItem间共享 ...);你不仅共享code当按钮/菜单被按下时触发,而且状态是共享的,特别是事实上的动作(及其相关部件)是否被启用与否。

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.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.

这篇关于addMouseListener将或addActionListener方法或JButton的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆