JTable选择的单元数多于单击的单元数

时间:2014-02-25 17:32:55

标签: java swing jtable selection cell

我正在编写一个使用JTable的应用程序,我希望能够选择单个单元格,以便我可以与所选单元格进行交互。问题是,当我选择一定数量的单元格时,JTable认为我点击了比实际更多的单元格。例如,我单击3个单元格,JTable会自动选择第4个单元格。

这是我的问题的图像。我按照图像中编号的顺序选择3个单元格,选择第3个单元格后选择第4个单元格。 enter image description here

我该如何解决这个问题?

可运行的例子。我的表格应用程序看起来与此相同(显然没有菜单或额外的废话,但这是它的设置方式)。

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

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;

public class TestTable extends JFrame {

    private JPanel contentPane;
    private DefaultTableModel dbModel;
    private JTable table;
    private JScrollPane scrollPane;

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

    public TestTable() {
        super("Test Table");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 800, 500);

        String[] columnNames = {"Name","Sport","Years Played"};
        Object[][] data = {{"Tim","Baseball","4"},
                {"Josh","Hockey","6"},
                {"Jessica","Volleyball","3"}};

        dbModel = new DefaultTableModel(data, columnNames);
        table = new JTable(dbModel);
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        table.getColumnModel().setColumnSelectionAllowed(true);
        table.setCellSelectionEnabled(true);
        scrollPane = new JScrollPane(table);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        contentPane.add(scrollPane, BorderLayout.CENTER);
        setContentPane(contentPane);
    }
}

1 个答案:

答案 0 :(得分:4)

要启用单个单元格选择,请使用setCellSelectionEnabled(true),“将行和列选择模型的交集视为所选单元格”。另请参阅此相关answer