在JList或者JTable的中加入checkbox

public class RadioButtonPanel extends JPanel {
JRadioButton[] buttons;

RadioButtonPanel(String[] str) {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
buttons = new JRadioButton[str.length];
for (int i=0; i<buttons.length; i++) {
buttons[i] = new JRadioButton(str[i]);
buttons[i].setFocusPainted(false);
add(buttons[i]);
}
}

public void setSelectedIndex(int index) {
for (int i=0;i<buttons.length;i++) {
buttons[i].setSelected(i == index);
}
}

public int getSelectedIndex() {
for (int i=0; i<buttons.length; i++) {
if (buttons[i].isSelected()) {
return i;
}
}
return -1;
}

public JRadioButton[] getButtons() {
return buttons;
}
}

public class RadioButtonRenderer extends RadioButtonPanel
implements TableCellRenderer {
RadioButtonRenderer(String[] strs) {
super(strs);
}

public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof Integer) {
setSelectedIndex(((Integer)value).intValue());
}
return this;
}
}

public class RadioButtonEditor extends DefaultCellEditor
implements ItemListener {
RadioButtonPanel panel;

public RadioButtonEditor(JCheckBox checkBox,RadioButtonPanel panel) {
super(checkBox);
this.panel = panel;
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton[] buttons = panel.getButtons();
for (int i=0; i<buttons.length; i++) {
buttonGroup.add(buttons[i]);
buttons[i].addItemListener(this);
}
}

public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
if (value instanceof Integer) {
panel.setSelectedIndex(((Integer)value).intValue());
}
return panel;
}

public Object getCellEditorValue() {
return new Integer(panel.getSelectedIndex());
}

public void itemStateChanged(ItemEvent e) {
super.fireEditingStopped();
}
}

在程序中加入以上类
然后在你的Table类中加入一下方法:
public void setCloumnToRadioButton(Object cloumnName, String[] selections) {
getColumn(cloumnName).setCellRenderer(
new RadioButtonRenderer(selections)
);
getColumn(cloumnName).setCellEditor(
new RadioButtonEditor(new JCheckBox(),
new RadioButtonPanel(selections))
);
}

这是RadioButton的代码,不过吗CheckBox差不多了。

你可能感兴趣的:(checkbox)