Tab over JTable component

I have a panel containing several components, one of which is JTable. When the button JTablehas focus and the TAB key is pressed, by default, focus moves from cell to cell within the table. I need to change this to focus on the next component, and not completely JTable.

Ctrl-TAB achieves the desired results, but is unacceptable to the user. I can add a key listener to the table and change focus when I press TAB, but it seems that there may be a better way to do this.

Any ideas?

Thanks...

+3
source share
2 answers

, , , Tab, . , , Tab . , , , , , .

" ", , Tab Tabing. KeyboardFocusManager .

+1

, Action , ( ). , , , :

tp.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.<AWTKeyStroke>emptySet());

:

public static void main(String[] args) {
    final JTabbedPane tp = new JTabbedPane();

    // Remove Tab as the focus traversal key - Could always add another key stroke here instead.
    tp.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.<AWTKeyStroke>emptySet());

    KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);

    Action nextTab = new AbstractAction("NextTab") {
        public void actionPerformed(ActionEvent evt) {
            int i = tp.getSelectedIndex();
            tp.setSelectedIndex(i == tp.getTabCount() - 1 ? 0 : i + 1);
        }
    };

    // Register action.
    tp.getActionMap().put("NextTab", nextTab);
    tp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ks, "NextTab");

    tp.addTab("Foo", new JPanel());
    tp.addTab("Bar", new JPanel());
    tp.addTab("Baz", new JPanel());
    tp.addTab("Qux", new JPanel());

    JFrame frm = new JFrame();

    frm.setLayout(new BorderLayout());
    frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frm.add(new JButton(nextTab), BorderLayout.NORTH);
    frm.add(tp, BorderLayout.CENTER);
    frm.setBounds(50,50,400,300);
    frm.setVisible(true);
}
+4

Source: https://habr.com/ru/post/1712209/


All Articles