本文介绍了带有ActionListener/MouseListener的JButton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以同时创建ActionListener和MouseListener的Jbutton

Is it possible to create a Jbutton with both an ActionListener and MouseListener

意思是我创建了一个按钮,然后按它(通过actionListener)时,它改变了框架,以便在按下按钮之后,我可以按一下框架上的任何位置,并且将使用MouseListener.

Meaning so i create a button and then when i press it ( throught actionListener) it changes the frame so that AFTER then button was pressed i can press anywhere on the frame and MouseListener would in use.

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

这里有当前代码:但是,当我尝试单击按钮并且我无法第二次调用mouseListener时,它们现在已同步

Heres the curent code: however they're now in sync when i try to click the button and i cannot call mouseListener a 2nd time

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

推荐答案

对我来说,您仍然想做些什么.虽然这可以帮助您.单击开始按钮时,它将在组件中添加鼠标列表器,单击停止按钮时,将删除鼠标列表器.因此,您可以阻止两个侦听器同步工作.

What you want to do is still not clear to me. Though this can help you. It will add a mouse listner to the component when the start button is clicked and remove the mouse listner when stop button is clicked. Thus you can stop the two listeners from working in sync..

JButton startButton = new JButton();

startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

   //Add MouseListener to move the component

}
});

JButton stopButton = new JButton();

stopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

   //Remove the MouseListener

}
});

这篇关于带有ActionListener/MouseListener的JButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 07:01