Ano*_*181 3 java swing key-bindings jbutton
我想用这些目标制作一个程序:
1)创建JButton 2)使用KeyBindings将按钮附加到键("A"键)3)单击"A"时执行一些代码
这是我到目前为止的代码:
// Imports
Public class Test{
JButton button = new JButton();
//...
Test(){
button.getInputMap().put(KeyStroke.getKeyStroke("A"), "Pressed");
//...
}
// Where do I add the code that responds when button is pressed?
}
Run Code Online (Sandbox Code Playgroud)
现在,在按下按钮的哪个位置添加我希望它执行的代码?
我能想到的两种方式:
doClick()通过键绑定按钮即可.KeyBindingEg.java
import java.awt.event.*;
import javax.swing.*;
public class KeyBindingEg extends JPanel {
private JButton btnA = new JButton();
public KeyBindingEg() {
Action btnAction = new ActionOne("A");
Action keyBindingAction = new ActionTwo();
int condition = JLabel.WHEN_IN_FOCUSED_WINDOW;
InputMap inputmap = btnA.getInputMap(condition);
ActionMap actionmap = btnA.getActionMap();
final String aKeyPressed = "a key pressed";
inputmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), aKeyPressed );
actionmap.put(aKeyPressed, keyBindingAction);
// actionmap.put(aKeyPressed, btnAction); // one or the other, your choice
btnA.setAction(btnAction);
add(btnA);
}
private class ActionOne extends AbstractAction {
public ActionOne(String text) {
super(text);
}
@Override
public void actionPerformed(ActionEvent e) {
sharedMethod();
}
}
private class ActionTwo extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
btnA.doClick();
}
}
private void sharedMethod() {
System.out.println("Method called by either key bindings or action listener");
}
private static void createAndShowGui() {
JFrame frame = new JFrame("KeyBindingEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new KeyBindingEg());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1957 次 |
| 最近记录: |