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.

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 can I set focus on TextField?

    Hi,
    I can't find a method or solution to set focus on TextField,I'd like to set the cursor into a special TextField when user enter my form.how can i implement this functionality?
    Any suggestion?
    Hanlin Li.
    Edited by: noob on Apr 13, 2012 4:28 PM

    textField.requestFocus();

  • 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();
    }

  • Set focus on TextField

    Hi guys,
    I want to focus the textfield with a cursor on it without
    clicking on the same and without using Ifocusmanager as I have
    taken the textField.
    I have tried
    stage.focus but it doesn't seem to work the way I want.
    please help me..

    It works.. But without clicking stage won't it happen?
    I have one more query related to it..
    I have n number of tfs on the stage and when I enter into the
    the first tf and if it reaches the maxchar no. it
    shifts its focus to the next tf. Now If I want to reenter the
    text into these tfs from the start it won't replace the text
    (for this i wrote tf .text="", cause of this it takes only
    single char irrespective of the maxchar limit! ) So is there any
    method to do it? Cause in focusmanager class it happens..and
    I want to make it work without one..

  • Cant get Focus on textfield

    Hi
    I have a class extending JFrame say "MainFrame" which consist of JSplitPane say "splitPaneA"
    splitPaneA has top and bottom component.
    TopComponent is another JsplitPane say "splitPaneA-B"
    splitPaneA-B consist of a Jpanel say "B-rightPanel "as RightComponent and another JPanel as left.
    splitPaneA has bottomcoponent which is Jpanel class say "BottomPanel " extendingJPanel
    splitPaneA .setABottomComponent(new BottomPAnel());
    BottomPanel has JtoolBar say toolBar
    ToolBar has a JtextFiled say textField1 which needs to be focused as soon as bottomPanel loads.
    I tried using following in BottomPanel class
    this.setEnabled(true);
    this.setFocusable(true);
    this.setVisible(true);
    this.requestFocusInWindow();
    textField1.requestFocusInWindow()
    But textFiled never gets focused.I also tried requestFocus method.
    In class MainFrame
    FocusManager.getCurrentManager().getFocusOwner()); always returns null
    (FocusManager.getCurrentManager().getFocusedWindow()); returns null
    this.hasFocus()); returns false
    Any help is greatly appreciated.

    Thanks for your responses.
    This is my compilable,executable dummy code.I have taken out lines which are not relevant to focus issue as well as the import.Please llet me know what can be done to get the focus in textfield as soon as window loads.
    public class DummyObjectSearchPanel extends JPanel implements ActionListener
    JTextField textField1;
    JButton searchButton;
    ImageIcon searchIconIcon;
    JToolBar jToolBar1;
    private static Icon closeIcon = new ImageIcon(ObjectSearchMainPanel.class.getResource("/resources/images/close_small.gif"));
    private JButton closeButton;
    JFrame frame;
    private String newline = "\n";
    public DummyObjectSearchPanel()
    this.setLayout(new BorderLayout());
    this.setBorder(new ShadowBorder());
    textField1 = new JTextField();
    this.setEnabled(true);
    this.setFocusable(true);
    this.requestFocusInWindow();
    this.setVisible(true);
    textField1.requestFocus();
    System.out.println("has focus " + textField1.hasFocus());
    jToolBar1 = new JToolBar();
    frame = new JFrame();
    frame.setUndecorated(true);
    jbInit();
    void jbInit()
    searchButton = new JButton();
    searchButton.setText("SearchButton");
    closeButton = new JButton(closeIcon);
    ActionListener al = new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textField1.requestFocusInWindow();
    textField1.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent e)
    searchButton_actionPerformed(e);
    jToolBar1.setBorder(null);
    jToolBar1.addSeparator();
    jToolBar1.add(closeButton);
    closeButton.setOpaque(false);
    closeButton.setMargin(new Insets(4, 4, 4, 4));
    Dimension closeBtnDimension = new Dimension(20, 20);
    closeButton.setPreferredSize(closeBtnDimension);
    closeButton.setMinimumSize(closeBtnDimension);
    closeButton.setSize(closeBtnDimension);
    closeButton.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(java.awt.event.ActionEvent evt)
    //closeButton action taken out to make code short
    jToolBar1.addSeparator();
    jToolBar1.addSeparator();
    jToolBar1.add(textField1);
    jToolBar1.addSeparator();
    jToolBar1.add(searchButton);
    jToolBar1.addSeparator();
    jToolBar1.addSeparator();
    this.add(jToolBar1);
    searchButton.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent e)
    searchButton_actionPerformed(e);
    textField1.requestFocusInWindow();
    void searchButton_actionPerformed(ActionEvent e)
    //searchbutton logic removed to simplify the code
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("New Search");
    Dimension d=new Dimension(600,100);
    frame.setSize(d);
    frame.setMinimumSize(d);
    frame.setPreferredSize(d);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    //Create and set up the content pane.
    JComponent newContentPane = new DummyObjectSearchPanel();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.getContentPane().add(new DummyObjectSearchPanel(),
    BorderLayout.CENTER);
    //Display the window.
    //frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    UIManager.put("swing.boldMetal", Boolean.FALSE);
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    public void actionPerformed(ActionEvent e)
    // TODO Auto-generated method stub
    Thanks you so much

  • 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

  • JSP: Focus on textfield after default value

    Hi all
    i have a JSP/Struts Web Application. When i start it i would like to put the focus on the textfield but after the default value that is written in the textfield. At the moment the focus is alreday put on the textfield, but it's before the default value not after it.
    Somebody has an idea?
    Thanks a lot
    Angela

    JSP can't make the browser do what the browser can't do.

  • 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

  • Newbie question: how to show current time as default value in textfield?

    hi.
    i wanna have a textfield that shows the current systemtime in the format
    DD-MON-YY
    i tried to do it as a pl/sql statement in the default value but it tells me
    ORA-06550: line 1, column 27: PLS-00103: Encountered the symbol "BEGIN" when expecting one of the following: ( - + case mod new not null avg count current exists max min prior sql stddev sum variance execute forall merge time timestamp interval date pipe
    thanks for help! :)

    Joshua,
    Specify a default value of:
    to_char(sysdate,'DD-MON-YY')
    and a Default Value Type of PL/SQL Expression.
    Joel

  • How to set the default focus to  a particular jtextfield

    hi,
    i'm trying to set the focus to the specified Jtextfield by default.
    i tried with reqestFocus() method,grabFocus() method,getCursor() method
    but all in vain.
    can anyone suggest me a solution please.
    very urgent request please
    thanks in advance
    regards
    Ravi teja

    If I understand the question correctly then this thread will help:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=290339

  • How to retain focus in Textfield

    I have one panel which contains three textfiled and one ToolBar. on clicking tool bar button certain dialog get opened.
    intially foucus remained on first textfield but when i do open the dialog with tool bar button. focus doesn't get return to first textfield even focus doesn't get back to screen.
    And my requirement is that to get focus on first textfield after closing the dialog.
    Please let me know if you have any suggestions.
    Thanks,

    yeah I need to set focus again on textfield and that is my question.you can do that using something like :jTextField.requestFocus(); I am seeking the event on which i can set the focus again please suggest.If you are using JOptionPane just add the above statement after showing dialog like JOptionPane.showInputDialog("Hello");
    jTextField.requestFocus();If you are using your own dialog, have a refrence to the textfield in the dialog and at 'windowClosing' Event use the mentioned statement.
    I think that should work....
    Thanks!

  • 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...

