在我的swing程序中,我有一个JTextField和一个JButton。我想,一旦用户按下“回车”键,JButton的actionListener就会运行。我该怎么办? 提前致谢。
在我的swing程序中,我有一个JTextField和一个JButton。我想,一旦用户按下“回车”键,JButton的actionListener就会运行。我该怎么办? 提前致谢。
JRootPane有一个方法setDefaultButton(JButton按钮),可以做你想要的。如果您的应用程序是JFrame,它会实现RootPaneContainer接口,您可以通过在JFrame上调用getRootPane()来获取根窗格,然后在返回的根窗格上调用setDefaultButton。相同的技术适用于JApplet,JDialog或任何其他实现RootPaneContainer的类。
这里有一个例子
http://www.java2s.com/Code/Java/Swing-JFC/SwingDefaultButton.htm
这就是你需要的:rootPane.setDefaultButton(button2);
摆脱ActionListeners。这是做听众的旧风格。毕业于Action课程。诀窍是了解InputMaps和ActionMaps的工作原理。这是Swing的一个独特功能,非常好用:
http://download.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
这是你如何做到的:
JPanel panel = new JPanel();
panel.setLayout( new TableLayout( ... ) );
Action someAction = new AbstractAction( "GO" ) {
public void actionPerformed() {
}
};
InputMap input = panel.getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
input.put( KeyStroke.getKeyStroke( "enter", "submit" );
panel.getActionMap().put("submit", someAction );
panel.add( button = new JButton( someAction ) );
panel.add( textField = new JTextField( ) );
使用WHEN_ANCESTOR_OF_FOCUSED_COMPONENT允许面板从其任何子节点(即祖先)接收键盘事件。因此,无论哪个组件具有焦点,只要它在面板内部,按键将调用在ActionMap中的“submit”下注册的任何动作。
这允许您通过共享操作来重复使用菜单,按钮或击键中的操作。