问题
I have a Price column that displays integers in plain format like 1000000. I would like to know how can I format it with commas without affecting its value when retrieving with table.getValueAt()?
Is there a method like table.setColumnCellFormat(decimalFormat)?
回答1:
You need a custom TableCellRenderer
which can format the value the way you need it. See Using Custom Renderers for more details
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.text.NumberFormat;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
DefaultTableModel model = new DefaultTableModel(0, 1);
for (int index = 10000; index < 11000; index++) {
model.addRow(new Object[]{index});
}
JTable table = new JTable(model);
table.getColumnModel().getColumn(0).setCellRenderer(new NumberTableCellRenderer());
setLayout(new BorderLayout());
add(new JScrollPane(table));
}
public class NumberTableCellRenderer extends DefaultTableCellRenderer {
public NumberTableCellRenderer() {
setHorizontalAlignment(JLabel.RIGHT);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof Number) {
value = NumberFormat.getNumberInstance().format(value);
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
}
}
}
回答2:
You should create a custom TableCellRenderer for that column, one that uses a DecimalFormat instance, one that has the setDecimalSeparatorAlwaysShown(true)
called on it.
回答3:
Take a look at Table Format Renderers.
It provides a simple example of how to create a custom renderer by overriding the setValue(...)
method of the renderer.
Or you can use one of the provided classes which allows you to easily create reusable renderers with different formats.
来源:https://stackoverflow.com/questions/30250085/formatting-integers-in-jtable-column-cells-with-commas