Default Focus to Button

Hi,
I have around 10 controls on my JDialog and Edit-F2 (Caption on JButton)
is one of them. Other components are disabled except the Edit-F2 button.
Now my Problem is when the Dialog pop's up on Pressing F2 the funtionality
associated with edit button should be executed. I am unable to set the
focus of the first time on Edit-F2 button. I tried grabFocus (),
requestFocus (), requestDefaultFocus (). I have implemented the keylisteners
also.
Please help. Thanks in advance.
-regards
deena

Hello,
There is one important thing to know about Swing and the focus management :
The focus manager sets automatically the focus on the first component of the Frame that as the focus.
If this first component is a container, it sets the focus on the first component of this container.
And if this component is also a container that contains other components, it sets the focus on the first of them.
Etc...
So, if you want a button to be the default button of a container, use the add(Component comp, int index), or the add(Component comp, Object constraints, int index) with index set to 0. You should do the same with the parent component of your button. Here is an example with a panel :
   JFrame frame = new JFrame("test") ;
   JPanel panel0 = new JPanel() ;
   panel0.add(new JButton("button 1"));
   panel0.add(new JButton("button 2"));
   JPanel panel1 = new JPanel() ;
   panel1.add(new JButton("button 3")) ;
   panel1.add(new JButton("default button"),0);
   frame.getContentPane().add(panel0) ;
   frame.getContentPane().add(panel1 , 0 );Running this code you should not need to call requestFocus nor any other method to set the focus on "default button".
Do not forget to set some constraints on your components to layout them correctly...

