1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
|
package auditorg_int;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
/**
* @version 1.2 08/13/99
*/
public class JRadioButtonTableExample2 extends JPanel {
public JRadioButtonTableExample2(){
DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(
new Object[][]{
{"1",new Integer(-1)}},
new Object[]{"Answer"});
JTable table = new JTable(dm);
String[] answer = {"0","1","2","3","4"};
table.getColumn("Answer").setCellRenderer(
new RadioButtonRenderer(answer)
);
table.getColumn("Answer").setCellEditor(
new RadioButtonEditor(new JCheckBox(),
new RadioButtonPanel(answer))
);
JScrollPane scroll = new JScrollPane(table);
this.add( scroll );
}
// Cell base
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;
}
}
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;
}
}
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();
}
}
} |
Partager