我有2个JTables
,一个用于显示行,另一个用于显示数据:
问题:对数据表进行排序时,还将对行进行排序:
是否可以使“ RowHeaderView”表不像数据表那样进行排序?
public class SimpleJTableHeader extends JFrame {
public JTable table;
public SimpleJTableHeader() {
// CREATE A JTABLE
Object rowData[][] = { { "a" }, { "b" }, { "c" }, { "d" } };
Object columnNames[] = { "1" };
table = new JTable(rowData, columnNames);
table.setRowHeight(20);
table.setAutoCreateRowSorter(true);
JScrollPane scrollPane = new JScrollPane(table);
// ADD ROW NUMBERS TO THE TABLE
scrollPane.setRowHeaderView(getHeaderTable());
// SHOW TABLE
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
public JTable getHeaderTable() {
final AbstractTableModel model = new AbstractTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getColumnCount() {
return 1;
}
@Override
public Object getValueAt(int row, int column) {
return table.convertRowIndexToModel(row);
}
@Override
public int getRowCount() {
return table.getRowCount();
}
};
JTable headerTable = new JTable(model);
headerTable.setPreferredScrollableViewportSize(new Dimension(40, 0));
headerTable.setRowHeight(20);
return headerTable;
}
public static void main(String args[]) {
new SimpleJTableHeader();
}
}
最佳答案
感谢mKorbel提供了新的正确的getHeaderTable方法:
public JTable getHeaderTable() {
DefaultTableModel model = new DefaultTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getColumnCount() {
return 1;
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
@Override
public int getRowCount() {
return table.getRowCount();
}
@Override
public Class<?> getColumnClass(int colNum) {
switch (colNum) {
case 0:
return String.class;
default:
return super.getColumnClass(colNum);
}
}
};
JTable headerTable = new JTable(model);
for (int i = 0; i < table.getRowCount(); i++) {
headerTable.setValueAt((i + 1), i, 0);
}
headerTable.setPreferredScrollableViewportSize(new Dimension(40, 0));
headerTable.setRowHeight(20);
return headerTable;
}
关于java - 为HeaderView禁用JTable Rowsorter,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21041837/