我想保存在表格中进行的更改,然后当我想加载它时,每次重新启动程序时都会发生错误。 这是我到目前为止的代码(请注意,我已经找到了答案,但我不是最好的java):
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class Table2 extends JFrame implements ActionListener{
//String[] colomn = {"Name","Age","Gender"};
Object[][] data = {{"John","20","Male"}};
JTable table = new JTable(new DefaultTableModel(data, new Object[]{"Name", "Age","Gender"})){
public Component prepareRenderer(TableCellRenderer r, int data, int col){ //gives a pattern to the table cells.
Component c = super.prepareRenderer(r, data, col);
if(data % 2 == 0){
c.setBackground(Color.PINK);
}
else{
c.setBackground(Color.LIGHT_GRAY);
}
return c;
}
};
//JTable table = new JTable(data,colomn);
public Table2(){
table.setPreferredScrollableViewportSize(new Dimension(300,200));
table.setFillsViewportHeight(true);
JScrollPane scrollpane = new JScrollPane(table);
add(scrollpane);
}
public static void main(String[] args) {
Table2 table = new Table2();
table.setLayout(new FlowLayout());
table.setVisible(true);
table.setSize(400,300);
table.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
table.setResizable(false);
table.setTitle("Table Prictice on JFrame");
//table.pack();
JButton button = new JButton("Add");
table.add(button);
button.addActionListener(table);
}
public void actionPerformed(ActionEvent e) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{"", "", ""});
System.out.println("Action Performed!");
}
}
答案 0 :(得分:0)
您可以使用ObjectOutputStream将数据数组保存到二进制文件中,然后可以从那里读取它。 为了节省您可以使用以下内容:
ObjectOutputStream outstream = new ObjectOutputStream(new FileOutputStream("filename"));
outstream.writeObject(data);
outstream.close();
要阅读,您可以使用:
ObjectInputStream instream = new ObjectInputStream(newFileInputStream("filename"));
Object[][] data = (Object[][]) instream.readObject();
instream.close();
要获取更改的数据,请查看How to Retrieve JTable Data as an Array