【发布时间】:2015-11-09 02:27:48
【问题描述】:
我在另一个问题中找到了一种很酷的方法来创建一个 JButton,它的动作以一种简单的方式编写和查看:
public JButton makeToolbarButton(String title, String actionCommand) {
JButton button = new JButton(title);
button.setActionCommand(actionCommand);
button.addActionListener(this);
return button;
}
该方法所在的类实现了ActionListener,按钮命令由:
public void actionPerformed(ActionEvent e) {
int action = Integer.parseInt(e.getActionCommand());
switch(action) {
case 1:
System.out.println("This button pressed.");
break;
}
}
按钮的制作者:
JButton button1 = makeToolbarButton("Button 1", "1");
所以我的问题是:我可以通过这种方法将 KeyStrokes 添加到按钮吗?我尝试过这样的事情(在makeToolbarButton 方法内):
button.getInputMap().put(KeyStroke.getKeyStroke("B"), "button_pressed");
button.getActionMap().put("button_pressed", button.getAction());
但我认为这不起作用,因为操作命令实际上并未将操作分配给特定按钮。有没有办法在 makeToolbarButton() 方法和 KeyStroke 的参数中添加一些东西来完成这个?
【问题讨论】:
-
button.getAction()不起作用,因为您没有为按钮分配Action。
标签: java swing action keymapping