Maybe you are looking for

  • How can I stop iTunes from changing my tags?

    I have a MacBook Pro running Yosemite, and iTunes 12. When I play a track, iTunes often changes the tags automatically, but not for every track. It's particularly difficult with compilations, where it will take a song and change the album to somethin

  • How can I check if I backed up my iphone

    I have had to restore as new due to restrictions passcode being locked and not being able to delete any applications. The help info I received told me not to do a restore backup if I wanted to unlock the code. I had backed up the phone earlier, but c

  • Error in calling stored procedure in sender JDBC adapter

    Hi Experts, I am working on MySQl to SAP scenario. I have to use stored procedure in sender JDBC adapter. I am calling SP as fallows: execute proc_dtdc_booking_interface_sd But it returned following error, Database-level error reported by JDBC driver

  • SQL Query doubt

    Hi, I have a Customer info table Table1 it has the following fields apart from many other fields like cust account info. Account_number Tax_id Tax_ID_format (this field has values S, T and the column is NUllable. I need to find all the tax ids that h

  • Do I need to unloadMovie?

    Another question on my: band_btn.onRelease = function () { loadMovie("clip_a.swf", "_root.clip_on_stage"); I have many buttons within video clips on my stage each opening SWF files. Each SWF files replace the same instance on stage as per above. When