我有一个简单的 JTable,第一列是整数,第二列是字符串。我希望能够对每一列进行排序。
我的渲染器:
package gui.table;
import gui.DaimlerColor;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
@SuppressWarnings("serial")
public class StandardCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
c.setBackground((isSelected ? DaimlerColor.LIGHT_BLUE : (row % 2 == 1 ? DaimlerColor.DARK_WHITE : DaimlerColor.WHITE)));
if(isSelected){
c.setBackground(DaimlerColor.LIGHT_BLUE);
}
return c;
}
}
我的表模型:
package gui.table;
import java.util.List;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import org.jdom2.Element;
import reporting.FailureClassificationCatalogue;
@SuppressWarnings("serial")
public class ReportTableModel extends DefaultTableModel {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
public ReportTableModel(List<Element> reports) {
super(createDataVector(reports), createColumnNames());
}
private static Vector<Vector<Object>> createDataVector(List<Element> reports) {
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
for (int i = 0; i < reports.size(); i++) {
Vector<Object> row = new Vector<Object>();
if(reports.get(i).getName().equals("Default")){
row.add("-");
}
else{
row.add(Integer.valueOf(i+1));
}
String title = reports.get(i).getAttributeValue("type");
try{
title = FailureClassificationCatalogue.valueOf(title).getName();
}catch(IllegalArgumentException iae){
}catch(NullPointerException npe){
}
row.add(title);
data.add(row);
}
return data;
}
@Override
public Class<?> getColumnClass(int colNum) {
switch (colNum) {
case 0:
return Integer.class;
case 1:
return String.class;
default:
return String.class;
}
}
private static Vector<String> createColumnNames() {
Vector<String> columns = new Vector<String>();
columns.add("Number");
columns.add("Error Type");
return columns;
}
/**
* overridden to ignore null values
*/
@Override
public void setValueAt(Object value, int row, int col) {
if (value == null) {
return;
}
// delegate to the parent method
super.setValueAt(value, row, col);
}
}
如果我不实现 getColumnClass,那么渲染器工作正常,但整数被排序为字符串。一旦我实现该方法,渲染器就无法正常工作(背景仅设置在一列中),但整数排序正确。我该如何解决这个问题?
我的代码来设置渲染器和排序器:
reporttable = new JTable();
reporttable.setName("report");
reporttable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reporttable.setRowHeight(40);
reporttable.addMouseListener(tgc.mouseListener);
reporttable.setDefaultRenderer( Object.class, new StandardCellRenderer());
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>();
reporttable.setRowSorter(sorter);
sorter.setModel(reportModel);
有任何想法吗?谢谢。