Hi all,

I have a JOptionPane with a YES button and a NO button. All I want to do is be able to press the left or right button on the keyboard to change the focus on the buttons. By using the mouse it works. Is there some kind of Listener I can use?

Here is my code :

int response = JOptionPane.showConfirmDialog(null,"Are you sure you want to exit","Exit?",


if(response == JOptionPane.YES_OPTION){
}else {
//do nothing

You could TRY a keylistener but I'm not sure that'll work out exactly like you want. There should already be a mechanism built in that changes components when tab is pressed. I would stick to that if I were you.

From Windows, usually hitting TAB will change focus between components. If you must use the arrow keys, you could add a KeyListener which changes the focus to the button components. I would probably make a new class and extend the JOptionPane

Copy and paste the code below to your Main class.
So call configureOptionPane() at your main method.
Also use UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE) to make enter follows focus.

public static void main(String[] args) {
   UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);
private static void configureOptionPane() {
        if(UIManager.getLookAndFeelDefaults().get("OptionPane.actionMap") == null)
            UIManager.put("OptionPane.windowBindings", new 
            Object[] {
                        "ESCAPE", "close",
                        "LEFT", "left",
                        "KP_LEFT", "left",
                        "RIGHT", "right",
                        "KP_RIGHT", "right"
                    ActionMap map = new ActionMapUIResource();
                    map.put("close", new OptionPaneCloseAction());
                    map.put("left", new OptionPaneArrowAction(false));
                    map.put("right", new OptionPaneArrowAction(true));
            ("OptionPane.actionMap", map);

    private static class OptionPaneCloseAction extends AbstractAction {
        public void actionPerformed(ActionEvent e) {
            JOptionPane optionPane = (JOptionPane) e.getSource();

    private static class OptionPaneArrowAction extends AbstractAction {
        private boolean myMoveRight;
        OptionPaneArrowAction(boolean moveRight) {
            myMoveRight = moveRight;
        public void actionPerformed(ActionEvent e) {
            JOptionPane optionPane = (JOptionPane) e.getSource();
            EventQueue eq = Toolkit.getDefaultToolkit().getSystemEventQueue();
            eq.postEvent(new KeyEvent(
                    (myMoveRight) ? 0 : InputEvent.SHIFT_DOWN_MASK,
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.