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 ^^)

Similar Messages

  • 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

  • Giving focus to a component

    Hi all,
    How does one give focus back or just plain giving focus to a JComponent
    e.g. JTextField, JButton, etc.
    This puzzles, me please help?

    That method was introduced in 1.4, but the API recommends you use requestFocusInWindow()

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

  • Giving focus to the program

    I need to make a Java program give focus to itself.
    I'm thinking of a thread that would give focus to the program every second.
    But I dont know how to make it "give focus to this program on the computer". With my searches, I can only find about giving focus to a component of the program, not the program in the computer/os
    The program will run in Windows, so something platform specific would be ok.
    Or any other way to make this Java program regain focus automatically about every second.

    In brief, I need to do it for a barcode system. It's somewhat complicated, the commerce system uses php and is online. In this system, I added an applet which recieves events from a local program (the one I want to auto-focus).
    This local program recieves events from the barcode scanner. But a barcode scanner is stupid, and considered like a keyboard for the computer, so a program must be in focus to recieve the events. The best solution I could think of is to make this local program always takes the focus. The interface of this program would be small (or no interface at al).
    All of this system is done and works correctly. The only piece of this puzzle that is missing is having the local program always recieve events from the scanner.
    The computer that will run it is the "cash regitster" computer for the store, so having this local program always gaining focus is correct. And if needed, this "auto-focus" could be deactivated while the computer is needed for other things.
    So the real point is maning sure the local program gains focus about every second so it recieves the events of the scanner, since the scanner is considered like a keyboard.

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

  • Giving focus to a JPanel

    I need to give the keyboard focus to an object, myJPanel, that extends JPanel. Calling myJPanel.isFocusable returns true, but when I try to give that object the focus with myJPanel.requestFocusInWindow, that method returns false and focus isn't transferred. Anybody have some ideas on what I'm doing wrong?
    Thanks in advance.
    --Jay                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Thanks for the help, both of you. What's driving me nuts is that the JPanel already is focusable, at least according to the isFocusable method. Code like this:
    System.err.println(this.isFocusable());
    this.setFocusable(true);
    System.err.println(this.isFocusable());
    System.err.println(this.requestFocusInWindow());
    prints out "true true false false." Apparently it is possible to give my JFrame the focus, but I'm just not doing it correctly. Also, I did call addKeyListener, but this is my first time using KeyListeners and it's totally possible I screwed that up too. Regardless, if the JFrame that's supposed to be listening for KeyEvents doesn't have the focus, then it won't pick up those KeyEvents whether the listener is set correctly or not. (At least, that's my reading of the Java documentation.)
    Anyway, thanks for your advice, and any more ideas would be totally appreciated.
    --Jay                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Back button focusing with the 6D

    I cannot get my 6D's back button focus (AF-ON) to work.  After following directions on Canon's website on how to set it up, the button just does not do anything.  Auto focus only works  with the shutter button.  I have the function set to "P" which I understood to be o.k.  Would resetting the camera to factory default help?  I would prefer not to have to send the camera to Canon for a one button repair.  The camera body was purchased new and is still under warranty.
    Thanks
    Solved!
    Go to Solution.

    It's super easy to set up BBF on a 6D....
    If you have already been changing some things and are unsure which ones, you might want to reset all the Custom Functions to factory default, before starting. (Note: There is a way to view which C.Fns are set and to what each is assigned... As you enter each of the four C.Fn groups, note the list in the lower LH corner of the LCD screen, that shows all the C.Fns in that group at a glance. The top line is the C.Fn number, the bottom line is the setting for each C.Fn.)
    To set up BBF....
    All you have to do is go into the menu, Custom Functions, C.Fn III-5, operations/others, button assignments. Select and enter that and then press "set" and this should take you right to the top of the LH column, which is a graphic illustration of the shutter release button. Press set again to enter this, then scroll to select the center option "start metering" and press "set" once more to select this choice, then press "menu" button several times to back out of the menus. Done!
    What this does is remove AF start from the shutter release button.  By default it's already assigned to the AF-On button on the back of the camera too, so BBF is set up and ready to use as soon as you remove it from the shutter release button.
    Metering and Image Stabilization will continue to start with a half press of the shutter release button or whenever you press the AF-On button. But AF will  only start with your thumb on the AF-On button. Using BBF, you now can use AI Servo most of the time, for stationary or moving subjects. If you want to "focus and recompose", simply focus and then lift your thumb off the AF-On button to leave focus where it is and recompose as you see fit. (Without BBF, you cannot do focus and recompose.... it will cause mis-focused shots.) You still might want to switch back to One Shot when you want high precision focus with stationary subjects.
    There is another option you may want to consider...
    Using the same Custom Function III-5, if you prefer you can swap the functions of the AF-On and * (AE Lock) buttons. I do this on my cameras for a couple reasons: One is that the * button is larger, more prominent, and closer to my thumb... so I prefer to use it for focusing. The other reason is that older Canon models that didn't have the AF-On button, you had to use the * button and that's the way I learned to use BBF (Note: In some cases there was an AF-On button on the body but not on the vertical grip, while older cameras simply didn't have an AF-On button at all, on the body or the grip).
    Alan Myers
    San Jose, Calif., USA
    "Walk softly and carry a big lens."
    GEAR: 5DII, 7D(x2), 50D(x3), some other cameras, various lenses & accessories
    FLICKR & PRINTROOM 

  • I have a 2012 Ford Focus with bluetooth messeging and I was wondering if the iphone 3gs has bluetooth messeging capabilities?

    I have a 2012 Ford Focus with bluetooth messeging and I was wondering if the iphone 3gs has bluetooth messeging capabilities?

    No. The iPhone does not support the MAP (Message Access Protocol) bluetooth profile.

  • Giving Focus to Window/Frame

    Hi
    I am unable to give focus to newly opened window/frame
    How can I do it? A quick reply would be appreciated as I need it urgently
    Thanx in advance
    jods

    When you initialize the Window/Frame set it to focusable with setFocusable(true) and then simply call requestFocus()

  • Giving "focus" to a folder in Mail: only with the keyboard?

    Hello everybody,
    I've found that in Mail, you can choose a folder with the mouse, but that you cannot activate it, you cannot give it the focus.
    When you click on a folder, it becomes pale blue and the arrow keys do not allow to go from one folder to the other. The focus is in the mails pane.
    The only way to give the focus to a folder is through the keyboard, using Shift-Tab (or Tab several times): the folder then becomes dark blue, it "has the focus", and the arrow keys allow to go from one folder to the other, or to open and close folders.
    This is an interface issue, and is highly unusual. Am I the only one to observe this?
    If I am the only one, then I have a bug somewhere. If not, Mail has an interface problem that I will report to Apple, hoping for the best.
    Thanks for your input, and Cheers!
    Roger the Photographer
    G5 1.8Dual, 2GB RAM   Mac OS X (10.4.8)   20" App Dsplay, ext. Lacie, iPod, Bach on Al-Lansing, Canon 5D, Canon L glass

    Hello Roger.
    What you’ve described is exactly how it works.
    Although I agree that this is non-standard behavior,
    I have the feeling that it’s intentional, not a bug.
    There are other situations in Mail where the view
    that handles the keystrokes is what the user is most
    likely to want rather than what has focus.
    If you have the preview pane visible, for example,
    and the view that has focus is the message list, the
    arrow keys let you select another message, but the
    Page Up/Down keys are handled by the preview instead,
    regardless of whether it has focus or not. Only if
    the preview pane is hidden does the message list
    respond to Page Up/Down keystrokes.
    Hi David,
    I've just discussed the thing rather extensively with an ex-senior scientist at Apple. I think that he is right - as you are -, this is intended behaviour.
    Whether it is a good idea or not is a different matter however. Apple's keyboard commands have never been as complete, or precise, as Microsoft's. Remark that this is not a compliment to Microsoft whose interface is at times simply terrible! But here, it's not the keyboard command policy that is not systematic, it's the response of the mouse. And this I find very surprising. I have 51 mailboxes in Mail and the more control I have, the happier I am, that's for sure!
    On the other hand, what surprised me is the fact that the mouse does not respond in the same way in, say, Mail and iTunes. In iTunes, if you click on a "folder" (they call them playlists, which is fine, but this is about the same as a folder is it not?), not only you select it, but you activate it: you give it the focus plain and simple.
    Look at Font Book: here also, you have what a power user is waiting for: clicking on a "folder", or a list or group, you give it the focus plain and simple. Idem in Address Book. iPhoto also, but then it's the tab key behaviour that's strange.
    I can see from here programming teams clashing over points like this one. I would greatly prefer that Apple's applications adopt a predictable behaviour from one app to the other.
    "Behaviour by design", all right. I will nonetheless send to Apple what we could call an "enhancement request".
    Cheers!
    Roger the Photographer
    G5 1.8Dual, 2GB RAM   Mac OS X (10.4.8)   20" App Dsplay, ext. Lacie, iPod, Bach on Al-Lansing, Canon 5D, Canon L glass

  • 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

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

Maybe you are looking for