2014-05-20 82 views
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!"); 
} 

} 
+1

你需要一個地方來存儲變化。文件或數據庫是最常見的解決方案。 –

回答

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

+0

可能值得一提的是,爲了使其工作,寫入流的對象必須實現'java.io.Serializable'接口。 – JonK