Using TAB to focus next component in a JTextArea

hello everybody,
I would like to use the TAB-key in a JTextArea to focus the next component in my frame.
I tried to use an KeyListener which calls an instance of javax.swing.FocusManager with the method
focusNextComponent(Component c).
My problem is, that - allthough I call consume() for the KeyEvent - the TAB is displayed im my JTextArea........
how can I solve this, that the TAB is NOT visible?
(plaese excuse my bad english )
Thanks Chris

The way to do it is use setNextFocusableComponent(Component c)
so as you create each component, you can set the order that the tab key will give focus.
eg
JButton b1 = new JButton();
JButton b2 = new JButton();
b1.setNextFocusableComponent(b2);
etc...
The tab won't be displayed in the JTextArea then,.
James

Similar Messages

  • Customize "Tab" key for JTextArea to focus next component.

    Hi,
    I am trying to change the "TAB" key behaviour for JTextArea, by using CustomAction configured via InputMap() and ActionMap(). When the user presses the Tab key, the focus should go the next component instead of tabbing in the same JTextArea component. Here is the code for the CustomAction().
        public static class CustomTabAction extends AbstractAction {
            private JComponent comp;
            public CustomTabAction (JComponent comp) {
                this.comp = comp;
                this.comp.getInputMap().put(KeyStroke.getKeyStroke("TAB"), "TABPressed");
                this.comp.getActionMap().put("TABPressed", this);
            public void actionPerformed(ActionEvent evt) {
                Object source = evt.getSource();
                if (source instanceof Component) {
                    FocusManager.getCurrentKeyboardFocusManager().
                            focusNextComponent((Component) source);
        }This works for most of the cases in my applicaiton. The problem is that it doesn't work with JTable which has a custom cell editor (JTextArea). In JTextArea field of JTable, if the Tab is pressed, nothing happens and the cursor remains in the custom JTextArea exactly at the same place, without even tabbing spaces. Here is the CustomCellEditor code.
        public class DescColCellEditor extends AbstractCellEditor implements TableCellEditor {
    //prepare the component.
            JComponent comp = new JTextArea();
            public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int rowIndex, int vColIndex) {
                // Configure Tab key to focus to next component
                CustomActions.setCustomAction("CustomTabAction", comp);
                // Configure the component with the specified value
                ((JTextArea)comp).setText((String)value);
                // Return the configured component
                return comp;
            // This method is called when editing is completed.
            // It must return the new value to be stored in the cell.
            public Object getCellEditorValue() {
                return ((JTextArea)comp).getText();
        }regards,
    nirvan

    >
    textArea.getInputMap().remove(....);but that won't work because the binding is actually defined in the parent InputMap. So I think you need to use code like:
    textArea.getInputMap().getParent().remove(...);But I'm not sure about this as I've never tried it.I tried removing the VK_TAB key from both the input map and parent input map as shown below. But I still have to press "TAB" twice in order to get out of the JTextArea column in JTable.
                comp.getInputMap().getParent().remove(
                            KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0));
                comp.getInputMap().remove(
                            KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0));after coding this, I am using the setFocusTraversalKeys for adding only "TAB" key as ForwardTraversalKey as given below.
            Set newForwardKeys = new HashSet();
            newForwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));
            comp.setFocusTraversalKeys(
                        KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,newForwardKeys);
            Set newBackwardKeys = new HashSet();
            newBackwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, KeyEvent.SHIFT_DOWN_MASK));
            comp.setFocusTraversalKeys(
                        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,newBackwardKeys);The only problem that remains now is that I have to press the "TAB" twice in order to get out of the JTextArea column
    regards,
    nirvan.

  • Setting focus to a JTextArea using tab

    Hi,
    I have a JPanel with a lot of controls on it. When I press tab I want to
    move focus to the next focusable component. This works fine for
    JTextFields, but when the next component is a JTextArea in a
    JScrollPane then I have to press tab 3 times to set the focus to the
    JTextArea. After pressing the tab key once I think the focus is set to
    the scrollBars of the JTextArea because when I press the up and down
    arrows the textarea is scrolled.
    How can I stop the JScrollPane from getting the focus?
    I have tried to set focusable to false on the scrollPane:
    scrollPanel.setFocusable(false);
    and the scrollBars of the scrollPane:
    scrollPanel.getHorizontalScrollBar().setFocusable(false);
    scrollPanel.getVerticalScrollBar().setFocusable(false);
    But it dosen�t work. Is this a completely wrong way of doing it?
    Please help!
    I use jdk 1.4.1
    :-)Lisa

    Not sure what your problem is. The default behaviour is for focus to go directly to the JTextArea.
    import java.awt.*;
    import javax.swing.*;
    public class Test1 extends JFrame
         public Test1()
              getContentPane().add( new JTextField("focus is here"), BorderLayout.NORTH );
              getContentPane().add( new JButton("Button1") );
              getContentPane().add( new JScrollPane( new JTextArea(5, 30) ), BorderLayout.SOUTH );
         public static void main(String[] args)
              Test1 frame = new Test1();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }

  • DATAGRID FOCUS ISSUE: Focus got lost, while moving from one cell to another cell using tab key.

    Problem: Focus got lost, while moving from one cell to another cell using tab key.
    Example: In an AdvanceDataGrid, there are three columns having custom ItemRenderer with Spark TextInput control (editable=true & focusEnabled=true).
    When I try to move the focus in with in 2nd, 3rd & 4th column using tab key, focus got lost. Most of the time it’s working, but some time it doesn’t work. There’s no clue as to how may rows/columns the focus has jumped to; or whether the focus has gone out of the data grid altogether.
    Observations: I am not sure whether this problem is because of custom component implementation or it is because of some issue related to Flex Component.
    It only occurs when we perform some actions like some server call, some complex logic execution etc. at the focus out event of itemrenderer.
    There is one property of datagrid i.e. editedItemPosition which contains row & column index of datagrid. On the focus out event, it gets null when focus got lost. We tried to set it, but it didn’t work.
    Steps Performed:-
    1. Currently focus is in 2nd column i.e. Apply to #.
    2. Once I press tab key from 2nd column, it goes to 3rd column which is correct.
    3. Now if I press tab key from 2nd column i.e. Payment #, focus should go to 3rd column, but it goes out of data grid and set the focus of button which is outside data grid.

    http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%2Bjtable+%2Btab+%2B%22enter+key%22&col=javaforums

  • How to use tab key with JTextArea to shift focus

    Hi
    My problem is simple as whenevr i use tab key in my JTextArea, instaed of shifting focus to next component, it adds a tab space to my text.
    How do i shift focus out of my JTextArea.
    Ashish

    you can also redefine the textarea's TAB Key behaviour. The tutorial has a good example for that - better than i would be able to describe :-)
    look at http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html

  • Next component to get focus?

    Hey Guys,
    If i had a panel with buttons and other components and if the focus is on one of the buttons, is it possible to have java return what the next component to get the focus is? I know there's a getNextFocusableComponent, but i'd rather use something that is deprecated so any suggestion is welcomed.
    Here's my code, I basically want the focus to go to button3 when it gets to the last cell in the table. I want the java to figure out the next component because I would rather not hard-code anything into this. Thanks guys!
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TestGui {
    public static void main(String[] args) {
    TestGuiFrame frame = new TestGuiFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.show();
    class TestGuiFrame extends JFrame {
    public TestGuiFrame() {
    setTitle("Pete's Test GUI");
    setSize(200, 200);
    Container contentPane = getContentPane();
    JPanel panel = new JPanel();
    JButton button1 = new JButton("button1");
    JButton button2 = new JButton("button2");
    JButton button3 = new JButton("button3");
    JButton button4 = new JButton("button4");
    JTable table1 = new JTable(2, 3);
    panel.add(button1);
    panel.add(button2);
    panel.add(table1);
    panel.add(button3);
    panel.add(button4);
    contentPane.add(panel);
    InputMap im = table1.getInputMap(JTable.
    WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
    final Action oldTabAction = table1.getActionMap().get(im.get(tab));
    Action tabAction = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
    oldTabAction.actionPerformed(e);
    JTable table = (JTable) e.getSource();
    int rowCount = table.getRowCount();
    int columnCount = table.getColumnCount();
    int row = table.getSelectedRow();
    int column = table.getSelectedColumn();
    if (row == (rowCount-1) && column == (columnCount-1)) {
    //set focus to next component <---- HELP NEEDED HERE =)
    table1.getActionMap().put(im.get(tab),tabAction);
    }

    I haven't tried it but you should be able to do something like:
    KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager()
    FocusTraversalPolicy policy = manager.getDefaultFocusTraversalPolicy()
    Component c = policy.getComponentAfter(....);Otherwise, maybe the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html]How to Use the Focus Subsystem will help.

  • Tab click focus event management

    My form includes a JTable and a few JButtons. The JTable is allowed for only single selection. Once i click on a row in my editable JTable the default functianality is that on click of the TAB KEY, focus shifts from one column to another in the same row and then from row to row.
    I would like to use the TAB KEY to shift the focus from the table into one of the buttons in the form.
    Is there any way to achieve this functionality

    Seems like that article missed a keystroke, Ctrl+TAB which shifts the focus from the table to the next Component.

  • How to set current row in table after use tab key on inputText

    Hello all,
    My first post .., I'm newbie in ADF and I will try to explain my problem.
    For the moment we use ADF 11g (11.1.1.4), in a jsff page I have a table with an inputText column.
    On the valueChangeListener of the inputText, I invoke a method in a viewScope bean which call an EJB method, make some services in the EJB on the line modified. After that I refresh the VO and the table (because others values on the line have been modified) and reset the focus on the same inputText modified by the user with javaScript because focus was lost after refresh.
    So far, everything works fine.
    When I use the arrow keys to change the selected row in the table, it's work fine (focus is still in the next or previous inputText), but if user try to use tab key to change the current line, the inputText on the next line have the focus but the current row of the table is not changed (I think it's normal).
    My question : how can I change the current row after tab key pressed in this case ?
    I don't know if it's really clear, not easy to explain, don't hesitate to ask more details.
    Thanks in advance.

    Frank Nimphius wrote:
    Hi,
    My question : how can I change the current row after tab key pressed in this case ?
    Use a client event to listen for the keyboard entry and intercept the tab. The use af:serverListener to call the server to set the rowKey on the table and issue a PPR for the table to re-paint
    See sample 11 on http://www.oracle.com/technetwork/developer-tools/adf/learnmore/index-101235.html#CodeCornerSamples
    to learn about how to use the client listener and server listener
    FrankHi,
    Thanks a lot for your advices, I used the client and server listener
    I used this code on the method call in order to change the selection after key tab pressed, I don't know if it can be easier, but it works.
              if (LOGGER.isDebugEnabled()) {
              LOGGER.debug("START changeSelectedRow");
              RowKeySet oldRowKeySet = myTable.getSelectedRowKeys(); // get oldRowKeySet
              if (oldRowKeySet == null) {
                   if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("oldRowKeySet is null");
                   return;
              RowKeySetImpl newRowKeySet = new RowKeySetImpl(); // The new RowKeySet use to change the selectedRow
              DCIteratorBinding bindingIterator = ADFUtils.findIterator(MY_ITERATOR);
              bindingIterator.setRangeSize(-1);
              // set the new index of the current row.
              int index = bindingIterator.getCurrentRowIndexInRange();
              if (index < bindingIterator.getAllRowsInRange().length - 1) {
                   index++;
              bindingIterator.setCurrentRowIndexInRange(index);
              // get the current row after changed the index
              Row currentRow = bindingIterator.getCurrentRow();
              if (currentRow != null) {
                   ArrayList nextLst = new ArrayList(1);
                   nextLst.add(currentRow.getKey());
                   newRowKeySet.add(nextLst);
                   // set the new selectedRow
                   myTable.setSelectedRowKeys(newRowKeySet);
                   SelectionEvent selectionEvent = new SelectionEvent(oldRowKeySet, newRowKeySet, myTable);
                   selectionEvent.queue();
                   AdfFacesContext.getCurrentInstance().addPartialTarget(myTable);
              if (LOGGER.isDebugEnabled()) {
                   LOGGER.debug("END changeSelectedRow");
    Best Regards
    Benjamin

  • Tabbed Panel Focus

    I am using tabbed panels to neatly display web part on a
    portal. The only problem I have encountered is tab focus being lost
    when I page through the content. Example: Tab 3 displays, in
    batches of 10, frequently used documents. When navigating to the
    next batch the page is returned with the default tab displayed. Is
    there a way to maintain focus for this example?

    You could pass call a function that would set the tab default
    to what ever so say they click on the next button have an onclick
    to call say the keepTab function or what ever
    so like
    <a href="#" onclick="keeptab(2);">Next</a>
    function keeptab(ID)
    Spry.Widget.TabbedPanels("tp1", { defaultTab: ID });
    haven't tested it but it should work.

  • Link inside tab must open next tab and jump to top of page

    I am trying to open the next tab from  a link within the tabbed panel while ensuring the top of the tab is focused on the screen.
    You can see my tabbed panel at the top of http://yabbox.com/spry.php
    In Panel one, there are links to panel 3 and panel 4.  On some screens you will need to scroll down to see this links and it is this scenario I am working on.
    If you click the link to panel three, the panel will open but as it is smaller, the viewer will be left reading the content below and not the panel itself, which will be very confusing.  This is especially so if you are using a laptop.
    I need to force the link to jump to the to the top of the screen, something like including a named anchor inside the tab itself.
    I am using the following code as found on this forum, but it's not working <a href="javascript:;" onclick="TabbedPanels1.showPanel('3')" scroll(0,0);="">Panel 3</a>
    Can you help?
    Andy

    Hi,
    You need a bookmark for the top of your tabbed panels and then to change the href of you link to reference it
    Try the  following changes
    <div id="TabbedPanels1" class="TabbedPanels" name="TabbedPanels1">
    <p><a href="#TabbedPanels1" onclick="TabbedPanels1.showPanel('3')" scroll(0,0);="">Panel 3</a></p>
    That's how I've solved it on one of my pages
    www.thehmc.co.uk/photo.html
    Regards
    Phil

  • Tabbed Pane Focus Problems

    Focus traversal doesn't appear to be working on tabs added after the JFrame is initially displayed (at least on JDK 1.4.2):
    1) Run the program. Focus is on the last field on the 3rd tab. Use the tab key to cycle through all components. It successfully tabs to the button, the tab, and each text field. This is working ok.
    2) Create a new tab.
    a) Focus should be on the last text field, but no component appears to have focus. (why???)
    b) Type some character. They are added to the last text field. So focus was placed on the last text field, but the caret was not painted (why???)
    c) Use the tab key to cycle through the components. When tabbing through the text fields the caret is not painted to indicate focus, except for the last text field (why???)
    d) Click on a text field and use the tab key to cycle through all compnents. This time the caret will be painted for the last text field and the text field you just clicked on. (why???)
    Any suggestions on how to fix this wierd behaviour? Here's my test code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TabbedPaneFocusTest
         static int columns = 0;
         public static void main(String args[])
              final JTabbedPane tabbedPane = new JTabbedPane();
              newTab(tabbedPane);
              newTab(tabbedPane);
              JComponent component = newTab(tabbedPane);
              JButton button = new JButton("Add Tab");
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        newTab(tabbedPane);
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.getContentPane().add(tabbedPane);
              frame.getContentPane().add(button, BorderLayout.SOUTH);
              frame.setSize(400, 200);
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
              // Select tab 3 and set focus on the last text field.
              tabbedPane.setSelectedIndex(2);
              component.requestFocusInWindow();
         private static JComponent newTab(JTabbedPane tabbedPane)
              columns++;
              JComponent component = null;
              JPanel panel = new JPanel();
              for (int i = 0; i < columns; i++)
                   component = new JTextField("TextField" + columns + i);
                   panel.add( component );
              tabbedPane.add( panel, "" + columns );
              tabbedPane.setSelectedIndex( tabbedPane.getTabCount() - 1 );
              component.requestFocusInWindow();
              return component;
    }

    I tested the last code in Java 1.5.0 (build 1.5.0-b64) on a Linux platform, and it does not seem to work. To determine who has the focus, I added a slithy modified DefaultKeyboardManager that printed out the focus owner, when I run the modified code, it seems that the focus is placed on the last textfield when the panes are created before displaying the frame, this works ok however when I created a pane using the button, the focus is on the button and not on the text field. Apparantly pressing the button does a requestFocusInWindow() on the button after the actionPerformed is executed, overruling the requestFocusInWindow() (just my humble opinion). The modified test code follows below:
    Marc
    package testfocus;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Main
         static int columns = 0;
         public static void main(String args[])
              FocusManager.setCurrentKeyboardFocusManager(new DefaultKeyboardFocusManager()
                             public void processKeyEvent(Component c,KeyEvent e)
                                  System.out.println("Focus owner: "+c);
                                  super.processKeyEvent(c,e);
              final JTabbedPane tabbedPane = new JTabbedPane();
              newTab(tabbedPane);
              newTab(tabbedPane);
              JComponent component = newTab(tabbedPane);
              JButton button = new JButton("Add Tab");
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        newTab(tabbedPane);
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.getContentPane().add(tabbedPane);
              frame.getContentPane().add(button, BorderLayout.SOUTH);
              frame.setSize(400, 200);
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
              // Select tab 3 and set focus on the last text field.
              tabbedPane.setSelectedIndex(2);
              component.requestFocusInWindow();
         private static JComponent newTab(JTabbedPane tabbedPane)
              columns++;
              JPanel panel = new JPanel();
              tabbedPane.add( panel, "" + columns );
              tabbedPane.setSelectedIndex( tabbedPane.getTabCount() - 1 );
              for (int i = 0; i < columns; i++)
                   panel.add( new JTextField("TextField" + columns + i, 5) );
              JTextField component = (JTextField)panel.getComponent(columns - 1);
              component.requestFocusInWindow();
              return component;
    }

  • The latest version of Firefox no longer asks if you want to save open tabes for your next session..I HATE not having that option. What were they thinking?

    Question
    The latest version of Firefox no longer asks if you want to save open tabs for your next session..I HATE not having that option. What were they thinking? (I think this is self explanatory)

    Firefox 4 saves the previous session automatically, so there is no longer need for the dialog asking if you want to save the current session.<br />
    You can use "Firefox > History > Restore Previous Session" to get the previous session at any time.<br />
    There is also a "Restore Previous Session" button on the default <b>about:home</b> Home page.<br />
    <br />
    Another possibility is to use:
    * [http://kb.mozillazine.org/Menu_differences Firefox (Tools) > Options] > General > Startup: "When Firefox Starts": "Show my windows and tabs from last time"

  • When filling out a form, some fields copy to others when I tab to the next. How can I make this stop?

    When filling out a form, some fields copy to others when I tab to the next. How can I make this stop?

    You can't using Adobe Reader. It looks like whomever created the form used the same identifiers (names) for various fields. Each field with the same name will populate with the information used in another field of the same name. This is intentional.
    Normally when I see this, it tells me that someone created an initial field then copy/pasted it to make additional fields but forgot to change the names.

  • How can I change the behavior of the Green Enter button when filling out a field in a form? Current it submits the entire form, I would like it to tab to the next field instead

    When using Firefox for Andriod:
    When filling out a field on a form, they keyboard has a Green Enter button that submits the entire form. However, there are multiple fields on the page, and I would like it to tab to the next field. At the very least not submit the form.
    Also, is there a way to configure the keyboard that shows up for each html5 input type?

    They keyboard that shows up has the large "Green Enter" go button, a backspace and some arrow keys, but no tab button.

  • JOptionPane.showConfirmDialog  "NO" button acting as "YES" on MAC using TAB

    JOptionPane.showConfirmDialog "NO" button acting as "YES" on MAC using TAB

    Ya , I am asking question ? Why "NO" is acting as "YES" button in case of JOptionPane.showConfirmDialog on MAC using TAB.
    i.e,
    I clicked on some button, then showConfirmDialog is opened, By default the focus is on "YES" button. Now I pressed TAB button and changed to the focus to "NO" button.
    If press ENTER key --> acting "YES"
    If press SPACE key -> acting as "NO"
    Why ?
    What should I do to make it correct ?
    Am I need mention set (Key,value) pairs for UIManager in case of MAC.
    Please suggest ?

Maybe you are looking for

  • I'm taking the plunge.

    I graduated high school last week, and for my graduation present, my mother's friend decided to contribute an astounding $2000 toward the purchase of a new Mac. See, I've been on a PC for a long time now, and graphic designing on Windows wasn't entir

  • To display the actual revenue on ERP Service order

    Hi ,     I am working on below scenario 1) i am using a service order type for which the revenue posting is active.I am creating a service order for a customer 2) Booking Planned resources , adding DIP profile to create the resource related billing 3

  • How do I change the background in FaceTime?

    At the Apple store the lady demonstrated some great backgrounds she used for Facetime like the Eiffel Tower, etc. Where do I find these? How do I get it set up? Can you help?

  • Components binding in DataTable

    Hi I have a dataTable with 2 selectOneMenu and a commandButton in 3 columns, the selectOneMenus and the dataTable are binded in a managed bean, the commandButton call an action method that retrieve the selection from the selectOneMenus and put it in

  • EXSLT implementation

    I was wondering if there is any plan to make the oracle XSLT processor supporting the valuable EXSL extensions http://www.exslt.org/