按下save按钮时保存Jtable数据

时间:2011-01-07 04:05:22

标签: java swing jtable

我想将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);
}
});

1 个答案:

答案 0 :(得分:3)

正如How to Use Tables中所述,您的表格数据应由TableModel管理,例如AbstractTableModel或您示例中使用的具体DefaultTableModel。在此example中,DataModel扩展AbstractTableModel并合成List<Value>个测试数据;你会听到监控串口的任何对象。 example也使用类Value来封装可选择的数值。自定义TableCellEditor会在更改时更新每个Value,因此DataModel始终包含列表中每个元素的选择状态。然后,您的保存按钮可以以您喜欢的任何格式保存列表元素。