Similar Messages

  • Is there a default focus Method ?

    I would like to have a button to be focused by default within a dialog such that user can easily fire the button's action. Is there a method to set default focus on a button ? Thanks !!!

    That's actually very helpful. I can now set a default focus button on a dialog. But then for some reason I can not set it for other dialogs initiated by this dialog. Since I have an opening dialog with a number of buttons, and those buttons will open up a new dialog. Right now I can only set the default focus to the opening dialog. The other dialogs that opens up from firing the buttons did not have the same effect as the opening dialog. Is there a way to fix it ? Thanks

  • Default focus behavior in Swing

    I have a JTabbedPane wherein every tab has a variety of fields, including buttons, text areas, text fields, tables, and so on. I wanted to tweak the default focus behavior such that the first text field or the first text area has the focus.
    I used requestFocusInWindow() to set the focus on the first text field I get. This, however, was being overriden at a later stage (I am working on a vast code) and the first component inside a tab is getting the focus.
    Is there any means to override the default focus behavior? I tried writing my own FocusTraversalPolicy but found that that is never used. How does the default focus behavior work? Does it set the focus on the first field it gets or what? And where can I find the code for the same?

    I used requestFocusInWindow() to set the focus on the first text field I get. The requestFocusInWindow() method only works when the GUI is already visible. So I would suggest that you add a ChangeListener to the tabbed pane and add your code to set the focus every time the tab is changed.
    For a slightly different approach the code in this posting will remember the last field for each tab that had focus and reset focus to that field when the tab is changed. The code is not completely off topic since it shows how to use a ChangeListener:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=570369

  • How to focus No button in JOptionPane.showConfirmDialog?

    How to focus No button in JOptionPane.showConfirmDialog when the Dialog window is opened?
    (default it focus Yes button).
    Please help me. Thank you very much.

    Use the showOptionDialog(...) method then you can specify the buttons and which button has focus.

  • JOptionPane en default focus issues

    Hello,
    I have written a simple class to show a login dialog, but I can't get the default focus right. My problem is that I want the first JTextField (usernameField) to be the one select when my dialog shows, but I want the first button (Ok button) to be called automatically when I press enter. What happens now that I set the first button (Ok button) default (last argument of JOptionPane.showOptionDialog), this makes sure that whenever I press enter this buttons gets called en the dialog reacts accordingly. But when the dialog is first shown this default button is also the one selected (having focus), this is not what I want. The JTextField (usernameField) should be selected (have focus) so a user can enter his username, then press enter and see what happens.
    When I don't set a default button nothings happens when I press enter but now the right JTextFields (usernameField) is selected.
    Hope anyone can help me.
    Thank you very much.
    The code:
    public class LoginDialog
        private int attempts;
        private TargetFinder controller;
        private Component parent;
        private String username;
        private String password;
        public LoginDialog(TargetFinder controller, Component parent)
            this.controller = controller;
            this.parent = parent;
            username = "";
            password = "";
        private int buildDialog()
            String dialogTitle, usernameText, passwordText, errorPart1, errorPart2;
            String[] buttonsText;
            try
                dialogTitle = LanguageParser.getText("loginTitle");
                usernameText = LanguageParser.getText("username");
                passwordText = LanguageParser.getText("password");
                buttonsText = new String[2];            
                buttonsText[0] = LanguageParser.getText("loginTitle");
                buttonsText[1] = LanguageParser.getText("cancel");
                errorPart1 = LanguageParser.getText("loginError1");     
                errorPart2 = LanguageParser.getText("loginError2");
            catch (Exception e)
                throw new RuntimeException("Login dialog could not be created", e);
            JPanel namePanel = new JPanel(false);
            namePanel.setLayout( new GridLayout(0, 1) );
            namePanel.add( new JLabel(usernameText) );
            namePanel.add( new JLabel(passwordText) );
            JPanel fieldPanel = new JPanel(false);
            fieldPanel.setLayout( new GridLayout(0, 1) );
            JTextField usernameField = new JTextField(12);
            fieldPanel.add(usernameField);
            JPasswordField passwordField = new JPasswordField(12);
            fieldPanel.add(passwordField);
            JPanel componentPanel = new JPanel(false);
            componentPanel.setLayout( new BoxLayout(componentPanel,
                    BoxLayout.X_AXIS) );       
            componentPanel.add(namePanel);
            componentPanel.add(fieldPanel);
            JPanel componentPanelError = new JPanel(false);
            componentPanelError.setLayout( new GridLayout(0, 1) );
            componentPanelError.add(componentPanel);
            JLabel errorLabel = new JLabel(
                    "<html>" +
                    errorPart1 +
                    "<br>" +
                    errorPart2 +
                    "</html>" );   
            errorLabel.setForeground(Color.RED);
            componentPanelError.add(errorLabel);
            int res;
            res = JOptionPane.showOptionDialog(
                    parent,
                    (attempts == 0) ? componentPanel : componentPanelError,
                    dialogTitle,
                    JOptionPane.OK_CANCEL_OPTION,
                    (attempts == 0) ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.ERROR_MESSAGE,
                    null,
                    buttonsText,
                    buttonsText[0] );
            if (res == JOptionPane.OK_OPTION)
                username = usernameField.getText();
                password = new String( passwordField.getPassword() );
            return res;
        public boolean login()
            attempts = 0;
            Database database = controller.getDatabase();
            while ( buildDialog() == JOptionPane.OK_OPTION )
                if ( database.login(username, password) )
                    return true;
                attempts++;
            return false;
    }

    Thanks for your reaction Olek,
    But I can't request focus because JOptionPane creates a model window, so the JVM waits for the user to click one of the buttons.
    Also I don't know how to add a ButtonListers to any of the buttons because the are created dynamicly by JOptionPane.
    I use JOptionPane.OK_CANCEL_OPTION to create both an Ok and a Cancel button, and define an array (buttonsText) with names for them. I can't ask the rootPane for this buttons because they only excist after I call JOptionPane.showOptionDialog(...) and this is model window.
            int res;
            res = JOptionPane.showOptionDialog(
                    parent,
                    (attempts == 0) ? componentPanel : componentPanelError,
                    dialogTitle,
                    JOptionPane.OK_CANCEL_OPTION,
                    (attempts == 0) ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.ERROR_MESSAGE,
                    null,
                    buttonsText,
                    buttonsText[0] );With kind regards,
    Eddy

  • Default Focus on TextField

    Hello All,
    I have got a problem, please help me. I have a textfield in a frame. When call that frame the textfield will be displayed with default focus on it. I dont want to have the cursor in that text field. I dont have any other swing components in that and the text field is the first component in that frame.
    Please help me....
    Thanks in advance

    Hello
    Thanks for your reply. But i my code is some thing like this.
    public class TextFieldExample extends JFrame
         public JTextField textField;
         public JButton enterButton;
         public TextFieldExample()
              super();
              textField = new JTextField(25);
              JPanel jp = new JPanel();
              jp.add(textField);
              getContentPane().add(jp);
              setLocationRelativeTo(this);
              pack();
         public static void main(String args[])
              TextFieldExample textFieldExample = new TextFieldExample();
              textFieldExample.setVisible(true);
              textFieldExample.addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent we)
                        System.exit(0);
    Now Please suggest me the solution.

  • In  Zoom Burst Effect Guided Edit, when i use the  Add Focus Area button instead of focusing on what i choose it bring the entire photo into focus.

    In Zoom Burst Effect in Guided Edit, when I use the Add Focus Area button instead of focusing on what I chose it brings the entire photo into focus.

    I'd try resetting the pse 12 preferences by going to Adobe Photoshop Elements Editor (Edit)>Preferences>General
    and click on Reset Preferences on next launch, then restart pse 12.

  • Default Focus on textInput ?

    Hi everybody !
    How set default focus on form element ?

    Hi Rustam -
    I believe that you'll need to write a bit of JavaScript to do this. You can set the default focus in your body's onLoad handler. Here is a sample uiXML page which sets the focus to a text input control when the page is loaded:
    <?xml version="1.0" encoding="UTF-8"?>
    <page xmlns="http://xmlns.oracle.com/uix/controller"
          xmlns:ui="http://xmlns.oracle.com/uix/ui"
          xmlns:data="http://xmlns.oracle.com/uix/ui"
          xmlns:ctrl="http://xmlns.oracle.com/uix/controller">
    <content>
      <body onLoad="form1.text2.focus()" xmlns="http://xmlns.oracle.com/uix/ui">
      <contents>
        <form name="form1">
        <contents>
          <stackLayout>
          <contents>
            <textInput name="text1"/>
            <textInput name="text2"/>
          </contents>
          </stackLayout>
        </contents>
        </form>
      </contents>
      </body>
    </content>
    </page>Andy

  • Changing the application wide default focus traversal policy

    Hi,
    I have a Swing application built using JDK1.3 where there lots of screens (frames, dialogs with complex screens - panels, tables, tabbed panes etc), in some screens layouts have been used and in other screens instead of any layout, absolute positions and sizes of the controls have been specified.
    In some screens setNextFocusableComponent() methods for some components have been called at some other places default focus traversal is used. (which I think is the order in which the components are placed and their postions etc). Focus traversal in each screen works fine.
    Now I have to migrate to JDK1.4. Problem now is that after migrating to JDK1.4.2, focus traversal has become a headache. In some screens there is no focus traversal and in some there is it is not what I wanted.
    So I thought to replace applicaiton wide default focus traversal policy and I did the following:
    ///////// Replace default focus traversal policy
    java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalPolicy(new java.awt.ContainerOrderFocusTraversalPolicy());
    But there is no change in the behaviour.
    Then I tried following:
    ///////// Replace default focus traversal policy
    java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalPolicy(new java.awt.DefaultFocusTraversalPolicy());
    I did all this in the main() method of the application before anything else just to ensure that all the components get added after this policy has been set. But no luck.
    Does someone has any idea what is the problem here ? I do not want to define my own focus traversal policy for each screen that I use (because thats lot of codes).
    Thanks

    not that hard if you only have the one focus cycle ( > 1 cycle and it gets a bit harder, sometimes stranger)
    import javax.swing.*;
    import java.awt.*;
    class Testing
      int focusNumber = 0;
      public void buildGUI()
        JTextField[] tf = new JTextField[10];
        JPanel p = new JPanel(new GridLayout(5,2));
        for(int x = 0, y = tf.length; x < y; x++)
          tf[x] = new JTextField(5);
          p.add(tf[x]);
        final JTextField[] focusList = new JTextField[]{tf[1],tf[0],tf[3],tf[2],tf[5],tf[4],tf[7],tf[6],tf[9],tf[8]};
        JFrame f = new JFrame();
        f.setFocusTraversalPolicy(new FocusTraversalPolicy(){
          public Component getComponentAfter(Container focusCycleRoot,Component aComponent)
            focusNumber = (focusNumber+1) % focusList.length;
            return focusList[focusNumber];
          public Component getComponentBefore(Container focusCycleRoot,Component aComponent)
            focusNumber = (focusList.length+focusNumber-1) % focusList.length;
            return focusList[focusNumber];
          public Component getDefaultComponent(Container focusCycleRoot){return focusList[0];}
          public Component getLastComponent(Container focusCycleRoot){return focusList[focusList.length-1];}
          public Component getFirstComponent(Container focusCycleRoot){return focusList[0];}
        f.getContentPane().add(p);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • How to default the radio button confirmation and invoice in shopping cart

    Hi Guys,
    In the shopping cart for a limit item I need to default the radio button for CONFIRMATION AND INVOICE as it is now defaluted to INVOICE ONLY .
    Please let me know how to change as I could not achieve it through UI badi.
    Thanks & Regards
    Arun

    Did you try the suggestions mentioned here: To make the field for Display only on the Shopping Cart Portal
    I'm looking for a way to restrict the "Invoice Only" option depending on the product category selected.  Do you know I would do this?
    For example only allow "Invoice Only" to be selected if Product Category X is selected.  If product category Y is selected then grey-out "Invoice Only".
    Matt

  • How to focus a button

    Hi all,
    Sorry about this stupid question, but really get confused now.
    I?ve got an Applet and i want to focus a button when it starts! How can i do this?
    thx

    Don't know if anyone is looking at this, but I went through a coupla days work, so I thot I would post. I was only able to get it working in IE. This solves the problem of initially not having focus on the applet, setting initial focus to a component and resetting the focus when switching back & forth betweens apps. First the HTML<SCRIPT LANGUAGE="JavaScript">
    <!--
    function setFocus() {
      hide.hideField.focus();
      document.TestApplet.setFocus();
    // -->
    </SCRIPT>
    <form id=hide>
    <INPUT style="border: 0px;" ReadOnly id=hideField maxLength=0 name="hideField" type=text notab>
    </form>
    </HEAD>
    <BODY onFocus="setFocus()" onLoad="setFocus()">
    <OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    //removed some
    <PARAM NAME="scriptable" VALUE="true">I have no idea how this is going to post. This calls the JApplets setFocus method on loading and on focus. Make sure scriptable="true". Now the JApplet.public class Applet1 extends JApplet {
      public void start() { Focus.setFocus(jButton2); }
      public void init() {
        getContentPane().addContainerListener(Focus.cl);
      public void setFocus() { Focus.setFocus(); }
      static class Focus {
        private static Component lastFocus;
        public static ContainerListener cl = new ContainerAdapter() {
          public void componentAdded(ContainerEvent ce) {
         Component child = ce.getChild();
         addlisteners(child);
        private static void addlisteners(Component c) {
          c.addFocusListener(fl);
          if(c instanceof Container) {
         Container ct = (Container)c;
         ct.addContainerListener(cl);
         for(int i=0; i<ct.getComponentCount(); i++) {
           addlisteners((Component)ct.getComponent(i));
        public static FocusListener fl = new FocusAdapter() {
          public void focusGained(FocusEvent fe) {
         lastFocus = (Component)fe.getSource();
        public static void setFocus() { setFocus(lastFocus); }
        public static void setFocus(final Component comp) {
          if (comp != null) {
         SwingUtilities.invokeLater(new Runnable() {
           public void run() { comp.requestFocus(); }
    }I tried to make it compatible with AWT, but haven't tested it too much. Focus might also be made into it's own class, instead of an inner class so that it can be called from anywhere (after dialogs???).

  • Default Strata navigation buttons used to have colors besides blue with Windows 2000.

    I recently moved from Windows 2000 to Windows 7 and noticed that the default Strata navigation buttons are now all blue. For example, with Windows 2000 the stop "X" was red and the "Forward" and "Back" arrow buttons were green. No biggie, but is there any way to get these colors with the default navigation buttons in Windows 7?
    Thanks!

    Hello and thank you for the reply!
    While I am waiting for the issue to start up again, I'd just like to cover some things you mentioned in your post. :)
    I only updated the bios because I was originally experiencing these issues. It was a method to hopefully resolve them, which did not work. I was very careful, and the process was a success. I updated to the most recent recommended driver for my motherboard
    from the manufacturers.
    As for Auslogics Boost Speed, it is not running on my computer, as it is a piece of software I only have used to clean junk files (cache/temp) for a very long time now with no issue. I have also tried updating all of my drivers with success, however that
    did not solve the issue either. I even rolled back my network card driver just in case with no luck.
    I have not thought of disabling my audio driver yet, being how it effects far more than just my audio when it happens. My mouse is jittery/laggy as well when no sound is playing. But other tests have shown that it may be a network issue. Next time it happens
    I'll temporary disable my network drivers to see if that causes the issue to clear up.
    I will be sure to mark answers which help appropriately. Thanks again! I should return with the information requested from Zigzag's wiki within 2 days of on-time, when this happens again. 

  • Firefox Loses Window Focus, Mouse Button profiles change to default

    I have a G700 mouse, which supports various hotkey profiles. For default profile, i have most buttons disabled. For games, i have game-specific hotkeys, and for firefox, i have firefox specific hotkeys (new tab, close tab, etc).
    There are 2 times that I notice this behavior:
    1) During regular browsing, clicking on various links causes firefox to lose focus, and the mouse software reverts from the "firefox" profile to the "default" profile. Interacting with firefox in any way does not fix this problem. the only way for firefox to become the default profile again is to click a different window or on the desktop, and then click back into firefox. The profile seems to be lost right after clicking a (javascript) link, though the number of links clicked is arbitrary. I cannot reproduce this issue with any fixed results (number of click, time period before losing focus, etc). But I can reproduce this issue reliably.
    When the mouse buttons stop working, the keyboard hotkey shortcuts DONT stop working. I dont have to re-select the firefox window to use keyboard shortcuts, I only have to do that if i want to use the mouse shortcut.
    2) If I am in private browsing mode, clicking links (specifically for websites that contain flash) causes the window which contains flash to move into the background and the non-private window becomes the foreground. Again, the mouse loses focus and the only way to regain focus is to manually click the window or to click away on a non-firefox object, then click the window. I believe this is a flashplayer based issue, though, and is unrelated to the profiles issue. When this happens, any interaction with a flash video also forces firefox's KEYBOARD hotkeys to not work. Ctrl+w and ctrl+t dont do anything, hitting escape does not give firefox control over keyboard hotkeys, and hitting "tab" only selects elements within the flash object. For youtube, it cycles through various clickable controls.
    EDIT: I have tried resetting the firefox profile and using a completely new profile, and i have also tried syncing profiles. This is a persistent problem.

    I'm using Firefox 23. This has been a problem since I got my mouse in September ish of 2012. As I stated, I've worked with logitech on this issue, they have no idea why it happens because only firefox exhibits this behavior. No other app on my computer does this and Firefox reset and clean profile do not do anything to solve the problem. Using logitech logging, I can produce a log and output of whenever the profile switches. I might be able to use logitech scripting to output debug information about what exactly causes it but that would take dev time I don't have.

  • How to create an YES/NO JOptionPane with the default focus on No?

    Hi,
    can somebody please show me how to display an JOptionPane with the options Yes and No that has the focus by default no the No button?
    By default it is on the Yes button which is rather problematic for confirm dialogs like "Do you really want to delete everything?".
    JPJava

    It would help if JPJava gave some sample code SSCCE to show they know how to construct a JOptionPane
    I use explorer to access the source files in the zip folder and JGrasp to view the source code
    this is copy modify from the API
    Object[] options = { "YES", "CANCEL" };//{"OK", "CANCEL"} shown in api
    JOptionPane.showOptionDialog(null, "Are you sure you want to delete", "Confirm Delete",
    JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
    null, options, options[1]);//options[1] selects CANCEL option as defaultthis method constructs
    showOptionDialog
    public static int showOptionDialog(Component parentComponent,
                                       Object message,
                                       String title,
                                       int optionType,
                                       int messageType,
                                       Icon icon,
                                       Object[] options,
                                       Object initialValue)
                                throws HeadlessExceptionBrings up a dialog with a specified icon, where the initial
    choice is determined by the initialValue parameter and the number of choices is determined by the optionType parameter.
    If optionType is YES_NO_OPTION, or YES_NO_CANCEL_OPTION and the options parameter is null,
    then the options are supplied by the look and feel.
    The messageType parameter is primarily used to supply a default icon from the look and feel.
    Parameters:
    parentComponent - determines the Frame in which the dialog is displayed; if null, or if the parentComponent
    has no Frame, a default Frame is used
    message - the Object to display
    title - the title string for the dialog
    optionType - an integer designating the options available on the dialog: YES_NO_OPTION, or
    YES_NO_CANCEL_OPTION
    messageType - an integer designating the kind of message this is, primarily used to determine the icon from
    the pluggable Look and Feel: ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE,
    QUESTION_MESSAGE, or PLAIN_MESSAGE
    icon - the icon to display in the dialog
    options - an array of objects indicating the possible choices the user can make; if the objects are components,
    they are rendered properly; non-String objects are rendered using their toString methods; if this parameter is null,
    the options are determined by the Look and Feel
    initialValue - the object that represents the default selection for the dialog; only meaningful if options is used; can be null
    Returns:
    an integer indicating the option chosen by the user, or CLOSED_OPTION if the user closed the dialog
    Throws:
    HeadlessException - if GraphicsEnvironment.isHeadless returns true
    See Also:
    GraphicsEnvironment.isHeadless()Edited by: Ross_M on Sep 22, 2008 9:19 AM

  • Default the active button in a dialog

    Hi All,
    I'm trying to find a way to default the focus onto the 'No' button in a Yes/No dialog box.
    I tried making a Yes and a No button using the execDialog with the first_tab property set to the No but it doesn't want to work for me.
    Thanks in advance for any help.
    Kyle

    Yes.
    Message Edited by jcarmody on 12-16-2008 08:59 AM
    Jim
    You're entirely bonkers. But I'll tell you a secret. All the best people are. ~ Alice
    Attachments:
    property.gif ‏21 KB

Maybe you are looking for