当我尝试将值写入csv文件时遇到麻烦,我只获取默认值。内部添加按钮动作监听器我有循环,只显示默认从列模型设置在顶部,我没有任何想法所以请帮助。
编辑:我在食物日志中有这个值并且它们显示正确,但在log.csv中它们不存在
/*
* Creating default model and adding labels for food nutrients
*/
columnModel = new DefaultTableModel();
columnModel.addColumn("Name");
columnModel.addColumn("Unit Amount");
columnModel.addColumn("Calories");
columnModel.addColumn("Fat");
columnModel.addColumn("Protein");
columnModel.addColumn("Carbs");
recordBoard = new JTable(columnModel);
recordBoard.setPreferredScrollableViewportSize(recordBoard.getPreferredSize());
recordBoard.setFillsViewportHeight(true);
JTableHeader header = recordBoard.getTableHeader();
add(header);
add(recordBoard);
JPanel logButton = new JPanel();
logButton.setLayout(new BoxLayout(logButton, BoxLayout.X_AXIS));
/*
* Creating search text field for all foods
*/
JLabel comboBoxLabel = new JLabel("Search all Foods: ", JLabel.RIGHT);
csvFoods = new JComboBox();
logButton.add(comboBoxLabel);
logButton.add(csvFoods);
/*
* Creating new button for saveing food records
*/
recordSave = new JButton("Add Food");
recordSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.addLogRow(String.valueOf(csvFoods.getSelectedItem()), columnModel);
try {
columnModel = (DefaultTableModel) recordBoard.getModel();
FileWriter fw = new FileWriter(new File("log.csv"), true);
Calendar cal = Calendar.getInstance();
recordBoard.getTableHeader().setUI(null);;
fw.write("\n");
fw.write(cal.get(Calendar.YEAR) + ",");
fw.write(cal.get(Calendar.MONTH) + 1 + ",");
fw.write(cal.get(Calendar.DATE) + ",");
fw.write("f" + ",");
for (int i = 0; i <= 5; i++) {
fw.write(columnModel.getColumnName(i) + ",");
}
fw.write("\n");
fw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
答案 0 :(得分:0)
您正在访问表的列名,而不是内容本身。
要打印内容,您应该遍历每一行数据,并在每行内,遍历每一列:
for(int i = 0; i < columnModel.getRowCount(); i++) {
for(int j = 0; j < columnModel.getColumnCount(); j++) {
Object data = columnModel.getValueAt(i, j);
// print to file
}
}