Focusing a JTextField

I made a guessing game and id like to know how to make the program focus itself on my text field after each press of the guess button, instead of alwayz having to click in the field to get a cursor to enter your next guess.

use the requestFocus method

Similar Messages

  • Problem with gaining focus for JTextField in JTabPane

    I have 2 tabs. The first one has a "save to file" puush button, the seccond has two textfields. When I push the save button I get a warning that not all fields in the seccond tab are filled. If I choose the first button it shows me the seccond tab and searches for the first empty field. Then it should set the focus to that field but it doesn't. Here's the code:
    void goToEmptyField() {
            tabs.setSelectedIndex(1);
            JTextField field =  (nameField.getText().length() == 0) ? nameField : actionField;
            field.requestFocusInWindow();
        }The code for determining the first empty field works fine. I'm not sure if the seccond tab gets focus or just shows up. It doesn't have the light rectangle at the tab's description. Could anybody help me please?

    seems to work OK in this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Testing extends JFrame
      JTabbedPane tabs;
      JTextField nameField = new JTextField(20);
      JTextField actionField = new JTextField(20);
      public Testing()
        setLocation(400,300);
        setSize(300,200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel jp1 = new JPanel();
        JButton saveBtn = new JButton("Save");
        saveBtn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            if(checkFields()) saveData();}});
        jp1.add(saveBtn);
        JPanel jp2 = new JPanel();
        jp2.add(new JLabel("Name: "));
        jp2.add(nameField);
        jp2.add(new JLabel("Action: "));
        jp2.add(actionField);
        tabs = new JTabbedPane();
        tabs.addTab("Tab 1",jp1);
        tabs.addTab("Tab 2",jp2);
        getContentPane().add(tabs);
      public boolean checkFields()
        if(nameField.getText().equals("") || actionField.getText().equals(""))
          JOptionPane.showMessageDialog(this,"field/s empty");
          goToEmptyField();
          return false;
        return true;
      public void goToEmptyField()
        tabs.setSelectedIndex(1);
        JTextField field =  (nameField.getText().length() == 0) ? nameField : actionField;
        field.requestFocusInWindow();
      public void saveData()
        JOptionPane.showMessageDialog(this,"Saving data...");
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • Focus on JTextfield in JDialog box

    A JDialog box is being opened from a menu.
    There is only one JTextfield on the dialog box and 2 buttons.
    The focus is not on any of the components in the dialog box and I want it on the textfield by default.
    I have tried all the requestFocus(),requestDefaultFocus(),grabfocus() etc and none of them work.
    There is an eventListener added to the JTextfield could this be the problem.

    I am a little supprised that the focus is not given to the text field if that is the only thing on the dialog.
    You could try detecting the display of the dialog and then giving the focus to the text field. Focus will not be given to a component if the component cant be displayed at that time. My guess is that the dialog is still hidden when you are trying to set the focus and that is what is causing the problem.

  • Auto-shift of focus between JTextFields

    Greetings.
    I have an array of 50 JTextFields which I restricted to a four-character entry limit. The limit works just fine, but I would like the focus to shift to the next JTextField when the limit is reached. Currently, I'm watching for the limit via an extended PlainDocument called CharLimitDocument. (*code included below) I know that Java offers the function FocusManager.focusNextComponent(Component aComp), but I'm not sure how to retrieve the current component. Can anyone help?
    Thanks in advance,
    Liz
    *CharLimitDocument Code
    import javax.swing.text.*;
    import java.awt.*;
    //This class overloads the Document so that a JTextField can be designed to accept only a specific number of characters.
    class CharLimitDocument extends PlainDocument
    private int limit;
    public CharLimitDocument(int limit)
    {  this.limit = limit;  }
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
    if((str.length() + getLength()) <= limit)
    {     super.insertString(offs, str, a);     }
    else
    {     Toolkit.getDefaultToolkit().beep();     }
    }//end class CharLimitDocument

    Maybe you were talking about this function in javax.swing.JComponent?
    hasFocus() (returns boolean)
    You could test each component to see if it hasFocus() and then you'd be able to retrieve the 'current' component (pseudo code below). Even though you have fifty fields, this still woudn't be memory/processor intensive.
    Hope that helps,
    H
    int compindex=0;
    while((compindex)<=(getComponentCount()))
         if(getComponent(compindex).hasFocus()==true)
         {this is the current component... do whatever;}
         else
         {compindex++;}
    }

  • How to set focus on JTextField

    hi everyone,
    i have a JTextFields on my form. i have a reset button. i want keh when i click it all the fields get default value(that i have done) and focus is set on any of the JTextFields. please tell me how to do that.
    thanks & regards

    i triend using requestFocus method but i coouldn't get
    please tell me the wayread the docs
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JComponent.htmlor, post a small demo program explaining:
    what it is you expect, and
    what it is you get

  • Requesting focus for JTextField inside JPanel

    I have an application with following containment hierarchy.
    JFrame --> JSplitPane --> JPanel.
    JPanel is itself a seperate class in a seperate file. I want to give focus to one of the JTextfields in JPanel, when the JPanel is intially loaded in the JFrame. I believe that I cannot request focus until the JPanel is constructed. I can set the focus from JFrame (which loads JPanel) but I want to do this from JPanel. Is there any technique to request focus from the JPanel itself (preferably during JPanel construction).
    regards,
    Nirvan.

    I believe that I cannot request focus until the JPanel is constructedYou can't request focus until the frame containing the panel is visible. You can use a WindowListener and handle the windowOpened event.

  • Can't get focused a JTextField within a JTable cell

    I have a table and I placed a cell editor with a JText field on it for all cell editing,
    I want to do things when the focus is lost or gained and my app works fine when a cell is double clicked or f2 is pressed, but when a cell is selected (without double clicking) and just begin typing it produces no focus gained event.
    I tried by calling grabFocus method of that jTextField within the overriden prepareEditor method of the JTable but it doesn't get focus (doesn't even gains and loses it :s )
    Does anyone have an idea of how to force this component to grab focus?
    Thanks

    Hai,
    dont add the FocusListener to the EditorComponent.
    Try to use the JTable Functions - like this:
    import javax.swing.event.ChangeEvent;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.EventObject;
    import javax.swing.*;
    public class Test extends JFrame
         JTable table;
         JTextArea text;
         JScrollPane scroll;
         JTextField cellTextField;
         Test()
              DefaultTableModel model = new DefaultTableModel();
              cellTextField = new JTextField();
              text = new JTextArea();
              text.setEditable(false);
              scroll = new JScrollPane();
              scroll.setViewportView(text);
              table = new JTable(model){
                   @Override
                   public Component prepareEditor(TableCellEditor editor, int row, int column) {
                        text.append("Better use this to Start Edit!\n");
                        return super.prepareEditor(editor, row, column);
                   @Override
                   public void editingStopped(ChangeEvent e) {
                        text.append("Better use this to Stop Edit!\n");
                        super.editingStopped(e);
              model.addColumn("Column 1");
              model.addColumn("Column 2");          
              model.addRow(new String [] {"Cell 1", "Cell 2"});
              table.setCellSelectionEnabled( true );
              table.getColumnModel().getColumn(0).setCellEditor( new DefaultCellEditor(cellTextField));
              table.getColumnModel().getColumn(1).setCellEditor( new DefaultCellEditor(cellTextField));
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(table, BorderLayout.NORTH);
              getContentPane().add(scroll, BorderLayout.CENTER);
              setSize(300, 300);
              setVisible(true);
              setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         public static void main(String[] args)
              new Test();
    }

  • Getting focus on JTextField?

    I made a chat with a JApplet. In my chat i have a JTextField where users can write messages. I want to have focus on this JTextfield all the time, the user should not be allowed to get focus somewhere else. How can I do that? I tried requestFocus(); but its not making any differants. I use gridbaglayout and this is how I create my JTextfield:
    beskedFelt = new JTextField(10);
    c.insets = new Insets(10,0,0,0);
    c.gridx = 1;
    c.gridy = 2;
    gridbag.setConstraints(beskedFelt, c);
    contentPane.add(beskedFelt);
    beskedFelt.setEditable(true);
    beskedFelt.addActionListener(this);
    beskedFelt.requestFocus();
    thx for your time....

    yesss it worked:
    beskedFelt = new JTextField(10);
    EventQueue.invokeLater(new Runnable() {
    public void run() {
    beskedFelt.requestFocus();
    c.insets = new Insets(10,0,0,0);
    c.gridx = 1;
    c.gridy = 2;
    gridbag.setConstraints(beskedFelt, c);
    contentPane.add(beskedFelt);
    beskedFelt.setEditable(true);
    beskedFelt.addFocusListener(this);
    beskedFelt.addActionListener(this);
    public void focusGained(java.awt.event.FocusEvent fe)
    public void focusLost(java.awt.event.FocusEvent fe)
              Object source = fe.getSource();
              if ( source == beskedFelt)
    beskedFelt.requestFocus();
    thx a lot ppl....

  • Setting Focus of JTextField

    Hello,
    I have created a JDialog subclass that has several JTextFields in it.
    When the dialog is shown, I want the first (the top-most) textfield to have the focus.
    I have tried topTextField.requestFocus() but the focus remains on anotherTextField. isRequestFocusEnabled() == true for the topTextField, and I have not called any method to request the focus for anotherTextField.
    Is there any thing trickey about this getting focus business?

    Ok,
    I just noticed that the anotherTextField that has the focus is the first component that is added to a JPanel inbedded into my JDialog, and that when I add a different textField first, it has the focus. Is this a "feature" of Swing?
    In any case, I should still be able to change the focus to anyother component.
    Any ideas would be very helpful.

  • Focus On JTextField

    How can I put the Focus to JTextFiled when The JFrame is Displayed.

    Have you read the API for JTextField? There's a method there that will
    help. Try opening it up and searching for "focus".

  • Giving focus to JTextfield or JTextArea

    Hello,
    I want to know how to give the focus to a JTextField.To be more precise,
    I would like the cursor to be placed in the JTextField or JtextArea so the user does not have to click on the field and then enter a text.I must specify there a lot of components in my panel(JComboBox,JLabel,JList,JTextField).
    I tried jText.setFocus(),jText.setFocusable(true), and all the other focus' methods but it doesn't work.I also tried the caret method.
    Thanks in advance.

    This thread may explain your problem:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=290339

  • Focus with JTextField

    There is a fields check when the user clicked a button:
    if ( this.jTextField5.getText().length() == 0 )
    MessageBox.error("Il Campo [Menmonico Sito] non pu� essere vuoto", win);
    this.jTextField5.requestFocus();
    return false;
    else if ( this.jTextField6.getText().length() == 0 )
    MessageBox.error("Il Campo [Nome Telecom] non pu� essere vuoto", win);
    this.jTextField6.requestFocus();
    return false;
    If both jTextField5 and jTextField6 are empty and the user write nothing:
    the first time - after the message error, the jTextField5 catch the focus. It's OK!
    the second time - after the message error, the jTextField6 catch the focus but jTextField5 don't lost its focus. WHY?

    That is a very interesting problem. I think this is a windows control bug that the focus is not coming back. The only idea I have is to write a native function that calls WINAPI peace of code that makes the address edit control loose focus and probably then it would come to your applet. That is not much complicated operation in standalone appication but applet makes it more difficult. It's not easy to use native methods in applet - do you really care about that this much? It's not like the applet looses the focus forever, just click on something else and then on applet - it works brilliant :)
    pozdrawiam (regards)
    ania

  • Problem with focus and selecting text in jtextfield

    I have problem with jtexfield. I know that solution will be very simple but I can't figure it out.
    This is simplified version of situation:
    I have a jframe, jtextfield and jbutton. User can put numbers (0-10000) separated with commas to textfield and save those numbers by pressing jbutton.
    When jbutton is pressed I have a validator which checks that jtextfield contains only numbers and commas. If validator sees that there are invalid characters, a messagebox is launched which tells to user whats wrong.
    Now comes the tricky part.
    When user presses ok from messagebox, jtextfield should select the character which validator said was invalid so that user can replace it by pressing a number or comma.
    I have the invalid character, but how can you get the focus to jtextfield and select only the character which was invalid?
    I tried requestFocus(), but it selected whole text in jtextfield and after that command I couldn't set selected text. I tried with commands setSelectionStart(int), setSelectionEnd(int) and select(int,int).
    Then I tried to use Caret and select text with that. It selected the character I wanted, but the focus wasn't really there because it didn't have keyFocus (or something like that).
    Is there a simple way of doing this?

    textField.requestFocusInWindow();
    textField.select(...);The above should work, although read the API on the select(...) method for the newer recommended approach on how to do selection.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",
    see http://homepage1.nifty.com/algafield/sscce.html,
    that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the "Code Formatting Tags",
    see http://forum.java.sun.com/help.jspa?sec=formatting,
    so the posted code retains its original formatting.

  • JTextField gets focus NO more

    Hello,
    I have a big application running on JDK 1.4.0_03 which is running on RedHat 7.3 and sometimes it produces a very strange error.
    At some point in time (sometimes), the application refuses to give focus to JTextFields. I simply cannot click into the field any more. However, buttons still work, only JTextField cannot be used.
    Has anybody experienced anything similar?
    I am interested in any updates on this issue.
    Thank you in advance,
    G

    Rahim_From_Puniyal wrote:
    Yannix
    i post this thread at java programming forum. You reply me that "should be post at swing forum" then i post it again here you again reply my question like your previous answer.I said Next time Swing related question should be posted in the Swing forum.
    In short next time you have a new problem about swing post it in here. Simple English.
    Please don't reply if you don't have any useful answer to the question ok.
    your are not alone here at SUN developer forum. May be some give me a useful answer of my question and who is not memeber of java programming forum. that's allI think your are just one of those guys who doesn't read a post carefully.
    If you take a look at your other post I did give you an answer in reply # 1. Read Carefully.
    So before you tell me what's my problem you should read the thread carefully.
    and If you carefully read reply#1 I did state read your other thread for solution.

  • Applying the Shortcut key Tab to JTextField to focuse one by one

    how are we Focusing the JTextField one by one by using the Shortcut Key Tab,as per our specified ordering of JTextFields.
    In my application,i used the Shortcut key Tab for JTextField by focusing the JTextFields for each JTextField key event...but i could not get the result successfully.Do u have solution means u reply me plz.......

    as per our specified ordering of JTextFields.set your own FocusTraversalPolicy()
    http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html#customFocusTraversal

Maybe you are looking for

  • Ipod classic 120 stuck in disk mode, not recognized by windows or itunes

    so ive been havin tons of problems with my new ipod 120 classic first one day when i plugged it in it told me it was corrupted and needed to be restored then it would not restore i formated it with windows but that didnt seem to do anything the other

  • Balance between Vendor balance and GL

    Hi Experts, We are in the process on confirming the balance between the subledger recon account and the vendor balances.However,we find that there is a huge difference between the total balances of all the vendors and subledger and the balances do no

  • BAD parse error: zero-length content

    Hi there! Unfortunately I have a problem with JavaMail which I can not reproduce. Therefore, I don't have any 'debug' output of JavaMail. But maybe some of you have a clue for me. :) This is the error stack (just a snippet) which I get from JavaMail:

  • App World "My World" and Addendum Agreement....

    I have a New 9810 and App World has not worked since I took it out of the box.  Everytime I try to open the "My World" section or download an app it askes me to agree to the Addendum Agreement.  I accept and then it just goes back to the home screen.

  • [REQUEST] Gargoyle

    Gargoyle is an IF player that supports all the major interactive fiction formats. Most interactive fiction is distributed as portable game files. These portable game files come in many formats. In the past, you used to have to download a separate pla