java - 带有 ActionListener/MouseListener 的 JButton

标签 java jframe jbutton actionlistener mouselistener

是否可以创建一个同时具有 ActionListener 和 MouseListener 的 Jbutton

意思是我创建了一个按钮,然后当我按下它时(通过 actionListener)它改变了框架,这样在按下按钮之后我可以按下框架上的任何地方并且 MouseListener 将被使用。

JButton button = new JButton();//Creates Button
button.addActionListener(new ActionListener() {         
public void actionPerformed(ActionEvent e) {
    //Insert MouseListener
    //Then do something with mouseListener
}
}); 

这是当前代码:但是当我尝试单击按钮时它们现在处于同步状态,我无法第二次调用 mouseListener

    JButton button2 = new JButton("Click");
    button2.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            System.out.println("You clicked the button");
            newCube.stopCube();
        }

    });
    button2.addMouseListener(new java.awt.event.MouseAdapter()
    {
        public void mousePressed(java.awt.event.MouseEvent evt)
        {
            double x = evt.getX();
            double y = evt.getY();
            newCube.setCube(x,y);
        }
    });

最佳答案

如果你想通过点击来移动某些东西,你可以直接在那个节点上使用鼠标监听器,而不是在按钮上使用它。

要在按钮上同时添加 Action 监听器和鼠标监听器,您可以在按钮上使用 addActionListener 和 addMouseListener 方法。

查看 api 以获取有关这些方法的信息... http://docs.oracle.com/javase/7/docs/api/javax/swing/JButton.html

关于java - 带有 ActionListener/MouseListener 的 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22348685/

相关文章:

java - JButton 在计算机之间切换样式

java - 如何查看用户从 JList 中选择了什么?

java - TableCellEditor 设置新值时 TableCellRenderer 不改变值

java - 如何在Jframe中分离Jpanel

java - jframe中如何清除

java - JFrame 不会显示在 netbeans 平台中

java - JButton - 如何连接?

java - 我无法从 servlet 到 jsp 获取 json 对象。我能怎么做?

javascript - 如何从 java 使用 Javascript/AJAX 调用 HTML/PHP 中的 Web 服务

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?