尝试使用渲染器和编辑器向 JTable 添加单选按钮导致无法实现排他性。提供的代码片段演示了该问题。
作为替代方案,请考虑使用 JComboBox 作为行内互斥选择的编辑器。这是一种更有效的空间管理和用户体验方法。
// ... // Import declarations // ... public class JRadioAsRendererEditor extends JPanel { // ... // Class variables and methods // ... private class StatusRenderer extends StatusPanel implements TableCellRenderer { // ... // Overridden methods // ... @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setStatus((Status) value); if (isSelected) { setBackground(table.getSelectionBackground()); } else { setBackground(table.getBackground()); } return this; } } }
1。替代渲染器和编辑器
您可以创建自己的自定义渲染器和编辑器类来实现所需的行为。这是一个示例:
public class RadioCellRenderer extends DefaultTableCellRenderer { private RadioButtonGroup group; public RadioCellRenderer(RadioButtonGroup group) { this.group = group; } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JRadioButton button = (JRadioButton) value; button.setSelected(group.isSelected(button)); return button; } } public class RadioCellEditor extends DefaultCellEditor { private RadioButtonGroup group; public RadioCellEditor(JRadioButtonCheckBox box, RadioButtonGroup group) { super(box); this.group = group; } @Override public Object getCellEditorValue() { return delegate.get(); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { JRadioButton button = (JRadioButton) value; if (group.isClearable()) { group.clearSelection(); } group.add(button); return button; } }
2。 DefaultTableCellRenderer 和 DefaultCellEditor
您可以将 DefaultTableCellRenderer 和 DefaultCellEditor 类与处理排他性的自定义 JRadioButton 一起使用。这是一个示例:
public class ExclusiveJRadioButton extends JRadioButton { private RadioButtonGroup group; public ExclusiveJRadioButton(RadioButtonGroup group) { this.group = group; addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { group.setSelected(ExclusiveJRadioButton.this, true); } }); } @Override public void setSelected(boolean selected) { if (group.isSelected(this)) { return; } super.setSelected(selected); } }
以上是向 JTable 组添加单选按钮时如何实现排他性?的详细内容。更多信息请关注PHP中文网其他相关文章!