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!

Member Avatar for ztini

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");
		
		add(obj);
		add(ori);
		add(pro);
		add(msg);
	}
	
	private JButton createButton(String text, int key) {
		final JButton button = new JButton(text);
		button.setMnemonic(key);
		button.addKeyListener(this);
		button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				updateMessage(button.getText());
			}
		});
		return button;		
	}
	
	@Override
	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;
		}
		
	}

	@Override
	public void keyReleased(KeyEvent e) { }

	@Override
	public void keyTyped(KeyEvent e) { }
	
	private void updateMessage(String text) {
		msg.setText(text);
	}
	
	public static void main(String[] args) {
		JFrame frame = new JFrame("Button Test");
		frame.setLocation(600, 400);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.add(new ButtonTest());
		frame.pack();
		frame.setVisible(true);
	}
}

Just what I needed! Thanx so much!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.