嘗試使用渲染器和編輯器新增單選按鈕導致無法新增單選按鈕導致無法導致無法實現排他性。提供的程式碼片段演示了該問題。
作為替代方案,請考慮使用 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中文網其他相關文章!