将焦点从JTable转移到其他组件

时间:2014-05-20 22:55:25

标签: java swing jtable focus

我如何设置标签遍历以便线性地遍历框架的所有组件,包括JTable中的单元格?例如:

A container with a table between two text fields

如果我按下TAB,它将从“Focus Start”开始 - > 1 - > 2 - > ... - > 6 - > “焦点结束”,如果我按下SHIFT + TAB,它会按相同的顺序进行反转但是会反转吗?

目前,当焦点点击JTable时,它会将焦点在1和6之间循环,直到按下CTRL + TAB。

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.SwingConstants;

public class TableExample extends JFrame {

private JPanel contentPane;
private JTextField txtFocusStart;
private JTable table;
private JTextField txtFocusMe;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                TableExample frame = new TableExample();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public TableExample() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 130);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);

    txtFocusStart = new JTextField();
    txtFocusStart.setText("Focus Start");
    txtFocusStart.setHorizontalAlignment(SwingConstants.CENTER);
    contentPane.add(txtFocusStart, BorderLayout.NORTH);
    txtFocusStart.setColumns(10);

    table = new JTable();
    table.setModel(new DefaultTableModel(
        new Object[][] {
            {"1", "2", "3"},
            {"4", "5", "6"},
        },
        new String[] {
            "New column", "New column", "New column"
        }
    ));
    contentPane.add(table, BorderLayout.CENTER);

    txtFocusMe = new JTextField();
    txtFocusMe.setHorizontalAlignment(SwingConstants.CENTER);
    txtFocusMe.setText("Focus End");
    contentPane.add(txtFocusMe, BorderLayout.SOUTH);
    txtFocusMe.setColumns(10);
}

}

1 个答案:

答案 0 :(得分:3)

我想尝试重用现有的Actions以提供其他功能。

查看Table Tabbing,其中给出了一个示例,说明如何重用现有的Tab Action,使Tab键仅关注可编辑的单元格。

在您的情况下,您需要创建一个自定义类来执行Tab键。你的代码会简单得多。前向标签的代码类似于:

if (last cell)
    KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
else
    invokeOriginalAction( e );

您还需要为后向标签创建单独的操作。