2011-12-11 33 views
5

我正在爲現有的java swing應用程序實現一些鍵盤代碼,但我似乎無法獲得鍵盤按下來執行映射到JButton的「mousePressed」動作和「mouseReleased」動作。我沒有任何問題點擊button.doClick()的「action_performed」,有沒有類似的功能來模擬鼠標按下?事先感謝。如何用Java Swing模擬完整點擊?

+0

檢查這個http://stackoverflow.com/questions/2445105/how-do-you-simulate-a-click-on-a-jtextfield換算後的-的-JButton的-doclick – doNotCheckMyBlog

回答

6

可以模擬鼠標按下和鼠標操作使用Robot類。它是爲模擬例如用於自動測試用戶界面。

但是,如果你想分享「行動」,例如,按鈕和按鍵,您應該使用Action。見How to Use Actions。關於如何分擔訴訟,要求一個按鈕和一個按鍵

例子:

Action myAction = new AbstractAction("Some action") { 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     // do something 
    } 
}; 

// use the action on a button 
JButton myButton = new JButton(myAction); 

// use the same action for a keypress 
myComponent.getInputMap().put(KeyStroke.getKeyStroke("F2"), "doSomething"); 
myComponent.getActionMap().put("doSomething", myAction);  

瞭解更多關於鍵綁定上How to Use Key Bindings

2

你可以監聽器添加到您的按鈕:

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JFrame; 

public class ButtonAction { 

private static void createAndShowGUI() { 

    JFrame frame1 = new JFrame("JAVA"); 
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    JButton button = new JButton(" >> JavaProgrammingForums.com <<"); 
    //Add action listener to button 
    button.addActionListener(new ActionListener() { 

    public void actionPerformed(ActionEvent e) 
    { 
     //Execute when button is pressed 
     System.out.println("You clicked the button"); 
     } 
    });  

    frame1.getContentPane().add(button); 
    frame1.pack(); 
    frame1.setVisible(true); 
} 


public static void main(String[] args) { 
    javax.swing.SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       createAndShowGUI(); 
      } 
     }); 
    } 
}`