我有一个简单的JTable
,有3列。数字变大,所以我通过在其中加入逗号来格式化它们,即100,000。但是,这样做,我的表排序不起作用。
我该如何解决这个问题?
package tables;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class mainwindow extends JPanel {
public static void main(String[] args) {
Object[][] data = {
{"75,500", "Don't Let Go", new Integer(179)},
{"121,343", "Photograph", new Integer(29)},
{"32,323", "Hash Pipe", new Integer(186)}
};
Object[] columns = {"Track #", "Title", "Length"};
DefaultTableModel model = new DefaultTableModel(data,columns) {
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
default:
return String.class;
}
}
};
JTable table = new JTable(model);
JScrollPane scroll = new JScrollPane(table);
table.setAutoCreateRowSorter(true);
JOptionPane.showMessageDialog(null, scroll);
}
}
答案 0 :(得分:3)
你不会因为数据是字符串而不是数字而得到第一列的数字排序,我建议你将数据保存为整数,
Object[][] data = {
{75500, "Don't Let Go", new Integer(179)},
{121343, "Photograph", new Integer(29)},
{32323, "Hash Pipe", new Integer(186)}
};
创建并使用具有所需格式的新cellRender:
table.setDefaultRenderer(Integer.class, new DefaultTableCellRenderer() {
private NumberFormat numberFormat = new DecimalFormat("#,###,###");
@Override
protected void setValue(Object aValue) {
Integer value = (Integer) aValue;
super.setValue(numberFormat.format(value));
}
});