我想根据一个隐藏列对JTable
行进行排序。
说我有像这样的JTable
column1 column2
val1 val2
现在我还有一个隐藏的栏目3,我不想表现出来。当用户单击Column2时,它应该基于Column3(隐藏列)而不是基于Column2对行进行排序。
如何在JTable中实现这一目标?
答案 0 :(得分:3)
使用此处发布的代码:http://www.esus.com/docs/GetQuestionPage.jsp?uid=1270
有变量/方法参数col
- 只需检查它是否属于你的column2,如果是这样就把它视为你的隐藏列 - 按它排序并重新呈现表。
答案 1 :(得分:2)
您可以默认TableRowSorter添加到JTable,但有RowSorter,没有什么比Darryl的Multisort Table Header Cell Renderer
更好更清楚了注意RowSorter的定义仅对具体的TableColumn
有效siple示例(再次使用无用的balast)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class HeaderDoubleclickTest {
private String[] columnNames = {"String", "Integer", "Boolean"};
private Object[][] data = {
{"aaa", 12, true}, {"bbb", 5, false},
{"CCC", 92, true}, {"DDD", 0, false}
};
private TableModel model = new DefaultTableModel(data, columnNames) {
private static final long serialVersionUID = 1L;
@Override
public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
private JTable table = new JTable(model);
private JTableHeader header;
static class TestTableRowSorter extends TableRowSorter<TableModel> {
TestTableRowSorter(TableModel m) {
super(m);
}
@Override
public void toggleSortOrder(int column) {
}
public void wrapToggleSortOrder(int column) {
super.toggleSortOrder(column);
}
}
private Timer timer = new Timer(400, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("single");
JTable table = header.getTable();
RowSorter sorter;
if (pt != null && table != null && (sorter = table.getRowSorter()) != null) {
int columnIndex = header.columnAtPoint(pt);
if (columnIndex != -1) {
columnIndex = table.convertColumnIndexToModel(columnIndex);
((TestTableRowSorter) sorter).wrapToggleSortOrder(columnIndex);
}
}
}
});
private Point pt;
public JComponent makeUI() {
timer.setRepeats(false);
table.setRowSorter(new TestTableRowSorter(model));
header = table.getTableHeader();
header.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
if (timer.isRunning() && !e.isConsumed() && e.getClickCount() > 1) {
System.out.println("double");
pt = null;
timer.stop();
} else {
pt = e.getPoint();
timer.restart();
}
}
});
JPanel p = new JPanel(new BorderLayout());
p.add(new JScrollPane(table));
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new HeaderDoubleclickTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
答案 2 :(得分:2)
一种方法是为Column2
类型实现Comparable接口,如此example所示,并使用相应的Column3
值进行比较。方便的是,如果Column3
已经实施Comparable<Column3>
,您可以委托Column3
,example与Double
一起委托。