2011-12-11 11 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 -equivalent-of-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(); 
      } 
     }); 
    } 
}` 
関連する問題