Delphi Clinic C++Builder Gate Training & Consultancy Delphi Notes Weblog Dr.Bob's Webshop
Hubert Klein Ikkink (aka Mr.Haki) - Communications Officer
 Mr.Haki's JBuilder Jar #56
See Also: JBuilder Papers

Tab your way!
When designing a user interface we must often set a tab order for the different UI elements. So when a user presses the TAB key the next logical component has got the focus.
Normally the order in which the components are placed on a form determine the tab order of the components. The following piece of code makes sure the textfield first, second and third have a subsequent tab order.

  JTextField first  = new JTextField();
  JTextField second = new JTextField();
  JTextField third  = new JTextField();
  Panel panel = new Panel();
  panel.setLayout(new GridBagLayout());
  GridBagConstraints gbc = new GridBagConstraints();
  gbc.weightx = 1.0;
  gbc.fill = GridBagConstraints.HORIZONTAL;
  gbc.gridx = 0;
  panel.add(first,  gbc);
  gbc.gridx = 1;
  panel.add(second, gbc);
  gbc.gridx = 2;
  panel.add(third,  gbc);

Internet Explorer users may not experience the focus flow of control, because IE doesn't let the focus traverse.

And if we want to change the order we simple change the order in which we add the components to the panel. In our example we could change the tab order as follows first, third and second.

  panel.add(first,  gbc);
  panel.add(third,  gbc);
  panel.add(second, gbc);

Or another way to set the tab order is using the method setNextFocusableComponent(). This method is added to JComponent in the Swing classes and takes as an argument the next component which will get the focus. The next argument doesn't have to be a Swing component, any descendent of java.awt.Component will do.

  first.setNextFocusableComponent(third);
  second.setNextFocusableComponent(first);
  third.setNextFocusableComponent(second);
I didn't include an applet to show this, because it would mean I would have to include the Swing classes and the applet download time would be increased. But you get the idea...


This webpage © 1997-2009 by Bob Swart (aka Dr.Bob - www.drbob42.com). All Rights Reserved.