单击 rows/columns 时,ListSelectionEvent 会异步触发 2 个触发器

ListSelectionEvent fire 2 triggers asynchronously when clicking rows/columns

ListSelectionEvent 在单击时异步触发 2 个触发器 rows/columns

我应该更改我的代码吗?

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class JTableListSelectionListener {

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);
}

}

输出将是

已选择:42

已选择:42

已选择:33

已选择:33

但是我想在用户单击特定行或列时触发单个事件?

使用 ListSelectionEvent.getValueIsAdjusting() 检查它是否(正在更改)。

Returns whether or not this is one in a series of multiple events, where changes are still being made. See the documentation for ListSelectionModel.setValueIsAdjusting(boolean) for more details on how this is used.

按照 Andrew Thompson 的建议添加了 getValueIsAdjusting() 并且更新后的代码将是

cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
  public void valueChanged(ListSelectionEvent e) {

    if(e.getValueIsAdjusting()) {
        return;
    }
    ..