In my swing program I have a JTextField and a JButton. I would like for, once the user presses the "enter" key, the actionListener of the JButton runs. How would I do this? Thanks in advance.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
there is an example here
http://www.java2s.com/Code/Java/Swing-JFC/SwingDefaultButton.htm
this is what you need: rootPane.setDefaultButton(button2);
Get rid of ActionListeners. That's the old style for doing listeners. Graduate to the Action class. The trick is to understand InputMaps and ActionMaps work. This is a unique feature of Swing that is really quite nice:
http://download.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
Here's how you do it:
Using the WHEN_ANCESTOR_OF_FOCUSED_COMPONENT allows the panel to receive keyboard events from any of it's child (i.e. ancestors). So no matter what component has focus as long as it's inside the panel that keystroke will invoke any action registered under "submit" in the ActionMap.
This allows you to reuse Actions in menus, buttons, or keystrokes by sharing them.
JRootPane has a method setDefaultButton(JButton button) that will do what you want. If your app is a JFrame, it implements the RootPaneContainer interface, and you can get the root pane by calling getRootPane() on the JFrame, and then call setDefaultButton on the root pane that was returned. The same technique works for JApplet, JDialog or any other class that implements RootPaneContainer.