我现在正在研究JTable
,但是这是我遇到此类问题的两次,我认为我的方法是错误的,
我有一个 JTabbedPane
,其中三个选项卡设置为表格,我运行了测试以查看对所选选项卡的检测是否有效以及是否成功获取行信息和列信息。
我在三个表中添加了一个 MouseListener
,通过获取 getRow()
和 getColumn()
可以可靠地产生良好的结果事件!然而,这并没有产生可靠的结果,因为我现在发现,如果我单击一行,请按住鼠标按钮并拖动到另一行,然后再释放 getRow
和 getColumn
将给出单击的单元格,但突出显示的行将是我发布的行!
public void detectMouseClickRow(JTable aTabbedPane) {
aCol = aTabbedPane.getSelectedColumn();
aRow = aTabbedPane.getSelectedRow();
valueAt = (String)aTabbedPane.getValueAt(aRow, aCol);
}
如何获取突出显示的行的行和列信息?不然当有人点击要删除的职位时,可能会选错职位?
最佳答案
根据我有限的测试,获得选择起点的唯一“看似”可靠的方法是直接使用行和列ListSelectionModel
...
DefaultTableModel model = new DefaultTableModel(10, 10);
JTable table = new JTable(model);
ListSelectionListener listener = new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
int row = table.getSelectionModel().getAnchorSelectionIndex();
int col = table.getColumnModel().getSelectionModel().getAnchorSelectionIndex();
System.out.println(row + "x" + col);
}
};
table.getSelectionModel().addListSelectionListener(listener);
table.getColumnModel().getSelectionModel().addListSelectionListener(listener);
现在,此示例通过 ListSelectionListener
与 ListSelectionModel
交互来演示这个想法,但您也可以轻松地将这个想法合并到您的 MouseListener
并提取选择anchor
索引
关于java - 拖动鼠标时行和列损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44555085/