Traversing JTextFields

I have a GUI with about 10 JTextFields on it. My user would like to traverse it by pressing enter instead of tab. I know I can add action listeners to each of the text fields to get this behavior, but there has to be a better/easier way. Anyone know what it is?

    mainPanel.setFocusTraversalKeys
     (KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET);
    mainPanel.setFocusTraversalKeys(
     KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET);
    KeyStroke ENTERkey = KeyStroke.getKeyStroke("ENTER");
    KeyStroke F12key = KeyStroke.getKeyStroke(KeyEvent.VK_F12,0);
    InputMap inMap= mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    inMap.put(ENTERkey,"forward");
    inMap.put(F12key,"backward");
    mainPanel.getActionMap().put("forward", new FwFocusAction());
    mainPanel.getActionMap().put("backward", new BsFocusAction());

Similar Messages

  • How can we prevent JTabbedPanes from transferring focus to components outside of the tabs during tab traversal?

    Hi,
    I noticed a strange focus traversal behavior of JTabbedPane.
    During tab traversal (when the user's intention is just to switch between tabs), the focus is transferred to a component outside of the tabs (if there is a component after/below the JTabbedPane component), if using Java 6. For example, if using the SSCCE below...
    import java.awt.BorderLayout;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class TabbedPaneTest extends JPanel {
        public TabbedPaneTest() {
            super(new BorderLayout());
            JTabbedPane tabbedPane = new JTabbedPane();
            tabbedPane.addTab("Tab 1", buildPanelWithChildComponents());
            tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
            tabbedPane.addTab("Tab 2", buildPanelWithChildComponents());
            tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
            tabbedPane.addTab("Tab 3", buildPanelWithChildComponents());
            tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
            tabbedPane.addTab("Tab 4", buildPanelWithChildComponents());
            tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(tabbedPane);
            JButton button = new JButton("Dummy component that gains focus when switching tabs");
            panel.add(button, BorderLayout.SOUTH);
             * To replicate the focus traversal issue, please follow these steps -
             * 1) Run this program in Java 6; and then
             * 2) Click on a child component inside any tab; and then
             * 3) Click on any other tab (or use the mnemonic keys ALT + 1 to ALT 4).
            button.addFocusListener(new FocusAdapter() {
                @Override
                public void focusGained(FocusEvent e) {
                    System.err.println("Gained focus (not supposed to when just switching tabs).");
            add(new JScrollPane(panel));
        private JPanel buildPanelWithChildComponents() {
            JPanel panel = new JPanel();
            BoxLayout boxlayout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
            panel.setLayout(boxlayout);
            panel.add(Box.createVerticalStrut(3));
            for (int i = 0; i < 4; i++) {
                panel.add(new JTextField(10));
                panel.add(Box.createVerticalStrut(3));
            return panel;
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("Test for Java 6");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TabbedPaneTest());
                    frame.pack();
                    frame.setVisible(true);
    ... Then we can replicate this behavior by following these steps:
    1) Run the program in Java 6; and then
    2) Click on a child component in any of the tabs; and then
    3) Click on any other tab (or use the mnemonic keys 'ALT + 1' to 'ALT + 4').
    At step 3 (upon selecting any other tab), the focus would go to the component below the JTabbedPane first (hence the printed message in the console), before actually going to the selected tab.
    This does not occur in Java 7, so I'm assuming it is a bug that is fixed. And I know that Oracle suggests that we should use Java 7 nowadays.
    The problem is: We need to stick to Java 6 for a certain application. So I'm looking for a way to fix this issue for all our JTabbedPane components while using Java 6.
    So, is there a way to prevent JTabbedPanes from passing the focus to components outside of the tabs during tab traversal (e.g. when users are just switching between tabs), in Java 6?
    Note: I've read the release notes between Java 6u45 to Java 7u15, but I was unable to find any changes related to the JTabbedPane component. So any pointers on this would be deeply appreciated.
    Regards,
    James

    Hi Kleopatra,
    Thanks for the reply.
    Please allow me to clarify first: Actually the problem is not that the child components (inside tabs) get focused before the selected tab. The problem is: the component outside of the tabs gets focused before the selected tab. For example, the JButton in the SSCCE posted above gets focused when users switch between tabs, despite the fact that the JButton is not a child component of the JTabbedPane.
    It is important for me to prevent this behavior because it causes a usability issue for forms with 'auto-scrolling' features.
    What I mean by 'auto-scrolling' here is: a feature where the form automatically scrolls down to show the current focused component (if the component is not already visible). This is a usability improvement for long forms with scroll bars (which saves the users' effort of manually scrolling down just to see the focused component).
    To see this feature in action, please run the SSCCE below, and keep pressing the 'Tab' key (the scroll pane will follow the focused component automatically):
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    import javax.swing.JViewport;
    import javax.swing.SwingUtilities;
    public class TabbedPaneAutoScrollTest extends JPanel {
        private AutoScrollFocusHandler autoScrollFocusHandler;
        public TabbedPaneAutoScrollTest() {
            super(new BorderLayout());
            autoScrollFocusHandler = new AutoScrollFocusHandler();
            JTabbedPane tabbedPane = new JTabbedPane();
            tabbedPane.addTab("Tab 1", buildPanelWithChildComponents(20));
            tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
            tabbedPane.addTab("Tab 2", buildPanelWithChildComponents(20));
            tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
            tabbedPane.addTab("Tab 3", buildPanelWithChildComponents(20));
            tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
            tabbedPane.addTab("Tab 4", buildPanelWithChildComponents(20));
            tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(tabbedPane);
            JButton button = new JButton("Dummy component that gains focus when switching tabs");
            panel.add(button, BorderLayout.SOUTH);
             * To replicate the focus traversal issue, please follow these steps -
             * 1) Run this program in Java 6; and then
             * 2) Click on a child component inside any tab; and then
             * 3) Click on any other tab (or use the mnemonic keys ALT + 1 to ALT 4).
            button.addFocusListener(new FocusAdapter() {
                @Override
                public void focusGained(FocusEvent e) {
                    System.err.println("Gained focus (not supposed to when just switching tabs).");
            button.addFocusListener(autoScrollFocusHandler);
            JScrollPane scrollPane = new JScrollPane(panel);
            add(scrollPane);
            autoScrollFocusHandler.setScrollPane(scrollPane);
        private JPanel buildPanelWithChildComponents(int numberOfChildComponents) {
            final JPanel panel = new JPanel(new GridBagLayout());
            final String labelPrefix = "Dummy Field ";
            final Insets labelInsets = new Insets(5, 5, 5, 5);
            final Insets textFieldInsets = new Insets(5, 0, 5, 0);
            final GridBagConstraints gridBagConstraints = new GridBagConstraints();
            JTextField textField;
            for (int i = 0; i < numberOfChildComponents; i++) {
                gridBagConstraints.insets = labelInsets;
                gridBagConstraints.gridx = 1;
                gridBagConstraints.gridy = i;
                panel.add(new JLabel(labelPrefix + (i + 1)), gridBagConstraints);
                gridBagConstraints.insets = textFieldInsets;
                gridBagConstraints.gridx = 2;
                textField = new JTextField(22);
                panel.add(textField, gridBagConstraints);
                textField.addFocusListener(autoScrollFocusHandler);
            return panel;
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("Test for Java 6 with auto-scrolling");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TabbedPaneAutoScrollTest());
                    frame.setSize(400, 300);
                    frame.setVisible(true);
    * Crude but simple example for auto-scrolling to focused components.
    * Note: We don't actually use FocusListeners for this feature,
    *       but this is short enough to demonstrate how it behaves.
    class AutoScrollFocusHandler extends FocusAdapter {
        private JViewport viewport;
        private JComponent view;
        public void setScrollPane(JScrollPane scrollPane) {
            viewport = scrollPane.getViewport();
            view = (JComponent) viewport.getView();
        @Override
        public void focusGained(FocusEvent event) {
            Component component = (Component) event.getSource();
            view.scrollRectToVisible(SwingUtilities.convertRectangle(component.getParent(),
                    component.getBounds(), view));
    Now, while the focus is still within the tab contents, try to switch to any other tab (e.g. by clicking on the tab headers, or by using the mnemonic keys 'ALT + 1' to 'ALT + 4')...
    ... then you'll notice the following usability issue:
    1) JRE 1.6 causes the focus to transfer to the JButton (which is outside of the tabs entirely) first; then
    2) In response to the JButton gaining focus, the 'auto-scrolling' feature scrolls down to the bottom of the form, to show the JButton. At this point, the tab headers are hidden from view since there are many child components; then
    3) JRE 1.6 transfers the focus to the tab contents; then
    4) The 'auto-scrolling' feature scrolls up to the selected tab's contents, but the tab header itself is still hidden from view (as a side effect of the behavior above); then
    5) Users are forced to manually scroll up to see the tab headers whenever they are just switching between tabs.
    In short, the tab headers will be hidden when users switch tabs, due to the Java 6 behavior posted above.
    That is why it is important for me to prevent the behavior in my first post above (so that it won't cause usability issues when we apply the 'auto-scrolling' feature to our forms).
    Best Regards,
    James

  • JTabbedPane - traversing focus through tabs

    I would like to have focus traverse through tabs in a JTabbedPane. That is, when the focus is on the last component of a tab, hitting the key for forward focus traverse should bring up the next tab and focus on the first component on that tab. I'm already using a custom FocusTraversalPolicy on the panel containing the JTabbedPane, which handles focus traversal between the components on the tabs. This policy has no knowledge of which tab a particular component is on.
    I was hoping calling requestFocusInWindow() would automagically focus that tab, but it doesn't. Needless to say, having the focus traversal policy cycle through all the components (including those in non-selected tabs) doesn't work, either. Is there an elegant way to do this, without resorting to listening to key events, watching for the TAB key, and switching to the appropriate tab?

    Ok. here is my suggestion.
    When the focus is going to be transferred to the other tab use tabpane.setSelectedComponent(nextPanel), it will trigger traverse policy once again, but we will catch the fact that current component is JPanel and transfer it further to our field.
    Following code looks ugly:
    order.add(tf1);
    order.add(tf2);
    parentsForward.put(p,tf1);
    parentsBackward.put(p,b2);but this is a concept demonstration only, you can hide this piece inside TraversalPolicy implementation.
    Here is the full code:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class TabbedFocusExample extends JFrame  {
        public TabbedFocusExample()  throws HeadlessException {
            super("Tabbed Focus Test");
            setLayout(new FlowLayout());
            JPanel p;
            final JTabbedPane tp = new JTabbedPane();
            final JTextField tf1 = new JTextField(20);
            final JTextField tf2 = new JTextField(20);
            final JCheckBox cb1 = new JCheckBox("Option 1");
            final JCheckBox cb2 = new JCheckBox("Option 2");
            final JButton b1 = new JButton("Click me!");
            final JButton b2 = new JButton("Press me!");
         //stores real components, no container
         Vector<Component> order = new Vector<Component>();
         //stores (container,first_component_in_this_container) pair
            Map<Component,JComponent> parentsForward = new HashMap<Component,JComponent>();
         //stores (container,last_component_in_previous_container) pair
         Map<Component,JComponent> parentsBackward = new HashMap<Component,JComponent>();
            p = new JPanel(new FlowLayout());
            p.add(tf1);
            p.add(tf2);
            tp.addTab("Tab 1",p);
         order.add(tf1);
            order.add(tf2);
         parentsForward.put(p,tf1);
         parentsBackward.put(p,b2);
            p = new JPanel(new FlowLayout());
            p.add(cb1);
            p.add(cb2);
            tp.addTab("Tab 2", p);
         order.add(cb1);
            order.add(cb2);
         parentsForward.put(p,cb1);
         parentsBackward.put(p,tf2);
            p = new JPanel(new FlowLayout());
            p.add(b1);
            p.add(b2);
            tp.addTab("Tab 3", p);
         order.add(b1);
            order.add(b2);
         parentsForward.put(p,b1);
         parentsBackward.put(p,cb2);
         setFocusTraversalPolicy(new MyOwnFocusTraversalPolicy(order,parentsBackward,
                              parentsForward,tp));
            add(tp);
            pack();
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        public static void main(String[] args) {
            new TabbedFocusExample().setVisible(true);
        public  class MyOwnFocusTraversalPolicy     extends FocusTraversalPolicy   {
         private Vector<Component> order;
         private JTabbedPane tabbedPane;
         private Map<Component, JComponent> parentsForward;
         private Map<Component, JComponent> parentsBackward;
            public MyOwnFocusTraversalPolicy(Vector<Component> order,Map<Component,JComponent> parentsF,
                                       Map<Component,JComponent> parentsB,JTabbedPane jtb) {
                this.order = order;
             this.tabbedPane=jtb;
             this.parentsForward = parentsF;
                this.parentsBackward = parentsB;
            public Component getComponentAfter(Container focusCycleRoot,
                                               Component aComponent) {
              JComponent nextComp = parentsForward.get(aComponent);
              if(nextComp!=null){ //aComponent is Container return first component in this Container
                   return nextComp;
                    int idx = (order.indexOf(aComponent) + 1) % order.size();
              nextComp = (JComponent)order.get(idx);
              int indexCurrent = tabbedPane.indexOfComponent(((JComponent)aComponent).getParent());
              int indexNext = tabbedPane.indexOfComponent(nextComp.getParent());
              if(indexNext!=indexCurrent){ //if next Component sits in next tab go to next tab
                   tabbedPane.setSelectedComponent(nextComp.getParent());
                    return nextComp;
         //same stuff but in opposite direction
            public Component getComponentBefore(Container focusCycleRoot,
                                                Component aComponent)  {
              JComponent prevComp= parentsBackward.get(aComponent);
              if(prevComp!=null){
                   return prevComp;
                    int idx = order.indexOf(aComponent) - 1;
                    if (idx < 0) {
                          idx = order.size() - 1;
                    prevComp = (JComponent)order.get(idx);
              int indexCurrent = tabbedPane.indexOfComponent(((JComponent)aComponent).getParent());
              int indexPrevious = tabbedPane.indexOfComponent(prevComp.getParent());
              if(indexPrevious!=indexCurrent){
                   tabbedPane.setSelectedComponent(prevComp.getParent());
                   return prevComp;
            public Component getDefaultComponent(Container focusCycleRoot) {
                return order.get(0);
            public Component getLastComponent(Container focusCycleRoot) {
                return order.lastElement();
            public Component getFirstComponent(Container focusCycleRoot) {
                return order.get(0);
    }

  • Tab Traversal problem in JTable

    Hi all,
    I am having a requirement in my current project to traverse across the cells of a JTable. Some of the cells were set CustomCelleditor(mainly textfield).
    I have gone through the threads in this forum and tried a code snippet which is now highlighting the text on tab traversal. But there are 2 problems with which I am facing with :-
    1. I need to press tab twice to move to the next cell(one is stopping cell editing and the other is to traverse to the next cell).
    2. When I moved from cell 1 to cell2 using tab and then click on cell1, the text is not getting highlighted.
    Please help me in resolving these issues ?
    The code I tried includes :-
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import javax.swing.text.*;
    public class TableSelectAll extends JFrame{
         JTable table;
         public TableSelectAll() {     
              Object[][] data = { {"1", "A"}, {"2", "B"}, {"3", "C"}, {"4", "D"} };
              String[] columnNames = {"Number","Letter"};
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              table = new JTable(model) {   
              public void changeSelection(int row, int column, boolean toggle,
    boolean extend) {
              super.changeSelection(row, column, toggle, extend);
                   SwingUtilities.invokeLater( new Runnable(){                 
                   public void run() {    
                        table.dispatchEvent(new KeyEvent( table,                               KeyEvent.KEY_PRESSED,
                             0,
                             0,
                             KeyEvent.VK_F2,
                             KeyEvent.CHAR_UNDEFINED) );
                   JScrollPane scrollPane = new JScrollPane( table );
                   getContentPane().add( scrollPane );
                   MyCellEditor dce = new MyCellEditor( new SelectAllEditor() );
                   dce.setClickCountToStart( 1 );
                   table.setDefaultEditor(Object.class, dce );
         class SelectAllEditor extends JTextField implements FocusListener { 
              public SelectAllEditor() {           
              setBorder( new LineBorder(Color.black) );
              addFocusListener( this );
    public void setText(String text) {
         super.setText(text);
         System.out.println("text");
         selectAll();
    public void focusGained(FocusEvent e) { 
         System.out.println("gained");
         if (getSelectionStart() == getSelectionEnd())
         selectAll();
         public void focusLost(FocusEvent e) {}
    class MyCellEditor extends DefaultCellEditor {
    public MyCellEditor(JTextField t) {
    super(t);
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int
    row, int column) {
    final Component c = super.getTableCellEditorComponent(table, value, isSelected, row, column);
    if (c != null && c instanceof JTextField) {
    try {
    c.requestFocus();
    } catch (Exception e) {
    //handleException(e);
    return c;
    public static void main(String[] args) {   
         TableSelectAll frame = new TableSelectAll();
         frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
    frame.pack(); frame.setVisible(true);
    Regards
    Nagalakshmi

    Additional info:[http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=2&t=017300]

  • Related JtextField Event Handling

    Hi,
    In the JtextField whener I pressed the ALT + TAB the focus lost of the
    JtexrField is called.After that again pressed the Tab in the same Jtextfield the KeyListener is not fired.Is there any possibility to fire the
    Event whener we pressed the Tab second time.
    Regards,
    Naresh.

    So, you press ALT+TAB in a JTextField and it loses focus.
    Do you give focus back to the JTextField before you press Tab again? That
    could be one problem. The second is that Tab is a focus traversal key, and
    so the focus manager is going to process that key before the component
    sees it. You could remove Tab as a focus traversal key, and that would allow
    the component to receive it, but I'm not sure you want to do that.

  • Problematic focus traversal (JTextArea)

    I have a data entry dialog with several JTextFields and one JTextArea.
    Focus traversal (with the tab key) works nicely between instances of JTextField, but it is not possible to tab out of the JTextArea to the next JTextField (as a tab is inserted in the text area instead). I've have looked up swing focus traversal in books, but no cigar when it comes to dealing with JTextAreas
    Does anyone know how to fix this? I don't need to enter tabs into the text area.
    thanks,
    Andy

    There is a Swing forum for Swing related questions.
    Have you tried searching the forum?. Using keywords "+jtextarea +tab" would be a good place to start. You'll be amazed how many times this question has been asked/answered before.
         This example shows two different approaches for tabbing out of a JTextArea
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TextAreaTab extends JFrame
         public TextAreaTab()
              // Reset the FocusManager
              JTextArea textArea1 = new JTextArea(5, 30);
              textArea1.setText("1\n2\n3\n4\n5\n6\n7\n8\n9");
              JScrollPane scrollPane1 = new JScrollPane( textArea1 );
              getContentPane().add(scrollPane1, BorderLayout.NORTH);
              textArea1.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
              textArea1.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);
              scrollPane1.getVerticalScrollBar().setFocusable(false);
              scrollPane1.getHorizontalScrollBar().setFocusable(false);
              //  Replace the Tab Actions
              JTextArea textArea2 = new JTextArea(5, 30);
              textArea2.setText("1\n2\n3\n4\n5\n6\n7\n8\n9");
              getContentPane().add(new JScrollPane(textArea2), BorderLayout.SOUTH);
              InputMap im = textArea2.getInputMap();
              KeyStroke tab = KeyStroke.getKeyStroke("TAB");
              textArea2.getActionMap().put(im.get(tab), new TabAction(true));
              KeyStroke shiftTab = KeyStroke.getKeyStroke("shift TAB");
              im.put(shiftTab, shiftTab);
              textArea2.getActionMap().put(im.get(shiftTab), new TabAction(false));
         class TabAction extends AbstractAction
              private boolean forward;
              public TabAction(boolean forward)
                   this.forward = forward;
              public void actionPerformed(ActionEvent e)
                   if (forward)
                        tabForward();
                   else
                        tabBackward();
              private void tabForward()
                   final KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
                   manager.focusNextComponent();
                   SwingUtilities.invokeLater(new Runnable()
                        public void run()
                             if (manager.getFocusOwner() instanceof JScrollBar)
                                  manager.focusNextComponent();
              private void tabBackward()
                   final KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
                   manager.focusPreviousComponent();
                   SwingUtilities.invokeLater(new Runnable()
                        public void run()
                             if (manager.getFocusOwner() instanceof JScrollBar)
                                  manager.focusPreviousComponent();
         public static void main(String[] args)
              TextAreaTab frame = new TextAreaTab();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);

  • Changing the application wide default focus traversal policy

    Hi,
    I have a Swing application built using JDK1.3 where there lots of screens (frames, dialogs with complex screens - panels, tables, tabbed panes etc), in some screens layouts have been used and in other screens instead of any layout, absolute positions and sizes of the controls have been specified.
    In some screens setNextFocusableComponent() methods for some components have been called at some other places default focus traversal is used. (which I think is the order in which the components are placed and their postions etc). Focus traversal in each screen works fine.
    Now I have to migrate to JDK1.4. Problem now is that after migrating to JDK1.4.2, focus traversal has become a headache. In some screens there is no focus traversal and in some there is it is not what I wanted.
    So I thought to replace applicaiton wide default focus traversal policy and I did the following:
    ///////// Replace default focus traversal policy
    java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalPolicy(new java.awt.ContainerOrderFocusTraversalPolicy());
    But there is no change in the behaviour.
    Then I tried following:
    ///////// Replace default focus traversal policy
    java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalPolicy(new java.awt.DefaultFocusTraversalPolicy());
    I did all this in the main() method of the application before anything else just to ensure that all the components get added after this policy has been set. But no luck.
    Does someone has any idea what is the problem here ? I do not want to define my own focus traversal policy for each screen that I use (because thats lot of codes).
    Thanks

    not that hard if you only have the one focus cycle ( > 1 cycle and it gets a bit harder, sometimes stranger)
    import javax.swing.*;
    import java.awt.*;
    class Testing
      int focusNumber = 0;
      public void buildGUI()
        JTextField[] tf = new JTextField[10];
        JPanel p = new JPanel(new GridLayout(5,2));
        for(int x = 0, y = tf.length; x < y; x++)
          tf[x] = new JTextField(5);
          p.add(tf[x]);
        final JTextField[] focusList = new JTextField[]{tf[1],tf[0],tf[3],tf[2],tf[5],tf[4],tf[7],tf[6],tf[9],tf[8]};
        JFrame f = new JFrame();
        f.setFocusTraversalPolicy(new FocusTraversalPolicy(){
          public Component getComponentAfter(Container focusCycleRoot,Component aComponent)
            focusNumber = (focusNumber+1) % focusList.length;
            return focusList[focusNumber];
          public Component getComponentBefore(Container focusCycleRoot,Component aComponent)
            focusNumber = (focusList.length+focusNumber-1) % focusList.length;
            return focusList[focusNumber];
          public Component getDefaultComponent(Container focusCycleRoot){return focusList[0];}
          public Component getLastComponent(Container focusCycleRoot){return focusList[focusList.length-1];}
          public Component getFirstComponent(Container focusCycleRoot){return focusList[0];}
        f.getContentPane().add(p);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • Component that is focusable, but not focus- traversable

    Hi,
    I have found a tidy solution to this, and posted it in the thread I thought was most appropriate, THEN I found, it was in the REFLECTION forum - duh.
    I won't cross post the whole solution here.
    So if you're interested, bowl over there for the answer
    http://forum.java.sun.com/thread.jspa?messageID=3541807&#3541807
    Cheers
    Bruce

    Answer,
    I have a status field on my dialog that shouldn't be keyboard traversible, but I would like the user to be able to cut the contents (such as an error display), so I need to be able to have it focusable by mouse click.
    I did this by enclosing the component inside a focusCycleRoot container that isn't itself focusable !!
    original code, status widget gets focus when traversing via keyboard.
            JTextField status = new JTextField();
            status.setColumns(40);
            status.setEditable(false);
            status.setFocusable(true); // So user can cut the text with mouse
            status.setBorder(new javax.swing.border.EmptyBorder(status.getInsets()));
            container.add(status, "layout stuff");This is the modified code, which stops status being traversible by keyboard.
            JTextField status = new JTextField();
            status.setColumns(40);
            status.setEditable(false);
            status.setFocusable(true); // So user can cut the text with mouse
            status.setBorder(new javax.swing.border.EmptyBorder(status.getInsets()));
            Container statusTraversalHider = new JPanel();
            statusTraversalHider.add(status);
            statusTraversalHider.setFocusCycleRoot(true);
            statusTraversalHider.setFocusable(false);
            container.add(statusTraversalHider, "layout stuff");

  • HELP please in ** Traversing through folders **

    Hi,
    I have a small java program which when given a particular folder will generate an "index.html" file with "ahref" to all the files and folders in the selected folder.
    I have pasted the code below. It uses a small text field and buttons and JFileChooser to allow the user to choose the folder.
    I would LIKE TO be able to select the folder and make the code traverse into every subfolder from the seleted folder and generate a "index.html" file in each folder. I would be very grateful for any assistance to help me traverse in folders from.
    Many thanks,
    Asif
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    public class IndexGenerator {
    private JFrame generatorFrame;
    private JPanel generatorPanel;
    private JTextField dirField;
    private JButton fcButton;
    private JButton createButton;
    private JFileChooser fc;
    public IndexGenerator() {
    // Create and set up the window
    generatorFrame = new JFrame("Index.HTML Generator");
    generatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Create and set up the panel
    generatorPanel = new JPanel(new FlowLayout());
    // Add the widgets
    addWigets();
    // Set the default button
    generatorFrame.getRootPane().setDefaultButton(fcButton);
    // Add the panel to the window
    generatorFrame.getContentPane().add(generatorPanel);
    // Display the window
    generatorFrame.pack();
    generatorFrame.setVisible(true);
    * Create and add the widgets.
    public void addWigets() {
    // Create widegets
    dirField = new JTextField("Enter full path here");
    fcButton = new JButton("Choose folder");
    createButton = new JButton("Generate HTML");
    fc = new JFileChooser();
    //fc.setCurrentDirectory(new java.io.File("."));
    //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    // Open the File Chooser dialog
    fcButton.addActionListener(
    new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (fc.showOpenDialog(generatorFrame) == JFileChooser.APPROVE_OPTION) {
    dirField.setText(fc.getCurrentDirectory().toString());
    } else {
    System.out.println("No Selection ");
    // Listen to events from the Create button
    createButton.addActionListener(
    new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
    // On clicking the createHTML button
    createHTML();
    // Add the widgets to the container
    generatorPanel.add(dirField);
    generatorPanel.add(fcButton);
    generatorPanel.add(createButton);
    * Create the GUI and show it. For thread safety,
    * this method should be invoked frmo the
    * event-dispatching thread
    private static void createAndShowGUI() {
    // Nice window decorations
    JFrame.setDefaultLookAndFeelDecorated(true);
    IndexGenerator ig = new IndexGenerator();
    public void createHTML() {
    File folder = new File(dirField.getText());
    File[] listOfFiles = folder.listFiles();
    for(int x=0; x < listOfFiles.length; x++) {
    try {
    BufferedWriter out = new BufferedWriter(new FileWriter(dirField.getText() + "\\" + "index.html"));
    out.write("<HTML> \n" +
    "<HEAD><TITLE>Change Requests</TITLE> \n" +
    "<STYLE> \n" +
    "li,ul {font-family: Verdana, Tahoma, Arial, Helvetica, sans-serif; font-size: 10pt; font-style: strong; color: #000000} \n" +
    "h2 {font-family: Verdana, Tahoma, Arial, Helvetica, sans-serif; font-size: 14pt; color: #808080} \n" +
    "h4 {font-family: Verdana, Tahoma, Arial, Helvetica, sans-serif; font-size: 8pt; color: #000000} \n" +
    "A:link {text-decoration: none ; color: #0000FF; font-size: 8pt;} \n" +
    "A:visited {text-decoration: none ; color: #740163; font-size: 8pt;} \n" +
    "</STYLE> \n" +
    "<BODY> \n" +
    "<H2>Change Requests</H2> \n" +
    "<UL> \n");
    for (int i = 0; i < listOfFiles.length; i++) {
    if (listOfFiles.isFile()) {
    out.write("<LI><A HREF=\"" + listOfFiles[i].getName() +"\" \"target=\"_blank\">" + listOfFiles[i].getName() + "</A></LI> \n");
    } else if (listOfFiles[i].isDirectory()) {
    out.write("<LI><A HREF=\"" + listOfFiles[i.getName() +"\">" + listOfFiles.getName() + "/</A></LI> \n");
    out.write("</UL> \n" +
    "</BODY></HTML> \n");
    out.close();
    } catch (IOException e) { }
    public static void main(String[] args) {
    * Schedule a job for the event-dispatching thread:
    * creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();

    You can make createHTML accept a folder name parameter and know nothing about dirField.getText(). This way you can call the method recursively when you find a directory. The first time you will call it with dirField.getText() of course, and then it will traverse subfolders by calling itself with the found folder name.
    HTH
    Mike

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

  • Displaying the results of an iterator in JTextfields.

    Hi people,
    I have got two methods which basically iterate through statements (forward and back).
    However I have a separate class which is basically the GUI for my program. I want the user to be able to click the next button and it iterates through the list and displays the element in the list in the JTextField.
    The problem I am having is that it will not display the element in the predefined fields, does anyone know how I can go about this? My code for my two methods is below:
    public void MusicNext()
               try
               if(titerator==null)
                   titerator = iList.listIterator();
               if(titerator.hasNext())
                   System.out.println(titerator.next());//Just prints out the iterator atm.
               else
                  titerator = null;
                  MusicNext();
               catch(ConcurrentModificationException ex)
                  titerator = iList.listIterator();
                  System.out.println("Iterator has been reset.");
              public Music MusicNext(String pTitle)
                Music tTitle = null;
             boolean found = false;
                Iterator it = iList.iterator();
                if(it.hasNext() && !found)
              tTitle = (Music) it.next();
              found = tTitle.getTitle().equalsIgnoreCase(pTitle);
                return tTitle;
            public void MusicPrevious()
               try
               if(titerator==null)
                   titerator = iList.listIterator();
               if(titerator.hasPrevious())
                   System.out.println(titerator.previous());//Just prints out the iterator atm.
               else
                  titerator = null;
               catch(ConcurrentModificationException ex)
                  titerator = iList.listIterator();
                  System.out.println("Iterator has been reset.");
               catch(NoSuchElementException ex)
                  //titerator = iList.listIterator();
                  System.out.println("No such element.");
         }I am pretty sure they shouldn't be void but should return an element, but I am really not sure what to return.
    Many Thanks,
    Rob.
    (Sorry I posted this before but I left out alot of detail).

    Don't get or instantiate the iterator in often-called methods.
    It should be get or instantiated as a class global field once and for all.
    Your ListIterator is good for such treatment becuase it can be
    freely scanned backward, while Iterator can't.

  • Initial JTextField value

    Hello!
    I'm puzzled with API docs:
    public JTextField()
    Constructs a new TextField. A default model is created, the initial string is null, and the number of columns is set to 0.
    But when I read the textfield with textfield.getText I do not get a null Object but an empty String object, i.e(""). Why?

    Hmm, very curious.Yes it is, so I looked into it.
    Perhaps the no-arugument constructor creates a default
    Document with an empty string?You are correct sir. In a round about way a character array is created which consists of a single character, that being the null terminator. If your still curious, its done in the GapContent constructor.

  • Can't Copy text unless console is opened before applet with JTextField

    If an applet uses JTextFields, it is impossible to copy text from the console to the clipboard (or anywhere else) if the console is opened after the applet.
    See http://demo.capmon.dk/~pvm/nocopy/nocopy.html for a working applet with source and class file to try it out on...
    So if something bad has happened, and there are hints in the console e.g. a stack trace, it all has to be retyped by hand, since all Copy or export is impossible...
    Does anyone know of a workaround for this? I'd like to be able to e.g. copy stack traces to bug reports.
    Try these test cases:
    * Close all browser windows. Open a browser and visit this page. After the page with this applet has loaded, then open the console with "Tools/Sun Java Console" (or "Tools/Web Development/Java Console" in Mozilla). Select some text in the console. There is no way to put this text on the clipboard; the "Copy" button doesn't work, and neither does CTRL+Insert, CTRL+C or anything else.
    * Close all browser windows. Open a browser window no some non-java page and then open the console with "Tools/Sun Java Console" (or "Tools/Web Development/Java Console" in Mozilla). Then visit this page. Select some text in the console. Now the "Copy" button does work, enabling "export" of e.g. stack traces to other applicaitons e.g. email.
    The difference is which is opened first: The console or the applet. If you look at the very rudimentary Java source code, it is the mere creation of a JTextField is what disables or breaks the Copy functionality.
    I've tried this on Windows XP with IE 6.0 and Mozilla 1.3 and they behave exactly the same. The JVM is Sun's 1.4.2 and I've tried 1.4.1_02 also with the same behavior. I've also tried javac from both 1.4.2 and 1.4.1_01

    hey .. this seems like a bug.. can you please file a bug at
    http://java.sun.com/webapps/bugreport
    thanks...

  • 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

  • Leaving JTextField with TAB

    A simple question really ... I have a JTextField that I would like to have the user exit from with TAB and get
    the same action as if they had left the field with the
    ENTER key, i.e., I'd like to be able to use the getText
    method to retrieve what the user entered. Currently, with
    no modifcations whatsoever to the JTextField, when I
    invoke getText after the user leaves the field with a TAB,
    getText returns NULL. I've tried just about everything,
    but can't get any of it to work (removeKeyStrokeBinding(), extending JTextField, etc.).
    Thanks in advance for any suggestions.

    As you have niticed this is not such a simple question at all.
    After some experimentation I decided to make the enter key cause the text field to loose focus.
    addKeyListener (new KeyAdapter()
    public void keyPressed (KeyEvent evt)
    int key = evt.getKeyCode();
    if (key == KeyEvent.VK_ENTER)
    transferFocus ();
    Then give the text field a focus listener
    class TextListener extends java.awt.event.FocusAdapter
    public void focusLost (FocusEvent e)
    // evalutate the text using getText()
    Which gets the field's content, validates it and then save it in the appropriate place.
    The advantage to this approach is the whole field edits are always done in the same place (the focus adapter), and the enter and tab actions appear the same to the user.
    The disadvantage is that, unless you know the initial value, you won't be able to tell if the value has changed.
    hope this helpds some.
    Terry

Maybe you are looking for

  • Address Book will not print

    I am new to MAC. I have spent the last month entering 1037 contacts into my address book. Now I cannot print it. The software itself does not respond. I have had to force quit it everytime. I tried to do smaller segments, but I actually cannot even p

  • System.out and System.err

    Hi all, This is a stupid newbie question, but I could not find the answer on the Web site, so here goes: Where do System.out and System.err get written to? I'm trying to deploy some plain-vanilla stateless session beans that do a bunch of println() c

  • SBO 2007 PL41 - problem?

    With new PL41 I have problem with vendor order. When the order has more lines (I mean more than 10), then creation of order takes too long and sometimes it blocks the table OITM and all users cannot work. Before PL41 creation of order took about 15 s

  • I can't recieve email

    All of a sudden I can't receive email I can send  and have tried turning off and on wifi working at a loss now what do I try next?

  • Production scheduler & profile configuration

    Dear SAPper, When i create production order, the production scheduler is automatically flled (ex.101) and then the production scheduler profiles is automaticalled filled too. I don;t maintain production scheduler & production scheduler profile in wor