将 JTable 列设置为 String 并将其排序为 Double 后,自定义单元格渲染器最初将列格式化为 $###,##0.00 在该值变为后停止渲染单元格
编辑单元格时,会依次发生以下事件:
为了在编辑后保持单元格渲染,以下步骤是必要:
以下是使用默认编辑器和渲染器实现的基本示例:
import javax.swing.DefaultCellEditor; import javax.swing.DefaultTableCellRenderer; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import java.text.NumberFormat; public class RenderEditNumber { public static void main(String[] args) { NumberFormat nf = NumberFormat.getCurrencyInstance(); DefaultTableModel model = new DefaultTableModel( new String[]{"Amount"}, 0) { @Override public Class<?> getColumnClass(int columnIndex) { return Double.class; } }; for (int i = 0; i < 16; i++) { model.addRow(new Object[]{Double.valueOf(i)}); } JTable table = new JTable(model); table.setPreferredScrollableViewportSize(new Dimension(123, 123)); table.setDefaultRenderer(Double.class, new CurrencyRenderer(nf)); table.setDefaultEditor(Double.class, new CurrencyEditor(nf)); } private static class CurrencyRenderer extends DefaultTableCellRenderer { private NumberFormat formatter; public CurrencyRenderer(NumberFormat formatter) { this.formatter = formatter; this.setHorizontalAlignment(JLabel.RIGHT); } @Override public void setValue(Object value) { setText((value == null) ? "" : formatter.format(value)); } } private static class CurrencyEditor extends DefaultCellEditor { private NumberFormat formatter; private JTextField textField; public CurrencyEditor(NumberFormat formatter) { super(new JTextField()); this.formatter = formatter; this.textField = (JTextField) this.getComponent(); textField.setHorizontalAlignment(JTextField.RIGHT); textField.setBorder(null); } @Override public Object getCellEditorValue() { try { return new Double(textField.getText()); } catch (NumberFormatException e) { return Double.valueOf(0); } } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { textField.setText((value == null) ? "" : formatter.format((Double) value)); return textField; } } }
在此示例中,CurrencyRenderer 和CurrencyEditor 类分别扩展了默认渲染器和编辑器实现,以处理数字格式。请注意,此示例不包括 fireTableCellUpdated() 调用,因为它是由 JTable 内部处理的。
以上是如何在单元格编辑后保持 JTable 单元格渲染?的详细内容。更多信息请关注PHP中文网其他相关文章!