我需要在下一个示例中向按钮添加按键侦听器或按键绑定的帮助。我想在按键盘上的A或B时做出与用鼠标按下时相同的操作。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class NetTest {
static JButton btnA = new JButton("A");
static JButton btnB = new JButton("B");
static JPanel jp = new JPanel();
static JFrame jf = new JFrame("Test APP");
static JLabel jl = new JLabel("Which button was clicked ?");
static ActionListener action = new ActionListener() {
public void actionPerformed(ActionEvent e) {
jl.setText(((JButton)e.getSource()).getText());
}
};
public static void main(String[] args) {
jf.setVisible(true);
jf.setSize(400, 400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jp.add(btnA);
jp.add(btnB);
jp.add(jl);
jf.add(jp);
btnA.addActionListener(action);
btnB.addActionListener(action);
}
}
为了进行监听,KeyEvents
您需要使用JComponent#getInputMap()和JComponent#getActionMap()方法来放置要监听的输入事件和相应的动作。试试这个例子:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Demo{
private void initGUI(){
AbstractAction buttonPressed = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
};
JButton submit = new JButton("Submit");
submit.addActionListener(buttonPressed);
/*
* Get the InputMap related to JComponent.WHEN_IN_FOCUSED_WINDOW condition
* to put an event when A key is pressed
*/
submit.getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).
put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A,0), "A_pressed");
/*
* Add an action when the event key is "A_pressed"
*/
submit.getActionMap().put("A_pressed", buttonPressed);
/*
* Same as above when you press B key
*/
submit.getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).
put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B,0), "B_pressed");
submit.getActionMap().put("B_pressed", buttonPressed);
JPanel content = new JPanel(new FlowLayout());
content.add(new JLabel("Test:"));
content.add(submit);
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(content);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Demo().initGUI();
}
});
}
}
注意:在按下或A / B键AbstractAction
时,此示例使用相同的示例JButton
,但输出将取决于事件源是谁。
注意2:如果使用JComponent.WHEN_IN_FOCUSED_WINDOW
条件,则只要按A或B键就可以执行操作。当您有文本输入组件(例如JTextfield
或),JTextArea
并且最终用户几乎可以肯定会多次按下A或B键时,就不会出现这种情况。如果是这种情况,则必须使用JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
条件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句