【问题标题】:ListSelectionEvent fire 2 triggers asynchronously when clicking rows/columns单击行/列时,ListSelectionEvent 触发 2 异步触发
【发布时间】:2016-10-24 09:57:09
【问题描述】:

ListSelectionEvent 在点击行/列时触发 2 个异步触发

我应该用我的代码改变什么吗??

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

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

【问题讨论】:

    标签: java swing event-handling jtable listselectionlistener


    【解决方案1】:

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

    返回这是否是一系列多个事件中的一个,仍在进行更改。有关如何使用它的更多详细信息,请参阅ListSelectionModel.setValueIsAdjusting(boolean) 的文档。

    【讨论】:

      【解决方案2】:

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

      cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
      
          if(e.getValueIsAdjusting()) {
              return;
          }
          ..
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-07
        • 1970-01-01
        • 2014-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多