已更新
在此代码中,鼠标单击表格单元格仍处于编辑模式且JRadioButton处于错误状态。我必须按ESC键以退出编辑模式,让渲染器在单元格中呈现JRadioButton的正确状态。有人知道我需要在代码中实现什么才能让单元格编辑器发布编辑模式吗?
public class Test extends JFrame { JTable myTable = new JTable(); public Test() { this.setSize(150, 150); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { dispose(); System.exit(0); } }); setVisible(true); myTable.setModel(new MyModel()); myTable.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer()); myTable.getColumnModel().getColumn(0).setCellEditor(new MyEditor()); myTable.setTableHeader(null); this.add(myTable); } public static void main(String[] args) { Test test = new Test(); } class MyModel extends AbstractTableModel { Object myModelData[]; public MyModel() { List list = new ArrayList(); list.add(new MyModelData("item 1", new Boolean(true))); list.add(new MyModelData("item 2", new Boolean(false))); list.add(new MyModelData("item 3", new Boolean(true))); myModelData = list.toArray(); } @Override public int getColumnCount() { return 1; } @Override public String getColumnName(int column) { return ""; } @Override public int getRowCount() { return myModelData.length; } @Override public Object getValueAt(int row, int column) { return myModelData[row]; } @Override public Class getColumnClass(int column) { return JRadioButton.class; } @Override public void setValueAt(Object value, int row, int column) { myModelData[row] = value; } @Override public boolean isCellEditable(int row, int column) { return true; } } class MyModelData { private String text; private Boolean status; public MyModelData(String text, Boolean status) { this.text = text; this.status = status; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Boolean getStatus() { return status; } public void setStatus(Boolean status) { this.status = status; } } class MyRenderer extends JRadioButton implements TableCellRenderer { @Override public Component getTableCellRendererComponent(JTable t, Object v, boolean s, boolean f, int r, int c) { this.setSelected(((MyModelData) v).getStatus()); this.setText(((MyModelData) v).getText() + " rendered"); return this; } } public class MyEditor extends JRadioButton implements TableCellEditor { @Override public Component getTableCellEditorComponent(JTable t, Object v, boolean s, int r, int c) { ((MyModelData) v).setStatus(!((MyModelData) v).getStatus()); this.setText(((MyModelData) v).getText() + " in edit mode"); return this; } @Override public Object getCellEditorValue() { return null; } @Override public boolean isCellEditable(EventObject event) { return true; } @Override public boolean shouldSelectCell(EventObject anEvent) { return true; } @Override public boolean stopCellEditing() { return true; } @Override public void cancelCellEditing() { } @Override public void addCellEditorListener(CellEditorListener l) { } @Override public void removeCellEditorListener(CellEditorListener l) { } } }