Moowing focus with the tab key (swing)

Hi. I have a JFrame with 4 text areas in. I want to be able to "hop" to the next text area by pressing the tab key. Most internet pages says this is default, but when I press tab, I get a tab space inside the text area I'm in.. Any ideas on how to do this? (i use Java 1.5)

HashSet focusForward = new HashSet();
HashSet focusBackward = new HashSet();
focusForward.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,0));
focusBackward.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,InputEvent.SHIFT_DOWN_MASK));
    myTextArea.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,focusForward);
myTextArea.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,focusBackward);

Similar Messages

  • Moving the Focus with the TAB key in a JTextArea Component

    Dear Friends,
    I have exhausted all options of moving focus from JTextArea to next component. I have also tried all suggestions available in this forum. But i'm not able to solve my problem. Can any one help me.
    Thanx in advance.

    I had the same problem before. Here is what i did.
    JTextArea txtArea = new JTextArea(2,15);
    Set forwardTraversalKeys = new HashSet();     
    forwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));          
    txtArea.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,forwardTraversalKeys);          
    Set backwardTraversalKeys = new HashSet();          
    backwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK));          
    txtArea.setFocusTraversalKeys( KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, backwardTraversalKeys);
    JScrollPane scrollPane = new JScrollPane(
         txtArea,
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    // the scrollbar of the JScrollPane is focusable that's why it requires
    // another TAB key to transfer the focus.
    scrollPane.getVerticalScrollBar().setFocusable(false);

  • KeyEvents with the TAB Key

    Hey All,
    I have a small progam with a small problem. My program is an applet with numerous textfields and I have implemented the KeyEvents event listener. What I want to have happened when I press the "Tab Key" is the cursor move from one tab to another, but when it goes to the next tab it clears out the text that is currently in the textfield. Take a look at my code segment that is giving me the problem.
    public void keyPressed(KeyEvent e)
    if(NameField == e.getSource())
              if(e.getKeyCode() == KeyEvent.VK_TAB)
                   SalaryField.setText(" ");
    I know that is works if I replace "VK_TAB" with something else like "VK_A". "NameField" and "SalaryField" are the names of mt textfields. I am currently using Java SDK 1.3.1 to program in java program, but my browser uses JVM/Runtime Enviornment 1.4.1. When I run it with my broswer nothing happens when I press tab and some for the program that I am using to progam in. I did a search in the forum and came up with I have above, but still cannot it to work. When I read APIs on 1.4.1 and 1.3.1 that both said that
    "Aside from those keys that are defined by the Java language (VK_ENTER, VK_BACK_SPACE, and VK_TAB), do not rely on the values of the VK_ constants. Sun reserves the right to change these values as needed to accomodate a wider range of keyboards in the future."
    What is going on? How can I solve this problem?
    Thanks,
    Iceman
    PS:
    My Interface is swing

    Hey All,
    Thanks for the help I got to work when I ran it with my programming program, but when I run it in a browser using the current JVM the tab key does not work. What is wrong now? Or how am I to use FocusListener now, I tried to use the getOppositeComponent(, my complier says that it is not a method of FocusListener. Even though java says in the docmentation that it is. Can I get some more help here. The questions again is How can I tab in a applet?
    Later,
    Iceman

  • Strange behavior with the tab key and multiple users

    Hello,
    I'm stuck on this problem and none of the usual trouble-shooting techniques have yielded results, so perhaps someone will point me the right direction.
    I have an Intel iMac running 10.3.9 with two user accounts, and in one of the accounts the tab key fails to advance the cursor from field to field in any application, be it a browser, mail client, etc. The tab key works otherwise, I can switch between applications using apple tab, for instance. The other user account works fine. The keyboard & Mouse preferences are identical on both user accounts. In fact, after creating a new user account it too had no tabbing from field to field either, which would seem to indicate that it is not a problem in an individual account. Repairing the permissions did not help, and even a recent archive and install failed to change this. Anyone know where to look for an answer? Thanks in advance...
    iMac 2GHz Intel Core 2 Duo Mac OS X (10.4.9)

    I did a wholesale replacement of the preferences folder from the working account to the non-working one, and after going through the welcome screens and re-setting a variety of preferences (setting up mail.app again, etc...), the tab key is functioning as expected in all applications. Thanks!

  • What's with the tab key in the new version of Pages

    In the previous version I could have a list and was able to tab within a line in that list and it would recognize the tabs. Now, if you are in line, shifts the position of the list level.
    Version 2
    1. My list line could tab to here $50.00
    2. Second line
    3. and so on.
    Version 3
    a. My list line (shifts the list if you click the tab key) can't add anything
    2. Second line
    3. and so on.
    NOTE: the a. line under version 3 is indented when the tab key is clicked. If I do this in this reply box, this line won't even show up. That's why I edited my post.
    Or do I have something buggy when shifting from 2 to 3. (I already threw 2 away.)
    Message was edited by: darrenv
    Message was edited by: darrenv

    The fn key is on the portables, not the stand-alone keyboards. It allows for a smaller/less keys keyboard & still lets you do things like forward delete by holding down the fn key & pressing delete.

  • KeyStrokes with the Tab Key

    Hi,
    I am making a Desktop Application using a JDesktopPane. I want to allow my users to cycle between internal frames quickly by pressing CTRL-TAB. I created the Action object and set its accelerator value, but the action refuses to trigger when i press CTRL-TAB. I have boiled the problem down to the following sample application. This is using jdk 1.5.0, i haven't tried other versions.
    I create three actions, CTRL-ENTER, CTRL-TAB, and CTRL-SPACE. All three VK_ keys are listed in the javadoc for the KeyStroke.getKeyStroke(int keyCode,int modifiers) method.
    Here is the sample application
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class MyTest extends JFrame
       public MyTest()
          super( "My Test" );
          Action enter_action = new MyAction( "Enter" );
          enter_action.putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_ENTER, InputEvent.CTRL_DOWN_MASK ) );
          Action tab_action = new MyAction( "Tab" );
          tab_action.putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_TAB, InputEvent.CTRL_DOWN_MASK ) );
          Action space_action = new MyAction( "Space" );
          space_action.putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_SPACE, InputEvent.CTRL_DOWN_MASK ) );
          JMenuBar menu_bar = new JMenuBar();
          JMenu menu = new JMenu( "My Menu" );
          menu.add( enter_action );
          menu.add( tab_action );
          menu.add( space_action );
          menu_bar.add( menu );
          this.setJMenuBar( menu_bar );
       public static void main( String[] args )
          MyTest my_desk = new MyTest();
          my_desk.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
          my_desk.setSize( 600, 600 );
          my_desk.setVisible( true );
       private static class MyAction extends AbstractAction
          public MyAction( String name )
          {  super( name );  }
          public void actionPerformed( ActionEvent e )
          {  System.out.println( this.getValue( Action.NAME ) + " Performed" );  }
    }Why is the CTRL-TAB accelerator not working? Both the other actions work fine. The action fires if you choose the menu item, but not if you press the accelerator. Is this a bug with 1.5?
    Thanks for any help,
    Reg

    Boy this road looks familiar.
    If the objects are on the same panel navigation comes free.
    Alternatively you can create an input map and action map.
    This is how I solved keystroke issues in my project
    for a component c you can use
    c.getInputMap() and
    c.getActionMap()
    In the following example I modified a text editing component to undo the meaning of + - * and /
    and replace it with specialized actions
    hope this helps
        public void mapKeyStrokes(InputMap im, ActionMap am) {
            im.remove(KeyStroke.getKeyStroke('+'));
            im.remove(KeyStroke.getKeyStroke('-'));
            im.remove(KeyStroke.getKeyStroke('*'));
            im.remove(KeyStroke.getKeyStroke('/'));
            im.remove(KeyStroke.getKeyStroke('%'));
            im.put(KeyStroke.getKeyStroke('+'),"add");
            im.put(KeyStroke.getKeyStroke('-'),"sub");
            im.put(KeyStroke.getKeyStroke('*'),"mpy");
            im.put(KeyStroke.getKeyStroke('/'),"div");
            im.put(KeyStroke.getKeyStroke('%'),"percent");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0),"enter");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ADD,0),"add");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SUBTRACT,0),"sub");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_MULTIPLY,0),"mpy");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DIVIDE,0),"div");
            am.put("enter",fixedActions[13]);
            am.put("add",fixedActions[8]);
            am.put("sub",fixedActions[3]);
            am.put("mpy",fixedActions[2]);
            am.put("div",fixedActions[1]);
            am.put("percent",tabbedActions[0][1]);
        }

  • On Mac, need to navigate to first google search listing by keystroke, the tab key works sometimesand sometimes the down arrow works, nothing works consistently

    If I do a search using the google search engine, say of a phone number like (530) 335-5414 it results in a page with about 10 to 15 listing. Here is what the page looks like
    https://www.google.com/?gws_rd=ssl#q=%28530%29%20335-5414
    I am on a mac and I need to find a keyboard command to get me reliably to select the first listing . When the caret appears next to the listing I can press the enter key to open the underlying hyperlink.
    I have had success doing this with the tab key and sometimes it works almost 8 times in a row. Then I sometimes use the down arrow key and it occasionally gets me there. IS THERE A RELIABLE KEYBOARD NAVIGATION TO THE FIRST LISTING ON A GOOGLE SEARCH RESULT PAGE. I don't understand why my keyboard only works occasionally to navigate in this way . This is very important for me to do this and maybe someone out there knows how to get to select the first listing on a page by keyboard that works.
    Thank you very much for you

    I've called the big guys to help you. Good luck.

  • Why does the "TAB" key no longer work to move the cursor from field to field with Firefox 17 in MAC OS 10.8?

    The "TAB" key will not move the cursor from field to field with Firefox 17 in MAC OS 10.8. You have to use the mouse to click on the new field to move the cursor.

    See:
    * http://kb.mozillazine.org/accessibility.tabfocus
    Note: In OS X (as of 2005-01), if this preference is not explicitly set, the “Full Keyboard Access” setting in System Preferences will be honored. All builds before that date (e.g., Firefox 1.0.x) will ignore that setting.
    This pref doesn't exist by default, so if you want to use it instead of the system settings then you need to create a new Integer pref with the name accessibility.tabfocus and set the value to what you want (7 is to tab through all the fields).

  • How to recognize the tab key in a JTextField

    I have a drawing program with a main window and a tools palette, which is a JDialog. The tools palette has JToggleButtons and one JTextField. When you have the focus in the JTextField and you press tab repeatedly, it tabs through all the JToggleButtons and then back into the JTextField.
    However I would like to recognize the pressing of the tab key and ask for the focus to go back to the main window.
    I subclassed the JTextField, added a KeyAdapter, but it does not recognize the tab key. I also added the processKeyBinding method, but it doesn't recognize the tab key either.
    How can I recognize the tab key?
    Here is a self-contained test program that illustrates the problem:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class AnanyaCurves extends JFrame
      Tools tools;
      public AnanyaCurves(Dimension windowSize)
        Basics.ananyaCurves = this;
        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        setTitle("Ananya Curves");
        tools = new Tools(this);
      public static void main(String[] args)
        int toolsWidth;
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        toolsWidth = 200;
        Dimension windowSize = new Dimension(screenSize.width - toolsWidth, screenSize.height - 58);
        AnanyaCurves ananyaCurves = new AnanyaCurves(windowSize);
        ananyaCurves.pack();
        ananyaCurves.setBounds(toolsWidth, 0, windowSize.width, windowSize.height);
        ananyaCurves.setVisible(true);
        ananyaCurves.requestFocus();
      public void setVisible(boolean b)
        tools.setVisible(b);
        super.setVisible(b);
    class Basics extends java.lang.Object
      public static AnanyaCurves ananyaCurves;
      public Basics()
    class Tools extends JDialog
      JToggleButton btnGrid;
      JTextField textGrid;
      JPanel panel;
      public Tools(JFrame frame)
        super(frame, "Tools", false);
        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        btnGrid = makeBtn("Grid");
        textGrid = makeTextField();
        panel = makePanel();
        pack();
      public JToggleButton makeBtn(String name)
        JToggleButton btn = new JToggleButton();
        btn.setMaximumSize(new Dimension(108, 24));
        btn.setPreferredSize(new Dimension(108, 24));
        btn.setText(name);
        btn.setFont(new Font("Verdana", Font.PLAIN, 11));
        btn.setMargin(new Insets(5, 10, 5, 10));
        btn.setOpaque(true);
        return btn;
      public ACJTextField makeTextField()
        ACJTextField textField = new ACJTextField();
        textField.setFont(new Font("Verdana", Font.PLAIN, 12));
        textField.setMaximumSize(new Dimension(108, 20));
        textField.setPreferredSize(new Dimension(108, 20));
        textField.setText("0.25");
        textField.setEnabled(true);
        return textField;
      public JPanel makePanel()
        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.add(btnGrid);
        panel.add(textGrid);
        getContentPane().add(panel);
        return panel;
    class ACJTextField extends JTextField
      KeyAdaption keyAdaption;
      public ACJTextField()
        super();
        keyAdaption = new KeyAdaption();
        this.addKeyListener(keyAdaption);
      class KeyAdaption extends KeyAdapter
        public void keyPressed(KeyEvent event)
          int keyCode = event.getKeyCode();
          if (keyCode == KeyEvent.VK_TAB)
            Basics.ananyaCurves.requestFocus();
      protected boolean processKeyBinding(KeyStroke keyStroke, KeyEvent keyEvent, int int2, boolean boolean3)
        int keyCode = keyEvent.getKeyCode();
        if (keyCode == KeyEvent.VK_TAB)
          Basics.ananyaCurves.requestFocus();
          return false;
        return super.processKeyBinding(keyStroke, keyEvent, int2, boolean3);
    }Thanks for looking at this.

    Wow, Michael, you work like magic! Thanks so much! I would be happy to give you a commercial key to my Ananya Curves program also once the second release is on my website. It's a program for drawing curves in an easier way without pulling on tangent lines, with all control points right on the curve. Just send me an email to [email protected] if you are interested!

  • JButton gains focus when Hitting tab key but hitting Enter has no effect.

    Hi,
    I have a program that has two buttons. When pressed, using the mouse, the buttons text appears in the middle of the screen. I have NOT alerted the focus subsystem. Thus when I press the tab key the buttons are highlighted in turn, to indicate that they currently have focus. However if I press enter the buttons actions (to update the middle of the screen with it's text) does not get activated.
    I am using 1.4.2 on a Windows machine.
    any help on this would be much appreciated !!
    The code is as follows:
    package com.logicacmg.skynet.tms.mmi.ui;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import java.awt.Container;
    public class Test implements ActionListener
    JButton bTwo = new JButton("button 2");
    JButton b = new JButton("button 1");
    JLabel label = new JLabel(" ");
    /** Creates a new instance of Test */
    public Test()
    JFrame frame = new JFrame();
    //Create a panel to hold the MMI screens.
    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BorderLayout());
    b.addActionListener(this);
    bTwo.addActionListener(this);
    mainPanel.add(b, BorderLayout.WEST);
    mainPanel.add(bTwo, BorderLayout.EAST);
    mainPanel.add(label, BorderLayout.CENTER);
    //add the main panel which contains the screens and the status bar
    //to this frame.
    Container contentPane = frame.getContentPane();
         contentPane.add(mainPanel, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    public static void main(String [] args)
    new Test();
    public void actionPerformed(ActionEvent e)
    JButton aButton = (JButton)e.getSource();
    if(aButton == b)
    label.setText("one");
    else if(aButton == bTwo)
    label.setText("Two");

    Which plaf are you using? Because when I switch to the windows plaf, the behavior is what you describe.
    Demo:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class X {
        public static void main(String[] args) {
            final JFrame f = new JFrame("button focus");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            ActionListener al = new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    System.out.println(evt.getActionCommand());
            Container cp = f.getContentPane();
            cp.setLayout(new FlowLayout());
            for(int i=0; i<3; ++i) {
                JButton btn = new JButton("Button " + i);
                btn.addActionListener(al);
                cp.add(btn);
                if (i == 1)
                    f.getRootPane().setDefaultButton(btn);
            final JCheckBox laf = new JCheckBox("platform plaf");
            laf.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent evt) {
                    String cls = laf.isSelected() ? UIManager.getSystemLookAndFeelClassName() :
                      UIManager.getCrossPlatformLookAndFeelClassName();
                    try {
                        UIManager.setLookAndFeel(cls);
                        SwingUtilities.updateComponentTreeUI(f);
                    } catch (Exception e) {
                        e.printStackTrace();
            cp.add(laf);
            f.pack();
            f.setVisible(true);
    }

  • [Bug?] How to use the Tab key in forms

    Ahoy!
    The latest release of Photoshop has "broken" the native behavior of the Tab key in html panels. I'm not sure if this is a bug or just a new API I need to incorporate.
    Expected behavior:
    1. Focus into text field in a form
    2. Hit the Tab key
    3. The next field is focused.
    Actual behavior
    1. Focus into text field in a form
    2. Hit the Tab key
    3. Photoshop hides the application UI (Photoshop hotkey tab behavior).
    Anyone happen to know if there's something that can be done about this?

    Bug is very annoying for our users when they try to input their usernames and passwords to login (often) and also when they're filling out a large form with four fields in it.
    Hope it is fixed soon or a work around provided.
    Tom Wrenn
    Frontend Engineer
    CreativeWorx

  • Detecting the TAB key

    With a recent release of Java, a KeyListener no longer detects the TAB key, which is now apparently considered to be a focus event, not a keyboard event. It is critical to our application, a terminal emulator, that we be able to detect TAB and SHIFT-TAB. I read somewhere about a work-around involving a FocusListener, but a FocusListener does not report when the TAB key is pressed. Can somebody help me here?

    I seem to have solved the problem, and I'd like to present my solution in case anybody else runs across the problem.
    We use an AWTEventlistener. This is intended to watch AWT events but not handle them. However, there is no reason why we shouldn't process tab events within it. AWT will continue to process the tab key as a focus switch, but this solution enabled us to get our applet working again. I hope that future releases of Java will pay more attention to backward compatibility however, so that this kind of fix is not needed.
    In the canvas class:
    // Add the event listener provided we are on a version of the VM
    // that supports it.
    try {
    if (Class.forName("java.awt.event.AWTEventListener")!= null) {
         Toolkit.getDefaultToolkit().addAWTEventListener(new Myeventlistener(), AWTEvent.KEY_EVENT_MASK);
    } catch (Throwable e) {}
    import java.awt.*;
    import java.awt.event.*;
    public class Myeventlistener implements AWTEventListener
    public void eventDispatched(AWTEvent e)
    KeyEvent k = (KeyEvent) e;
    if (k.getID() == k.KEY_PRESSED) {
    if (k.getKeyCode() == 9) {
    if (k.isShiftDown())
    // Process as BackTab Key
    else
    // Process as tab Key

  • OnKeyTyped ignores the Tab key

    Hello,
    using Windows XP, SP 3, JavaFX 1u1 on Java 1.6.0_11 with the NetBeans JavaFX plugin, I noticed that the onKey[Pressed/Released/Typed] functions would not get key events caused by pressing the Tab key. Is there any reason for that?

    Typically, Tabs are consumed by the Focus subsystem and not passed along. See this tutorial that discusses Focus Listeners.
    http://java.sun.com/docs/books/tutorial/uiswing/events/focuslistener.html
    The Key Listener tutorial below has example code (near the bottom) that shows how to make Tab events available to a Key Listener at these lines:
    //Uncomment this if you wish to turn off focus
    //traversal. The focus subsystem consumeshttp://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html

  • Why do I have to use the tab key even more to tab between page elements.

    Firefox versions prior to ver 4 I used the tab key to tab between page elements (form elements, buttons, etc). I upgraded to ver 4 and now when I tab from form element to form element I first see a gray line outlining the element area and then another press of the tab the element becomes active for me to use. I now have to use double the tab keys to move between form elements.

    Hello new_mac_user, see if the next works
    # In the [[Location bar autocomplete|Location bar]], type '''about:config''' and press '''Enter'''. The about:config "''This might void your warranty!''" warning page may appear.
    # Click '''I'll be careful, I promise!''', to continue to the about:config page.
    # in search field type (or copy/paste from here) '''accessibility.tabfocus'''
    # double-click on it and change the value to '''4''' (probably you have 1 the default on mac)
    # click ok, exit firefox and restart it.
    with the above you give focus to links (and linked images) only when you press the tab key.
    see for more info : http://kb.mozillazine.org/Accessibility.tabfocus
    https://developer.mozilla.org/en-US/docs/Mozilla/Preferences/Preference_reference/accessibility.tabfocus
    thank you

  • Focusing JLable on Tab key..

    Hi All,
    I have a JFrame that has four text fields and two labels.
    basically they are with save and close images acting as the button
    for me.
    Now my problem is when I press the tab key, the focus transverse
    in all four text fields, but it never comes on JLables.
    Can anybody tell me how to achieve this.
    Hoping for a favorable response
    Kind Regards
    Chetan Chandarana

    Just a guess..
    label.setFocusable(true);

Maybe you are looking for