Focus on a JTextField

I have a JTextField which is in a JPanel in a JFrame. I have tried grabFocus() and requestFocus() but neither seem to work in ensuring that when the frame is launched that the cursor is blinking on the textbox. Unfortunately I am working on a project where the client is not very keen on using the mouse! Has anyone any ideas on how to ensure that the TextField has the cursor blinking and the focus when it is launched!
Thanks in advance

I have a JTextField which is in a JPanel in a JFrame.
I have tried grabFocus() and requestFocus() but
neither seem to work in ensuring that when the frame
is launched that the cursor is blinking on the
textbox.
There are some bugs related to Focus management in JDK 1.3.x. They are fixed in JDK 1.4.
Unfortunately I am working on a project where
the client is not very keen on using the mouse! Has
anyone any ideas on how to ensure that the TextField
has the cursor blinking and the focus when it is
launched!Fortunately, there is a workaround though :
JTextField myTextField = new JTextField();
//.... add this textfield to your panel etc...
  Runnable doHelloWorld = new Runnable() {
     public void run() {    
    myTextField.requestFocus();
SwingUtilities.invokeLater(doHelloWorld);
myFrame.setVisible();

Similar Messages

  • Custom focus rectangle in JTextField

    I'm trying to change my theme/look & feel to show a focus rectangle for JTextField, somewhat like this: [http://www.macvswindows.com/index.php?title=GUI_Customization|http://www.macvswindows.com/index.php?title=GUI_Customization] (second image down, or direct [http://www.macvswindows.com/images/thumb/f/f2/osx_aqua_colors.png/500px-osx_aqua_colors.png|http://www.macvswindows.com/images/thumb/f/f2/osx_aqua_colors.png/500px-osx_aqua_colors.png] ) I don't want to make it exactly like MacOS, but a similar idea.
    For now I'm just trying to do it on the inner part of the field. I can get it to paint with the code below, but then the caret painting messes things up as I tab through the fields or move the caret around inside the fields.
    So it seems I'm headed down the wrong path, what should I be doing? Extending DefaultHighlighter or DefaultCaret, or something else?
    Thanks,
    Jim
    package testui;
    import javax.swing.*;
    import javax.swing.plaf.metal.DefaultMetalTheme;
    import javax.swing.plaf.metal.MetalLookAndFeel;
    public class ThemeTest extends JFrame {
        public class TestMetalTheme extends DefaultMetalTheme {
            public void addCustomEntriesToTable(UIDefaults table) {
                UIManager.put("TextFieldUI", "customui.CustomTextFieldUI");
            public String getName() {
                return "TestMetalTheme";
        public static void main(String[] args) {
            ThemeTest testFrame = new ThemeTest();
            testFrame.setVisible(true);
        public ThemeTest() {
            try {
                MetalLookAndFeel.setCurrentTheme(new TestMetalTheme());
                UIManager.setLookAndFeel(new MetalLookAndFeel());
            } catch (Exception e) {
                e.printStackTrace();
            setSize(500, 500);
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            JPanel panel = new JPanel();
            add(panel);
            panel.add(new JTextField("test"));
            panel.add(new JTextField("test"));
            panel.add(new JTextField("test"));
            panel.add(new JButton("button"));
    package testui;
    import javax.swing.*;
    import javax.swing.plaf.ComponentUI;
    import javax.swing.plaf.metal.MetalTextFieldUI;
    import java.awt.*;
    public class CustomTextFieldUI extends MetalTextFieldUI {
        private Color focusColor = Color.cyan;
        private JComponent component;
        public CustomTextFieldUI(JComponent c) {
            if (c == null) {
                throw new IllegalArgumentException("component must be specified");
            this.component = c;
        public static ComponentUI createUI(JComponent c) {
            return new CustomTextFieldUI(c);
        protected void paintSafely(Graphics g) {
            super.paintSafely(g);
            if (component.hasFocus()) {
                Dimension size = component.getSize();
                Graphics2D g2d = (Graphics2D) g;
                System.out.println(g2d.getClip());
                System.out.println(g2d.getClipBounds());
                g2d.setColor(focusColor);
                g2d.setStroke(new BasicStroke(2f));
                g2d.drawRect(1, 1, size.width - 3, size.height - 3);
    }

    Why not just combine the two approaches?
    import java.awt.*;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import javax.swing.*;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.Border;
    import javax.swing.plaf.ComponentUI;
    import javax.swing.plaf.metal.MetalTextFieldUI;
    public class CustomTextFieldUI extends MetalTextFieldUI {
         private Color focusColor = Color.cyan;
         private JComponent component;
         private Border normalBorder;
         private Border focusedBorder;
         private FocusListener focusListener;
         public CustomTextFieldUI( JComponent c ) {
              if ( c == null ) {
                   throw new IllegalArgumentException( "component must be specified" );
              this.component = c;
              focusListener =  new FocusListener() {
                   public void focusGained( FocusEvent fe ) {
                        if ( normalBorder == null ) {
                             normalBorder = component.getBorder();
                             focusedBorder = new BevelBorder( BevelBorder.LOWERED ) {
                                  @Override
                                  public Color getHighlightInnerColor() { return focusColor; }
                                  @Override
                                  public Color getHighlightOuterColor() { return focusColor; }
                                  @Override
                                  public Color getShadowInnerColor() { return focusColor; }
                                  @Override
                                  public Color getShadowOuterColor() { return focusColor; }
                        component.setBorder( focusedBorder );
                   public void focusLost( FocusEvent fe ) {
                        component.setBorder( normalBorder );
         public static ComponentUI createUI( JComponent c ) {
              return new CustomTextFieldUI ( c );
         @Override
         protected void installListeners() {
              super.installListeners();
              component.addFocusListener( focusListener );
         @Override
         protected void uninstallListeners() {
              super.uninstallListeners();
              component.removeFocusListener( focusListener );
    }

  • Problem while adding both Key And Focus Listeners to JTextField

    Hi!
    I have something peculiar while adding Key and Focus Listener to JTextField. Suppose i add just Key Listener then everything's fine and i could keep track of keys being pressed. But as soon as i add a Focus Listener to it with the code to select full text in focusGained() method, it starts reponding wrongly to arrow keys pressed and does not perform desired actions. For let arrow key it moves caret by one for the first time after that it does not resond to that unless caret is changed by using mouse. If right arrow key is pressed the it moves the caret to last position from wherever it is. For UP and DOWN it selects the full text(This should be done when it gets focus)
    public void focusGained(FocusEvent fe)
    setCaretPosition(0);
    moveCaretPosition(getDocument().getLength());
    Can someone help me out on this?
    thanks and regards,
    Amit.

    None of those things will cause your JFrame to resize itself. And this is probably a good thing, because your JFrame shouldn't change size once you have created it. Why not create your JPanel so that it has enough space for you to add the component later? Or why not just add the component to start with and then enable it or make it editable when you decide that's necessary?

  • Open and Close OnScreen Keyboard while focus gain on JTextField

    Hi
    I have a Jtextfield when ever I click on textfield I want to open OSK(On Screen Keyboard) of Windows 8 OS and windows 7.
    I tried in below mentioned way to open and close in focus listener focusGained() and focusLost() but it is not working. could some body do needful.
    Opening OSK:
    builder = new ProcessBuilder("cmd /c " + sysroot + " /System32/osk.exe");
    Closing Osk:
    Runtime.getRuntime().exec("taskkill /f /im osk.exe");

    You need to start() the ProcessBuilder and you need to split the command like this:
    builder  = new ProcessBuilder("cmd", "/c", sysroot + " /System32/osk.exe");
    builder.start();
    And naturally you should wrap the call in a new Thread or use an ExecutorService to avoid EDT problems.

  • How to capture the event on changing focus from a JTextField?

    Hi All,
    I have got a problem...
    I want to do something (say some sort of validations/calculations) when I change the focus by pressing tab from a JTextField. But I am not able to do that.
    I tried with DocumentListener (jtf01.getDocument().addDocumentListener(this);). But in that case, it's calling the event everytime I ke-in something in the text field. But that's not what I want. I want to call that event only once, after the value is changed (user can paste a value, or even can key-in).
    Is there any way for this? Is there any method (like onChange() in javascript) that can do this.
    Please Help me...
    Regards,
    Ujjal

    Hi Michael,
    I am attaching my code. Actual code is very large containing 'n' number of components and ActionListeners. I am attaching only the relevant part.
    //more codes
    public class PaintSplitDisplay extends JApplet implements ActionListener
         JFrame jf01;
         JPanel jp01;
         JTextField jtf01, jtf02;
         //more codes
         public void start()
              //more codes
             jtf01 = new JTextField();
              jtf01.setPreferredSize(longField);
              jtf01.setFont(new Font("Courier new",0,12));
              jtf01.setInputVerifier(new InputVerifier(){public boolean verify(JComponent input)
                   //more codes
                   System.out.print("updating");
                   jtf02.setText("updated value");
                   System.out.print("updated");
                   return true;
              //more codes
              jtf02 = new JTextField();
              jtf02.setPreferredSize(mediumField);
              jtf02.setEditable(false);
              jp01.add(jtf02, gbc);
              //more codes
              jf01.add(jp01);
              jf01.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jf01.setVisible(true);
              //more codes
         public static void main(String args[])
              PaintSplitDisplay psp = new PaintSplitDisplay();
              psp.start();
         public void actionPerformed(ActionEvent ae)
              //more codes
    }As you can see I want to update the second JTextField based on some calculations. That should happen when I change the focus from my frist JTextField. I have called jtf02.setText() method inside InputVerifier. But it's giving error...
    Please suggest...
    Ujjal

  • How to gain focus to a JTextField in a Jwindow

    Hi Friends
    I am trying to create a Login screen which covers the entire desktop using a Jwindow.
    I have one JTextfield and JPassword field in the Jwindow but i am not able to gain focus to those text fields and not able to type anything in those fields...
    I am using java 1.4.2
    This is my program...
    public class Login implements ActionListener
            JWindow fs;
            JTextField tx1;
            JPasswordField tx2;
             public Login ()
                 fs= new JWindow(new JFrame());
                 tx1= new JTextField(12);
                 tx2= new JPasswordField(12);
                 JButton jb = new JButton();
                 fs.getContentPane().setLayout(new FlowLayout());
                 fs.getContentPane().add(tx1);
                 fs.getContentPane().add(tx2);
                 fs.getContentPane().add(jb);
                 fs.setSize(300,300);
                 fs.setVisible(true);
                 fs.show();
                 fs.toFront();
    public void actionPerformed (ActionEvent e)
         System.out.println("User id "+tx1.getText()+" and Password is : "+tx2.getText()):
    public static void main(String[] args)
        new Login();
         Can some one help me in solving this issue with JWINDOW... Plz dont suggest JFrame , since i am not willing to use that header....
    Thanks in advance
    Ur Friend.

    Swing releated questions should be posted in the Swing forum.
    Check out this posting, found in the Swing forum:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=675445
    Plz dont suggest JFrame , since i am not willing to use that header....
    JFrame.setDefaultLookAndFeelDecorated(false);

  • Allow focus after disabling JTextField

    I have a form with several textfields. Two textfields are mutually exclusive; you can modify one or the other, but not both. Upon edit of one, I disable the other. This works perfectly. My problem is the tab order disappears upon disabling the textfield. If I edit fieldA, fieldB is appropriately disabled upon focusLost of fieldA. I can use the tab key multiple times, but focus is never set to another component on the form. How can I get around this?
    Here's the sample code:
          fieldA.addFocusListener(
                new FocusAdapter()
                   public void focusLost(FocusEvent focusEvent)
                         JTextField field = (JTextField)focusEvent.getSource();
                         // if the value was changed, disallow editing in trade field
                         String newValue = field.getText();
                         if (!newValue.equalsIgnoreCase(original))
                            fieldB.setEnabled(false);
                         // need else block in case the user changes the value, then changes it back to the original value
                         else
                            fieldB.setEnabled(true);
             );

    public void focusLost(FocusEvent e)
         if (textField2 == e.getOppositeComponent())
              textField2.transferFocus();
         textField2.setEnabled( false );
    }

  • To get the focus to a JTextField

    Hi,
    In my project,I am using a JFrame as a background .And I put a JDeskotppane.On that pane i put JInternalFrame.
    My JInternalFrame contains so many JButtons and JTextFields.
    My need is when I run the project the focus sholud be in my first JTextField.But the focus automatically goes to the JButton which is my first component.
    I try with following methods.
    jTextField1.requestFocus()
    jTextField1.requestFocusInWindow().
    But not .Is ther any way to do it?
    Thank you so much.
    Meena.

    Hi,
    Thank you so much.
    I write the coding of
    jTextField1.requestFocusInWindow() in Window Activated event.
    I got the result I want.
    The link given by you is very useful to me.
    Thank you so much
    Meena.

  • Problems whith focus in a JTextField!!!

    Hello:
    I have a JTextField inside a JFrame, at the beginning, when I open the window the Focus appears in the JTextField.I put disabled this JTextField and later i put it enabled. I would like that the Focus came back to appear in that JTextField.
    I have used the method "grabFocus" and doesn�t work.
    What can i use?
    Thanks in advance.
    M�nica

    If you read the sdk api doc for grabFocus() you will see that a client code should use requestFocus() instead.

  • Focus of a JTextField & font size.

    The program has a FlowLayout in which 2 JTextFields are added by means of
    add(new JScrollPane(verbInstructions));
    add(new JScrollPane(verbTextBox));
    How can the focus be set to verbTextBox elsewhere in the program?
    Also how can the size of the text moved to a JTextField be in a smaller font than the default?
    Thanks for your help.
    Edited by: zscipio on Sep 30, 2009 7:41 AM

    camickr wrote:
    grabFocus worked. Yes, but if you read the API you will find:
    This method is intended for use by focus implementations. Client code should not use this method; instead, it should use requestFocusInWindow().
    Ah! Sorry, OP. Then again...
    That is why Swing related questions should be posted in the Swing forum.A fair point!
    What's the reasoning behind this, out of interest?

  • How to disable the tab focusing for a JTextField object because those ...

    Hi All,
    Here I need some help. I want to disable the tab focusing( tab index) for a JTextField objects because those objects are set as setEditable(false). Also can u tell me about how to change the tab index orders for JTextFields.
    Many thanks,
    Vijaycanaan.

    I want to disable the tab focusing( tab index) for a JTextField objectsLook through the API and find methods with the word "focus" in the method name.
    Also can u tell me about how to change the tab index orders for JTextFields."How to Use the Focus Sub System":
    http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html

  • Giving focus with mutpile JTextFields

    Hey,
    if i have two JTextFields, is it possible for me to give focus to a different one than the one at the top? I.e, i have three text fields, however i dont want to focus to go to the top one (which it does by default), i would like to give the second one focus, is this possible at all? Thank you!

    so, would it look like
    oldField.requestFocus;[ ? (oldField being the textfield)
    or is there more to it? (thanks for the reply btw ^^)

  • Focus lose to JTextField

    Hi All,
    The requirement is, on change of text in JTextField, I need to read the value of the text and do some calculation and display result in another text field. From the book I found that action listener could be added but we need to press "Enter" button to trigger this event. Please guide me on how to achive this.
    Thanks in adnvace.

    Use a FocusListener or an InputVerifier.

  • Can not focus or edit on JTextField on SuSe Linux 9.1

    Hi,
    I am trying to debug a strange problem with JTextField on SuSe Linux 9.1.
    The problem is that the mouse click can not gain focus to the JTextField
    in a very high frequency. Once problem occurs, the keyboard tab also
    does not work. The problem does not happen all the time.
    I wrote a simple event listener that dump out events that confirm that
    the TextField got the mouse click event.
    We are using JDK1.4.2_05.
    The same piece of code works fine with Windows XP and RedHat.
    I would greately appreciated if you have any suggestion to debug this
    issue.
    Thanks,

    The first thing to do is identify which of the two rows with the same key value are correctly referenced by rows in other tables.  If all referencing rows relate to only one of the errant pair then you can insert the non-key values from the other
    one into a new row, and then delete the original 'bad' row.  If you find that there are rows in referencing tables which relate to each of the errant pair, then, after copying the non-key values from one into a new row and deleting the 'bad'  original,
    you'll need to change the foreign key values in those rows in any referencing tables which related to the 'bad'  original to the value of the primary key in its replacement row.  You'll need to delete the relationship before doing any of this of
    course.
    Once you've done the above I'd then be inclined to copy the table to a new one under a different name, delete the original table, rename the copy to the original name, and then re-create the enforced relationship.  Finally, compact and repair the database.
    Ken Sheridan, Stafford, England

  • JTextField not gaining focus on initialization of Applet

    I originally tried posting this in the Applets forum but was unable to get a response, so I am re-posting here in hopes of finding an answer.
    I have a simple JApplet with a JFrame, a JTextField added to the JFrame, and a WindowListener added to the JFrame that requests focus to the JTextField whenever the JFrame is activated. Upon opening the applet the WindowListener's windowActivated() method is called and requestFocusInWindow() for the JTextField returns true however the focus is never actually given to the JTextField. According to the API for Component,
    "This method returns a boolean value. If false is returned, the request is guaranteed to fail. If true is returned, the request will succeed unless it is vetoed, or an extraordinary event, such as disposal of the Component's peer, occurs before the request can be granted by the native windowing system. Again, while a return value of true indicates that the request is likely to succeed, developers must never assume that this Component is the focus owner until this Component receives a FOCUS_GAINED event"
    I am assuming that the request is getting "vetoed" but I don't understand why or what this even means. If I alt-tab off of the applet window and alt-tab back on then the request is handled properly. This issue only arises on initially opening the applet. Has anyone seen this issue before? Is there a known workaround? Here is the code for my sample applet:
    import javax.swing.*;
    import java.awt.event.*;
    public class MyApplet extends JApplet{
    private JFrame myFrame;
    private JTextField myTextField;
    private FrameWindowListener myListener;
    public void init(){
    myFrame = new JFrame();
    myFrame.setSize(700, 360);
    myFrame.setLocation(100, 100);
    myTextField = new JTextField();
    myFrame.add(myTextField);
    myListener = new FrameWindowListener();
    myFrame.addWindowListener(myListener);
    public void start(){
    myFrame.setVisible(true);
    myFrame.pack();
    public class FrameWindowListener extends WindowAdapter{
    public void windowActivated(WindowEvent e){
    boolean focus = myTextField.requestFocusInWindow();
    if(focus){
    System.out.println("Focus successful");
    } else{
    System.out.println("Focus unsuccessful");
    }

    Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
    http://forum.java.sun.com/help.jspa?sec=formatting
    Works fine for me using JDK1.4.2 on XP using appletviewer.
    The only suggestion I would make is that you should use pack() before setVisible(...). Also I usually have that code in the init() method instead of the start() method.

Maybe you are looking for