將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中文網其他相關文章!