2009-08-30 85 views
2

我有一个jbutton,它在用鼠标点击时执行一个功能。这样做的编程我有这等功能jbutton.doClick()单击按钮但不执行功能

void clickButton(){ 
     backButton.doClick(); 
} 

当我运行clickButton()函数,我可以看到被压在JFrame中的后退按钮而是返回按钮相关的功能不会发生。当我用鼠标点击它的功能。我在这里做错了什么?

+0

为什么您在没有演示代码的情况下重新发布此问题以显示问题?我在最后一篇文章中告诉过你,使用doClick()方法没有什么特别之处,所以你必须在代码中遇到问题。发布一行代码对于我们解决您的问题毫无用处。发布SSCCE。如果您不知道SSCCE是什么,请使用Google搜索网页。 – camickr 2009-08-31 00:34:46

+0

你应该发布更多关于你的问题的信息。将代码分配给该按钮的代码(您说这些代码有时不起作用)。 – twolfe18 2009-08-31 00:35:55

+0

我相信addActionListener不太好用,但addItemListener的确出于某种原因。 – rogerdpack 2012-10-13 05:15:41

回答

0

你如何将逻辑附加到按钮?如果您正在使用ActionListener(或Action),它应该会触发。如果你正在使用别的东西(或许是MouseListener?),我不认为它会。

4

如果您有一个ActionListener附加到您的button,它会在您调用方法.doClick()时触发;

进行了抽样检测,以证明这一点:

public class Test implements ActionListener { 
    public Test() { 
    } 

    public void actionPerformed(ActionEvent e) { 
     System.out.println("The action have been performed"); 
    } 

    public static void main(String[] agrs) { 
     JButton but = new JButton(); 
     but.addActionListener(new Test()); 
     but.doClick(); 
    } 
} 
1

可以遍历该按钮的听众和手动调用它们。

KeyEventDispatcher keyEventDispatcher = new KeyEventDispatcher() { 
      @Override 
      public boolean dispatchKeyEvent(final KeyEvent e) { 
      if (e.getID() == KeyEvent.KEY_TYPED) { 
       System.out.println(e); 
       if (e.getKeyChar() == ' '){ 
        MouseEvent me = new MouseEvent(btnStop,MouseEvent.MOUSE_CLICKED,EventQueue.getMostRecentEventTime(),0,0,1,1,false); 
        for (MouseListener ml : btnStop.getMouseListeners()) ml.mouseClicked(me); 
       } 
      } 
      // Pass the KeyEvent to the next KeyEventDispatcher in the chain 
      return false; 
      } 
     }; 
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyEventDispatcher); 
}