Default buttons in Swing

I've done this before but can't remember how now. How can I make a JButton the "default" button in a JFrame, such that if I hit enter while keyboard focus is on any component in the frame (that doesn't intercept the Enter keystroke itself), it's the same as clicking the button with the mouse?

hi,
if you are working with keyboard you need to have a keytyped-method. So if the return-key is pressed just only work with this button.
example:// ...
JButton jb=new JButton("Press Return");
public void keyTyped(KeyEvent e){
  if(e.getKeyCode()==// the variable for return)
    // do whatever the button should do
}regards

Similar Messages

  • Cursor becomes invisible in JTextField after using default button

    In my application there is an update screen (JPanel). I am using default button in that panel. The input field is a normal JTextField. When the update is over the cursor goes back to the input JTextField.
         Now my problem is that when I carry out update with mouse, the cursor is correctly placed into the input JTextField and is visible after the update is over. On the other hand, if I carry out the same update operation using default button (using keyboard), the cursor gets placed correctly in the input JTextfield column, but becomes invisible. If I minimize and then again maximize the window, the cursor appears back. What am I missing ? Note that I am using component.requestFocusInWindow() to get focus back to the input JTextField.
    regards,
    nirvan

    While trying to reproduce the behaviour for SSCCE, I found that it is the JOptionPane.showMessageDialog() that is causing the problem. Here is the SSCCE.
    package com.ns;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.WindowConstants;
    public class TestFocus extends javax.swing.JFrame {
        // Variables declaration - do not modify
        private JTextField field1;
        private JTextField field2;
        private JPanel jPanel1;
        private JButton reset;
        private JButton update;
        // End of variables declaration
        public TestFocus() {
            initComponents();
            setDefaultButton();
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jPanel1 = new JPanel();
            field1 = new JTextField();
            field2 = new JTextField();
            update = new JButton();
            reset = new JButton();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            field1.setPreferredSize(new Dimension(40, 20));
            jPanel1.add(field1);
            field2.setPreferredSize(new Dimension(40, 20));
            jPanel1.add(field2);
            update.setText("Update");
            update.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    updateActionPerformed(evt);
            jPanel1.add(update);
            reset.setText("Reset");
            reset.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    resetActionPerformed(evt);
            jPanel1.add(reset);
            getContentPane().add(jPanel1, BorderLayout.CENTER);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-385)/2, (screenSize.height-258)/2, 385, 258);
        }// </editor-fold>
        public void setDefaultButton(){
            this.getRootPane().setDefaultButton(update);
        private void updateActionPerformed(ActionEvent evt) {
            // TODO add your handling code here:
            JOptionPane.showMessageDialog(this,"Activity Updated Succesfully in Database.",
                                            "Information",
                                            JOptionPane.INFORMATION_MESSAGE);
            update.setEnabled(false);
            field1.setEditable(false);
            reset.setEnabled(true);
            this.getRootPane().setDefaultButton(reset);
        private void resetActionPerformed(ActionEvent evt) {
            // TODO add your handling code here:
            field1.requestFocusInWindow();
            field1.setText("");
            field1.setEditable(true);
            reset.setEnabled(false);
            update.setEnabled(true);
            this.getRootPane().setDefaultButton(update);
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TestFocus().setVisible(true);
    }If I remove the JOptionPane.showMessageDialog() method, everything works fine with mouse as well as keyboard.
    regards,
    nirvan.

  • Default button being clicked multiple times when enter key is pressed

    Hello,
    There seems to be a strange difference in how the default button behaves in JRE 1.4.X versus 1.3.X.
    In 1.3.X, when the enter key was pressed, the default button would be "pressed down" when the key was pressed, but wouldn't be fully clicked until the enter key was released. This means that only one event would be fired, even if the enter key was held down for a long time.
    In 1.4.X however, if the enter key is pressed and held for more than a second, then the default button is clicked multiple times until the enter key is released.
    Consider the following code (which is just a dialog with a button on it):
    public class SimpleDialog extends JDialog implements java.awt.event.ActionListener
    private JButton jButton1 = new JButton("button");
    public SimpleDialog()
    this.getContentPane().add(jButton1);
    this.getRootPane().setDefaultButton(jButton1);
    jButton1.addActionListener(this);
    this.pack();
    public void actionPerformed(ActionEvent e)
    if (e.getSource() == jButton1)
    System.out.println("button pressed");
    public static void main(String[] args)
    new SimpleDialog().show();
    When you compile and run this code under 1.3.1, and hold the enter key down for 10 seconds, you will only see one print line statement.
    However, if you compile and run this code under 1.4.1, and then hold the enter key down for 10 seconds, you will see about 100 print line statements.
    Is this a bug in 1.4.X or was this desired functionality (e.g. was it fixing some other bug)?
    Does anyone know how I can make it behave the "old way" (when the default button was only clicked once)?
    Thanks in advance if you have any advice.
    Dave

    Hello all,
    I think I have found a solution. The behaviour of the how the default button is triggered is contained withing the RootPaneUI. So, if I override the default RootPaneUI used by the UIDefaults with my own RootPaneUI, I can define that behaviour for myself.
    Here is my simple dialog with a button and a textfield (when the focus is NOT on the button, and the enter key is pressed, I don't want the actionPerformed method to be called until the enter key is released):
    package focustests;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    public class SimpleDialog extends JDialog implements java.awt.event.ActionListener
    private JButton jButton1 = new JButton("button");
    public SimpleDialog()
    this.getContentPane().add(new JTextField("a text field"), BorderLayout.NORTH);
    this.getContentPane().add(jButton1, BorderLayout.SOUTH);
    this.getRootPane().setDefaultButton(jButton1);
    jButton1.addActionListener(this);
    this.pack();
    public void actionPerformed(ActionEvent e)
    if (e.getSource() == jButton1)
    System.out.println("button pressed");
    public static void main(String[] args)
    javax.swing.UIManager.getDefaults().put("RootPaneUI", "focustests.MyRootPaneUI");
    new SimpleDialog().show();
    and the MyRootPaneUI class controls the behaviour for how the default button is handled:
    package focustests;
    import javax.swing.*;
    * Since we are using the Windows look and feel in our product, we should extend from the
    * Windows laf RootPaneUI
    public class MyRootPaneUI extends com.sun.java.swing.plaf.windows.WindowsRootPaneUI
    private final static MyRootPaneUI myRootPaneUI = new MyRootPaneUI();
    public static javax.swing.plaf.ComponentUI createUI(JComponent c) {
    return myRootPaneUI;
    protected void installKeyboardActions(JRootPane root) {
    super.installKeyboardActions(root);
    InputMap km = SwingUtilities.getUIInputMap(root,
    JComponent.WHEN_IN_FOCUSED_WINDOW);
    if (km == null) {
    km = new javax.swing.plaf.InputMapUIResource();
    SwingUtilities.replaceUIInputMap(root,
    JComponent.WHEN_IN_FOCUSED_WINDOW, km);
    //when the Enter key is pressed (with no modifiers), trigger a "pressed" event
    km.put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ENTER,
    0, false), "pressed");
    //when the Enter key is released (with no modifiers), trigger a "release" event
    km.put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ENTER,
    0, true), "released");
    ActionMap am = SwingUtilities.getUIActionMap(root);
    if (am == null) {
    am = new javax.swing.plaf.ActionMapUIResource();
    SwingUtilities.replaceUIActionMap(root, am);
    am.put("press", new HoldDefaultButtonAction(root, true));
    am.put("release", new HoldDefaultButtonAction(root, false));
    * This is a copy of the static nested class DefaultAction which was
    * contained in the JRootPane class in Java 1.3.1. Since we are
    * using Java 1.4.1, and we don't like the way the new JRE handles
    * the default button, we will replace it with the old (1.3.1) way of
    * doing things.
    static class HoldDefaultButtonAction extends AbstractAction {
    JRootPane root;
    boolean press;
    HoldDefaultButtonAction(JRootPane root, boolean press) {
    this.root = root;
    this.press = press;
    public void actionPerformed(java.awt.event.ActionEvent e) {
    JButton owner = root.getDefaultButton();
    if (owner != null && SwingUtilities.getRootPane(owner) == root) {
    ButtonModel model = owner.getModel();
    if (press) {
    model.setArmed(true);
    model.setPressed(true);
    } else {
    model.setPressed(false);
    public boolean isEnabled() {
    JButton owner = root.getDefaultButton();
    return (owner != null && owner.getModel().isEnabled());
    This seems to work. Does anyone have any comments on this solution?
    Tjacobs, I still don't see how adding a key listeners or overriding the processKeyEvent method on my button would help. The button won't receive the key event unless the focus is on the button. There is no method "enableEvents(...)" in the AWTEventMulticaster. Perhaps you have some code examples? Thanks anyway for your help.
    Dave

  • Shortcut on Button in swing

    Dear Sir,
    Can i get help from you any one to create shortcut on button in swing like press ENTER to process.
    I am so worried that how do it.
    I am waiting so anxiously for u reply.
    Regards,
    Shah Jehan

    If it is not a default button - use mnemonic.
    Default button reacts on "Enter" key press. Use JRootPane.setDefaultButton(), and JButton.requestFocusInWindow() if needed.

  • Default buttons not defaulting

    Hello. I am on the tail end of a DVD project and just begain encountering some unusual behavior with certain menus. This is a multiple-menu, multiple-video clips promotional DVD.
    Up to last week, the DVD has been working as expected in the simulator, in DVD Player (from the Video_TS folder and from a formatted disc), and in several set top players. Yesterday, though, in DVD Player from a formatted disc, the menus appear with no buttons visibly defaulted. The menu still behaves, though, as if the default button was selected (ie., if pressing "enter" activates the default button, and pressing an arrow button sends the selected state in the designated direction.) Each video asset returns to its menu with another default button, and these behave in the same way.
    I have already double-checked the connections between the buttons, menus, and videos, and they are set the way they have always been.
    - Can the preferences in DVDSP get corrupted (like they can in FCP)?
    - Can the DVDSP porject file become "bloated" or corrupted from going through too many revisions? If so, is there an easy way to put the current project into a new file?
    I expect that some people that view this disc will do so on a Mac, and I would like to clear this up if it is possible. Any ideas?
    Thank you!
    Listening,
    Aaron Kruse
    PowerMac G5, Dual 2GHz   Mac OS X (10.4.6)   3GB RAM, FCStudio 5.0 (DVDSP 4.0.3), Logic 7.2

    Aaron:
    I would try deleting all PAR and MPEG folders that DVDSP created during your authoring (inside the folders where your source files live) and make a clean build without reusing any of the previous VIDEO_TS folders. Probably some file is corrupted. If you want a FCP analogy, is like deleting your render files!
    Trashing preferences is a common preocedure . . . but like in FCP, ussually don't resolve problems. But it's like an aspirin, it will don't hurt your system. You can keep a copy of the pref file to restore in case you need.
    You could repair permissions and restart . . . just to be sure everything is cleaned in your system.
    I would try deleting all PAR and MPEG folders that DVDSP created during your authoring (inside the folders where your source files live) and make a clean build without reusing any of the previous VIDEO_TS folders.
    Probably with the specific experience in your problem psot something in the meantime!
    Hope it helps!
      Alberto

  • Snap mouse pointer to default button doesn't work

    Dear Community,
    I own a W520 with W7professional. My mouse is the ThinkPad bluetooth Laser Mouse.
    In the mouse properties window, I've activated the "Automatically move pointer to the default button in a dialog box" option but unfortunately it seems not working.
    Any idea?
    Best Regards,
    Marco

    hey calza_mc,
    try uninstalling the mouse drivers and reinstall it.
    also, do an update on your bluetooth drivers while you're at it
    WW Social Media
    Important Note: If you need help, post your question in the forum, and include your system type, model number and OS. Do not post your serial number.
    Did someone help you today? Press the star on the left to thank them with a Kudo!
    If you find a post helpful and it answers your question, please mark it as an "Accepted Solution"!
    Follow @LenovoForums on Twitter!
    Have you checked out the Community Knowledgebase yet?!
    How to send a private message? --> Check out this article.

  • Pointer does not move to the default button in the dialog box

    example: when cleaning out trash the pointer does not go to the default button in the dialog box, you have to manually go there.
    This happens all the time.

    Hi Abhishek,
    In SAP this job shows completed till the 3rd step. and no error in the job log. but it does not execute the 4th and the 5th steps. And in Redwood, it shows completed for 1st and 2nd steps, 3rd step is in Error but has no error log. The 4th and 5th steps are in chained status. I have not amended the job chain after import. I have just scheduled it as it was running in the SAP system.
    Let me know if you need some further information on this.
    Regards
    madhu

  • Set default Button and provide a KeyEvent to a component with focus !!!

    What is to do ???
    I have following program:
    public class DefaultButton extends Frame implements ActionListener
         private Button close;
         public DefaultButton()
              super("Default-Button");
              setLayout(null);
              setSize(400, 200);
              setLocation(150, 100);
              setBackground(Color.lightGray);
              addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent e)
                        setVisible(false);
                        dispose();
                        System.exit(0);
              // CloseButton
              close = new Button("Close");
              close.addActionListener(this);
              close.setVisible(true);
              close.setSize(100, 30);
              close.setLocation(290, 160);
              add(close);
              setVisible(true);
         public void actionPerformed(ActionEvent e)
              String cmd = e.getActionCommand();
              if (cmd.equals("Close"))
                   setVisible(false);
                   dispose();
                   System.exit(0);
         public static void main(String [] args)
              DefaultButton wnd = new DefaultButton();
    }If I click on "Close"-button, the window will be closed. But, if the button "Close" has focus, it schold be possibile to close the window with a press on the Enter-Key? How to do it? How can I provide an KeyEvent to button "Close"?
    Tanks for any help.

    Hi pitalica!
    It is possible using KeyListener:
    public class DefaultButton extends Frame implements ActionListener, KeyListener {
    close.addKeyListener(this);
    public void keyPressed(KeyEvent e) {
    if ((e.getSource() instanceof Button)
    && (((Button) e.getSource()).getActionCommand == "Close")) {
    int kc = e.getKeyCode();
    if (kc == KeyEvent.VK_ENTER) {
    performs any action
    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}
    I hope it helps.

  • Default button in BOV should always be #1

    I have a number of Tracks with button overlay in a subtitle stream and Button Highlight activated (cyan/yellow marker).
    The buttons are used to change audio stream during playback.
    From a menu with 6 buttons I select a Track:
    Button 1 = Track 1
    Button 2 = Track 2
    and so on.
    What happens when I play the Track(s) is this:
    Track 1 > Button 1 selected
    Track 2 > Button 2 selected
    Track 3 > Button 3 selected
    etc.
    Is it possible to always select button #1 when starting to play a Track, no matter which menu button was used?
    As it is now, the user gets confused, since the Track is setup to play audio stream 1 in a pre-script (and this works fine).
    TIA
    Message was edited by: Niklas Wikman

    Problem solved. Double-click on the subtitle in the Track and set the Default button in the Button tab in the PI.

  • How to bring mouse cursor to the default button of a dialog, like in windows

    Anybody know how to achieve this in LV?
    Please see the attached screenshot.
    - Partha
    LabVIEW - Wires that catch bugs!
    Attachments:
    Automatically move mouse pointer to the default button.PNG ‏34 KB

    Dear partha,
    1) You can be able to trace out the location of the button
    2) You can be able to move the cursor to that location
    3) You can be able to automatically generate a click on that button
    Use user32.dll to achieve all this. when u use it in CLN(Call Library Node), u can c functions 4 that.
    Try and ask if further help needed!!!!!
    Thanks,
    Mathan

  • How to hide default buttons on WD selection screen

    Hi Experts,
    Is there a way to hide default buttons ( Cancel, Check, Reset, Copy ) on web dynpro selection screen ??
    Please let me know how can I achieve this..
    Thanks in advance !
    Anand

    By selection screen do you mean the select-options reusable component?  If so, then there is an API of the component that you can call to disable these fields. Use the SET_GLOBAL_OPTIONS method of the select-options API to acomplish this:
    data: l_ref_cmp_usage type ref to if_wd_component_usage.
      l_ref_cmp_usage =   wd_this->wd_cpuse_select_options( ).
      if l_ref_cmp_usage->has_active_component( ) is initial.
        l_ref_cmp_usage->create_component( ).
      endif.
      wd_this->lv_wd_select_options =
           wd_this->wd_cpifc_select_options( ).
    * init the select screen
      wd_this->lv_sel_handler =
           wd_this->lv_wd_select_options->init_selection_screen( ).
      wd_this->lv_sel_handler->set_global_options(
        EXPORTING
    *      i_display_btn_cancel  = ABAP_TRUE    " Displays "Cancel" Button
    *      i_display_btn_check   = ABAP_TRUE    " Displays "Check" Button
    *      i_display_btn_reset   = ABAP_TRUE    " Displays "Reset" Button
          i_display_btn_execute = abap_false    " Displays "Apply" Button

  • Default Buttons

    Hi,
    I've got a simple application that needs a custom "search" dialog.
    I've created a subclass of JDialog and it comes up just fine...
    Basically I have a JTextField for them to put in the search, a few checkboxes for the options, and two buttons at the bottom of the dialog. The buttons are named "find first" and "find next."
    I've seen in many programs that when a dialog comes up and has several buttons, i.e. "yes"/"no", then often it will have one of them selected for you and if you hit [enter] it'll just activate that one. I would like to do this to my "find next" button, but am not sure how to do so.
    How do I make my "find next" button be the default for the dialog?
    Right now, I have an ActionListener set up on the text field so that if a user hits [enter] in the search box, the "find next" is activated. I think that this isn't the right way to go, though, since the text box has to be focused.
    Thanks,
    Jared

    I add this code in the constructor of the JDialog to support a default button when no button has focus. (Note. when a button has focus it automatically becomes the default button)
    getRootPane().setDefaultButton( findNextButton );
    FocusAdapter resetDefaultButton = new FocusAdapter()
         public void focusLost(FocusEvent e)
              getRootPane().setDefaultButton( findNextButton );
    replaceButton.addFocusListener( resetDefaultButton );
    replaceAllButton.addFocusListener( resetDefaultButton );
    closeButton.addFocusListener( resetDefaultButton );

  • How to set a default button in a JFileChooser dialog?

    How do I set the default button in a JFileChooser dialog?
    Thanks in advance!
    Thomas

    public static JButton searchByText(Component comp, String[] texts) {
        if (comp instanceof JButton) {
            JButton btn = (JButton) comp;
            String text = btn.getText();
            for(int j=0; j<texts.length; ++j)
                if (text.equals(texts[j]))
                    return btn;
            return null;
        if (comp instanceof Container) {
            Container cont = (Container) comp;
            for(int j=0, ub=cont.getComponentCount(); j<ub; ++j) {
                JButton result = searchByText(cont.getComponent(j), texts);
                if (result != null)
                    return result;
        return null;
    }You can call this method, passing it your JFileChooser and:
    String[] approves = {"Open", "Save"};

  • How to set the default button of an ALERT

    Can someone help me how to set the alert propety to change the default button from button1 to button2.Not from the prioperty palette, but inside the code using like set_alert_property.I am using the Oracle Forms 10g.
    Thanks in advance.
    Srini

    To the best of my knowledge, the default button cannot be set at runtime. This must be set at design time in the Builder.
    Refer to the Forms Builder online help for details:
    http://www.oracle.com/webapps/online-help/forms/10g/topics/f1_help/builts/setatpro.html

  • How to Take Out Default Buttons on Calendar ?

    Hi,
    Does anybody know how to hide/remove the default "Previous" and "Next" buttons on a calendar ? Any advice is greatly appreciated !!
    Dorothy

    Yes, I just want to display the calendar for a particular month selected by the user. I am able to do so. However, the "Next" button still shows even though technically there is no next month to go for. Clicking the "Next" button will then display the calendar with a line saying "No rows returned" and with a "Previous" button. The "Next" button, "Previous" button, "No rows returned" message together is causing confusion to the users. Therefore we want to hide/take out the two default buttons there. Any insights ??
    Thanks,
    Dorothy

Maybe you are looking for