To organize the focus order of the components up to version 1.4 of java, we used the setNextFocusableComponent()
". However, it was discontinued as of the cited version.
I would like to know how I can do this in the latest versions so that I can control the focus order of components on the screen with the TAB key. For example, the code below has 4 distinct components, and they get focus on the order they 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();
}
}
Switching focus with TAB :
How do I manually set the focus order of the components, for example by following the order below?
- first text field
- second text field
- combobox
- button