6
To organize the component focus selection order up to version 1.4 of java, we used the method setNextFocusableComponent()
. However, it was discontinued from the aforementioned version.
I would like to know how to do in the latest versions to control the focus order of components on the screen through the key TAB. For example, the code below has 4 distinct components, and they get focus on the order that were added on the screen:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class NextFocusTest extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JPanel panel;
private JTextField firstComp;
private JComboBox<String> thirdComp;
private JTextField secondComp;
private JButton fourthComp;
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
NextFocusTest frame = new NextFocusTest();
frame.setVisible(true);
});
}
public NextFocusTest() {
initComponents();
}
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(350, 200));
this.contentPane = new JPanel();
this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
this.contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(this.contentPane);
this.panel = new JPanel();
this.panel.setBorder(new EmptyBorder(0, 20, 0, 20));
this.panel.setLayout(new GridLayout(2, 2, 20, 5));
this.contentPane.add(this.panel, BorderLayout.NORTH);
this.firstComp = new JTextField();
this.firstComp.setPreferredSize(new Dimension(100, 20));
this.panel.add(this.firstComp);
this.thirdComp = new JComboBox<String>();
this.thirdComp.setModel(new DefaultComboBoxModel<String>(new String[] { "teste 1", "teste 2", "teste 3" }));
this.thirdComp.setPreferredSize(new Dimension(100, 20));
this.panel.add(this.thirdComp);
this.secondComp = new JTextField();
this.secondComp.setPreferredSize(new Dimension(100, 20));
this.panel.add(this.secondComp);
this.fourthComp = new JButton("OK");
this.fourthComp.setPreferredSize(new Dimension(90, 23));
this.panel.add(this.fourthComp);
pack();
}
}
Alternating the focus with TAB:
How do I manually set the component focus order, for example by following the order below?
- first text field
- second text field
- combobox
- button
Have you tried the method
setNextFocusableComponent
. Take an example:firstComp.setNextFocusableComponent(secondComp);
– viana
@acklay right at the beginning of the question I quote him, is discontinued.
– user28595
haha... just read the title. xD mals
– viana