[英]How do you simulate a full click with Java Swing?
我正在為現有的java swing應用程序實現一些鍵盤代碼,但我似乎無法通過鍵盤按下來執行映射到JButton的“mousePressed”動作和“mouseReleased”動作。 使用button.doClick()點擊“action_performed”沒有問題,是否有類似的功能來模擬鼠標按下? 先謝謝。
您可以使用Robot類模擬鼠標按下和鼠標操作。 它用於模擬,例如用於自動測試用戶界面。
但是如果你想分享按鈕和按鍵的“動作”,你應該使用Action
。 請參見如何使用操作 。
有關如何共享Button和Keypress的操作的示例:
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);
閱讀有關如何使用鍵綁定的鍵綁定的更多信息 。
考慮使用Robot
來模擬鍵盤按下和鼠標活動。
您可以為按鈕添加一個監聽器:
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();
}
});
}
}`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.