Hi everybody,
I've been working with gui recently, and I need help with my JButtons. I need to figure out how to set a button on the keyboard to click that JBUtton. I.e. When i hit the enter key it picks say the third button on the list or something like that. I've tried .setMnemonic with VK_Enter, but it still requires the user to press ALT+Enter. Is there a way to make it so that just a simple "Enter" keystroke (Ascii value 13) click the button?

Thanx in advance!

You'll want each of your JButton's to have an actionlistener. In addition, you'll want to the parent component to have a keylistener. Something like this:

import java.awt.event.*;
import javax.swing.*;

public class ButtonTest extends JPanel implements KeyListener{

	private static final long serialVersionUID = 1L;
	private JLabel msg;
	private JButton obj, ori, pro;
	public ButtonTest() {
		obj = createButton("Object", KeyEvent.VK_O);
		ori = createButton("Oriented", KeyEvent.VK_R);
		pro = createButton("Programming", KeyEvent.VK_P);
		msg = new JLabel("Status Message");
	private JButton createButton(String text, int key) {
		final JButton button = new JButton(text);
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
		return button;		
	public void keyPressed(KeyEvent e) {
		switch(e.getKeyCode()) {
		case KeyEvent.VK_O: updateMessage(obj.getText()); break;
		case KeyEvent.VK_R: updateMessage(ori.getText()); break;
		case KeyEvent.VK_P: updateMessage(pro.getText()); break;

	public void keyReleased(KeyEvent e) { }

	public void keyTyped(KeyEvent e) { }
	private void updateMessage(String text) {
	public static void main(String[] args) {
		JFrame frame = new JFrame("Button Test");
		frame.setLocation(600, 400);
		frame.add(new ButtonTest());

Edited 5 Years Ago by ztini: n/a

This question has already been answered. Start a new discussion instead.