我有一个JTable,我使用整数比较器和TableRowSorter
trs.setComparator(columnIndex, new IntComparator())
和table.setRowSorter(trs)
排序。
排序按预期工作但是我点击鼠标时使用int row = table.rowAtPoint(e.getPoint())
和DefaultTabelModel mod = (DefaultTableModel)table.getModel()
来获取使用mod.getValueAt(row, 0)
选择的行的值。
这将获取JTable原始排序中此位置的行的值,而不是排序后现在的行。如何使这个工作也适用于排序表?
由于
编辑:示例代码
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Comparator;
public class Test extends JFrame{
JTable table = new JTable();
JPanel panel = new JPanel();
public Test() {
add(panel);
pack();
setResizable(false);
setVisible(true);
setSize(1280, 720);
setupTable();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Test();
}
});
}
public void setupTable() {
Object[][] data = new Object[][]{
{1, 15, 17},
{2, 45, 7},
{3, 9, 26},
{4, 65, 65}
};
Object[] columns = new Object[]{"ID", "X", "Y"};
table = new JTable(new DefaultTableModel(data, columns) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
});
table.setPreferredScrollableViewportSize(new Dimension(720, 400));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane);
TableRowSorter<DefaultTableModel> trs = new TableRowSorter(table.getModel());
class IntComparator implements Comparator {
public int compare(Object o1, Object o2) {
Integer int1 = (Integer) o1;
Integer int2 = (Integer) o2;
return int1.compareTo(int2);
}
public boolean equals(Object o2) {
return this.equals(o2);
}
}
for (int i = 0; i < 3; i++) {
trs.setComparator(i, new IntComparator());
}
table.setRowSorter(trs);
table.setAutoCreateRowSorter(false);
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int row = table.rowAtPoint(e.getPoint());
if (0 <= row && row <= table.getRowCount()) {
DefaultTableModel mod = (DefaultTableModel) table.getModel();
String ID = String.valueOf(mod.getValueAt(trs.convertRowIndexToView(row), 0));
System.out.println(ID);
}
}
});
}
}
答案 0 :(得分:1)
查看功能: JTable#convertRowIndexToModel(int) 和 JTable#convertRowIndexToView(int)
您需要将从rowAtPoint
获得的行转换为使用JTable#convertRowIndexToView(int)
答案 1 :(得分:0)
正确使用mod.getValueAt(trs.convertRowIndexToModel(row), 0)
代替mod.getValueAt(trs.convertRowIndexToView(row), 0)
个已选择的排序行。
谢谢searchengine27