我想将jtable的名称和值保存到两个变量
中public class NewClass extends JPanel implements TableModelListener {
private final String[] columnNames = { "Name", "Value","check"};
private JTable table;
private DefaultTableModel tableModel;
private final JButton buttonSave;
public NewClass(){
tableModel = new DefaultTableModel(columnNames, 0);
tableModel.addTableModelListener(this);
table = new JTable(tableModel);
javax.swing.table.TableColumn var_col;
var_col = table.getColumnModel().getColumn(2);
final JCheckBox check = new JCheckBox();
var_col.setCellEditor(new DefaultCellEditor(check));
var_col.setCellRenderer(new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row, int
column) {
check.setSelected(((Boolean)value).booleanValue()) ;
return check;
}
});
JScrollPane scrollPane = new JScrollPane(table);
setLayout(new BorderLayout());
setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
add(BorderLayout.NORTH, new JLabel("Mon panier", JLabel.CENTER));
add(BorderLayout.CENTER, scrollPane);
//--------I want to save these Name and value in two variables -----------
Object[] data1 = {
new String("work"), new String("done"),new Boolean(false)};
tableModel.addRow(data1);
buttonSave = new JButton("Save");
buttonSave.setEnabled(false);
buttonSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
buttonSave.setEnabled(false);
}
});
答案 0 :(得分:3)
正如How to Use Tables中所述,您的表格数据应由TableModel
管理,例如AbstractTableModel
或您示例中使用的具体DefaultTableModel
。在此example中,DataModel
扩展AbstractTableModel
并合成List<Value>
个测试数据;你会听到监控串口的任何对象。 example也使用类Value
来封装可选择的数值。自定义TableCellEditor
会在更改时更新每个Value
,因此DataModel
始终包含列表中每个元素的选择状态。然后,您的保存按钮可以以您喜欢的任何格式保存列表元素。