I have a JTabbedPane, which must switch tabs when Ctrl+Number is pressed (Ctrl+1 for the first tab). Here is my code:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.WindowConstants;
public class NumberSwitchTryout {
public static void main(String[] args) {
JFrame frm = new JFrame("Switch between tabs on Ctrl+Number");
JTabbedPane tabber = new JTabbedPane();
tabber.add("First", new JTextField("First"));
tabber.add("Second", new JTextField("Second"));
tabber.add("Third", new JTextField("Third"));
tabber.add("Fourth", new JTextField("Fourth"));
JPanel enclosingPanel = new JPanel(new BorderLayout());
enclosingPanel.add(tabber);
enclosingPanel.add(new JTextField("Field outside tabber"), BorderLayout.NORTH);
frm.add(enclosingPanel);
for (int i = 0; i < 4; i++) {
ChangeTabAction act = new ChangeTabAction(tabber, i);
KeyStroke stroke = KeyStroke.getKeyStroke("control " + (i + 1));
enclosingPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(stroke, i);
enclosingPanel.getActionMap().put(i, act);
}
frm.setSize(500, 500);
frm.setLocationRelativeTo(null);
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setVisible(true);
}
private static class ChangeTabAction extends AbstractAction {
private JTabbedPane tabber;
private int index;
public ChangeTabAction(JTabbedPane aTabber, int anIndex) {
tabber = aTabber;
index = anIndex;
}
@Override
public void actionPerformed(ActionEvent e) {
tabber.setSelectedIndex(index);
}
}
}
All works fine when a normal number key is pressed. But failed when the key is pressed on number block of keyboard. Some ideas, how to make it working also for the numpad (I need it because most of our customers primarily working with the numpad)?
Background: I have some JTabbedPane with the different number of tabs (but always less than 10). All these JTabbedPane are declared in a class (one JTabbedPane per instance of a class). This class has method addTab(String name, Component tab). And when a tab is added I need to register a key action for switch to this tab in the enclosing panel. So I look now for a generic solution.
