0
我想保存在表中進行的更改,然後加載它時我無法每次重新啓動程序。 這裏是我到目前爲止的代碼(注意,我一直在尋求一個答案,但我不是最好的是java):如何在更改後保存JTable
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!");
}
}
你需要一個地方來存儲變化。文件或數據庫是最常見的解決方案。 –