我已经注册了按钮的按键绑定(bind),并且我想对所有数字击键使用react。我可以为每个键(0-9)注册不同的事件,但这有点愚蠢。那么是否有可能在一次事件中处理所有这些事情呢?
这是我的代码,仅对小键盘上的键 0 使用react:
private void setKeyBindings() {
AbstractAction aa = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Here");
}
};
this.editButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD0, 0), "0");
this.editButton.getActionMap().put("0", aa);
}
谢谢
最佳答案
So is it possible to handle it all in one event?
您可以创建一个供所有绑定(bind)使用的事件监听器:
也许是这样的:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CalculatorPanel extends JPanel
{
private JTextField display;
public CalculatorPanel()
{
Action numberAction = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
// display.setCaretPosition( display.getDocument().getLength() );
System.out.println(e.getActionCommand());
display.replaceSelection(e.getActionCommand());
}
};
setLayout( new BorderLayout() );
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
add(buttonPanel, BorderLayout.CENTER);
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
button.setBorder( new LineBorder(Color.BLACK) );
button.setPreferredSize( new Dimension(30, 30) );
buttonPanel.add( button );
InputMap inputMap = buttonPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke(text), text);
inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
buttonPanel.getActionMap().put(text, numberAction);
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Calculator Panel");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( new CalculatorPanel() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
关于java - 如何设置在一个事件中处理所有数字笔划的键绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32957211/