当选择同一行中的另一个单元格时,cellSelectionModel无法获取信息

时间:2018-12-17 16:46:18

标签: java swing jtable

cellSelectionModel出现问题。当选择同一行中的另一个单元格时,它无法获取信息 例如,如果我选择11,它将返回信息,但是如果在此之后我选择12,则不会返回任何信息,那么您是否知道要更正此错误?

示例代码:

public class TableListener {

    public static void main(String[] a) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JTable table;

        String[] columnTitles = { "A", "B", "C", "D" };
        Object[][] rowData = { { "11", "12", "13", "14" }, { "21", "22", "23", "24" },
                { "31", "32", "33", "34" }, { "41", "42", "44", "44" } };

        table = new JTable(rowData, columnTitles);

        table.setCellSelectionEnabled(true);
        ListSelectionModel cellSelectionModel = table.getSelectionModel();
        cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                String selectedData = null;

                int[] selectedRow = table.getSelectedRows();
                int[] selectedColumns = table.getSelectedColumns();

                for (int i = 0; i < selectedRow.length; i++) {
                    for (int j = 0; j < selectedColumns.length; j++) {
                        selectedData = (String) table.getValueAt(selectedRow[i], selectedColumns[j]);
                    }
                }
                System.out.println("Selected: " + selectedData);
            }

        });

        frame.add(new JScrollPane(table));

        frame.setSize(300, 200);
        frame.setVisible(true);
    }

}

1 个答案:

答案 0 :(得分:0)

您需要添加另一个侦听器:

table.getColumnModel().addColumnModelListener(new TableColumnModelListener() {
...

其中

public void columnSelectionChanged(ListSelectionEvent e) 

与您有关。