Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-6513213

JButton does not properly handle key events

XMLWordPrintable

      FULL PRODUCT VERSION :
      java version "1.7.0-ea"
      Java(TM) SE Runtime Environment (build 1.7.0-ea-b03)
      Java HotSpot(TM) Client VM (build 1.7.0-ea-b03, mixed mode, sharing)

      A DESCRIPTION OF THE PROBLEM :
      If the method JRootPane.setDefaultButton is used to define a default button then that button is triggered if the user press the enter key while focusing another button. This is not a direct violation of method spec. but one may assume that the focused button is triggered when enter key is pressed. For instance; if a JTextField is selected, then the current behavior is the correct one.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Attach two buttons to a frame, make one button the default button, use tab-button to focus the other button. Press enter. The unfocused/default button is triggered.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      The focused JButton should consume the key event. (similar to how a JTextArea consumes enter key events).
      ACTUAL -
      The unfocused/default JButton is triggered.

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      import java.awt.*;
      import java.awt.event.*;
      import javax.swing.*;

      public class Test5
      {
      public static void main(String ... args)
      {
      JButton ok = new JButton("OK");
      JButton cancel = new JButton("Cancel");

      ok.addActionListener(new ActionListener()
      {
      public void actionPerformed(ActionEvent aEvent)
      {
      System.out.println("ok pressed");
      }
      });

      cancel.addActionListener(new ActionListener()
      {
      public void actionPerformed(ActionEvent aEvent)
      {
      System.out.println("cancel pressed");
      }
      });

      JPanel panel = new JPanel(new BorderLayout());
      panel.add(cancel,BorderLayout.WEST);
      panel.add(ok,BorderLayout.EAST);

      JFrame f = new JFrame();
      f.add(new JTextField(60), BorderLayout.CENTER);
      f.add(panel, BorderLayout.SOUTH);
      f.pack();
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.getRootPane().setDefaultButton(ok);
      f.setVisible(true);
      }
      }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Do not use JRootPane.setDefaultButton ...

            shickeysunw Shannon Hickey (Inactive)
            ndcosta Nelson Dcosta (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: