我有一个JTable
,我根据一个特定的列对它进行排序。然后我根据特定的条件给表格单元格上色。问题是,当表格被排序时,彩色单元格的位置仍然在相同的位置。
secondary_table=new JTable(table_model);
TableRowSorter<TableModel> sorter = new TableRowSorter<>(secondary_table.getModel());
secondary_table.setRowSorter(sorter);
ArrayList<RowSorter.SortKey> sortKeys = new ArrayList<>();
int columnIndexToSort = 3;
sortKeys.add(new RowSorter.SortKey(columnIndexToSort, SortOrder.ASCENDING));
sorter.setSortKeys(sortKeys);
sorter.sort();
secondary_table=new JTable(table_model){
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
Component comp = super.prepareRenderer(renderer, row, col);
Object value = getModel().getValueAt(row, col);
if (value.equals("غائب")) {
comp.setBackground(Color.red);
comp.setForeground(Color.white);
} else if (value.equals("دوام كامل")) {
comp.setBackground(Color.green);
comp.setForeground(Color.black);
} else if (value.equals("دوام جزئي دخول فقط") || value.equals("دوام جزئي خروج فقط") ) {
comp.setBackground(Color.yellow);
comp.setForeground(Color.black);
}
else {
comp.setBackground(Color.white);
comp.setForeground(Color.black);
}
return comp;
}
};
JScrollPane scrollPane1= new JScrollPane();
JFrame frame1=new JFrame(employee_name);
JPanel pp=new JPanel();
frame1.add(pp);
frame1.setVisible(true);
frame1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
frame1.getContentPane().add(new JScrollPane(scrollPane1.add(secondary_table)), "Center");
frame1.pack();```
secondary_table=new JTable(table_model);
TableRowSorter<TableModel> sorter = new TableRowSorter<>(secondary_table.getModel());
secondary_table.setRowSorter(sorter);
ArrayList<RowSorter.SortKey> sortKeys = new ArrayList<>();
int columnIndexToSort = 3;
sortKeys.add(new RowSorter.SortKey(columnIndexToSort, SortOrder.ASCENDING));
sorter.setSortKeys(sortKeys);
sorter.sort();
secondary_table=new JTable(table_model){
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
Component comp = super.prepareRenderer(renderer, row, col);
Object value = getModel().getValueAt(row, col);
if (value.equals("غائب")) {
comp.setBackground(Color.red);
comp.setForeground(Color.white);
} else if (value.equals("دوام كامل")) {
comp.setBackground(Color.green);
comp.setForeground(Color.black);
} else if (value.equals("دوام جزئي دخول فقط") || value.equals("دوام جزئي خروج فقط") ) {
comp.setBackground(Color.yellow);
comp.setForeground(Color.black);
}
else {
comp.setBackground(Color.white);
comp.setForeground(Color.black);
}
return comp;
}
};
JScrollPane scrollPane1= new JScrollPane();
JFrame frame1=new JFrame(employee_name);
JPanel pp=new JPanel();
frame1.add(pp);
frame1.setVisible(true);
frame1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
frame1.getContentPane().add(new JScrollPane(scrollPane1.add(secondary_table)), "Center");
frame1.pack();```
一旦表被排序,我们需要依赖convertRowIndexToView(int)
&convertRowIndexToModel(int)
.
这在官方教程如何使用表:排序和过滤中有介绍。