渲染编辑编号:在单元格编辑后维护 JTable 格式
当使用自定义单元格渲染扩展 JTable 时,即使保持渲染也很重要单元格编辑后。这包括保留单元格渲染器内的格式。
问题:
为使用自定义单元格渲染器格式化的 JTable 列实现 JTextField 编辑器后,单元格丢失其自定义编辑后渲染
解决方案:
发生格式丢失的原因是模型在单元格值更改时未更新渲染器。要解决此问题,请确保在任何表格模型更改后调用单元格渲染器。
实现:
示例代码:
提供的示例代码通过创建 JTable 演示了此方法具有货币格式的列,可在单元格编辑后保持格式:
import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.text.NumberFormat; import java.util.EventObject; public class RenderEditNumber extends JPanel { private NumberFormat nf = NumberFormat.getCurrencyInstance(); public RenderEditNumber() { 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) { @Override // Always selectAll() public boolean editCellAt(int row, int column, EventObject e) { boolean result = super.editCellAt(row, column, e); final Component editor = getEditorComponent(); if (editor == null || !(editor instanceof JTextComponent)) { return result; } EventQueue.invokeLater(new Runnable() { @Override public void run() { ((JTextComponent) editor).selectAll(); } }); return result; } }; table.setDefaultRenderer(Double.class, new CurrencyRenderer(nf)); table.setDefaultEditor(Double.class, new CurrencyEditor(nf)); add(new JScrollPane(table)); } public static void main(String[] args) { EventQueue.invokeLater(() -> new RenderEditNumber().display()); } } class CurrencyRenderer extends DefaultTableCellRenderer { private NumberFormat formatter; public CurrencyRenderer(NumberFormat formatter) { this.formatter = formatter; setHorizontalAlignment(JLabel.RIGHT); } @Override public void setValue(Object value) { setText((value == null) ? "" : formatter.format(value)); } } class CurrencyEditor extends DefaultCellEditor { private NumberFormat formatter; private JTextField textField; public CurrencyEditor(NumberFormat formatter) { super(new JTextField()); this.formatter = formatter; textField = (JTextField) 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; } }
通过利用这种方法,JTable 单元格即使在编辑后也能保持自定义渲染,从而实现一致的数据呈现并改善用户体验。
以上是如何在编辑后维护自定义 JTable 单元格渲染?的详细内容。更多信息请关注PHP中文网其他相关文章!