2010-01-11 26 views
6

我有一個用Swing製作的簡單的Java GUI窗體。它有一些文本輸入和複選框,我希望它記住輸入到這些的最後一個值。當然,可以手動將它們保存到某個文件中,然後讀取文件並填充輸入,但是我不知道是否有辦法自動執行此操作。由於如何記住Swing GUI窗體中的最後一個值?

+0

只是不使用Java序列化! – 2010-01-11 16:34:06

+0

@Tom:爲什麼不準確? – OscarRyz 2010-01-11 16:48:59

回答

2

根據應用程序的大小和數據量,序列化整個UI可能是一種選擇。

這可能是一個壞主意,但是,當信息基本上被檢索並存儲在數據庫中了。在這種情況下,應該使用值對象和綁定,但對於UI與另一種持久化方式無關的一些簡單應用程序,您可以使用它。

當然,你不能修改序列化值,直接這樣,就認爲這是一個額外的選項:

alt text http://img684.imageshack.us/img684/4581/capturadepantalla201001p.png

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.io.*; 

public class SwingTest { 
    public static void main(String [] args) { 
     final JFrame frame = getFrame(); 
     frame.pack();   
     frame.setVisible(true); 
     Runtime.getRuntime().addShutdownHook(new Thread() { 
      public void run() { 
       writeToFile(frame, "swingtest.ser"); 
      } 
     }); 
    } 

    /** 
    * Reads it serialized or create a new one if it doens't exists 
    */ 
    private static JFrame getFrame(){ 
     File file = new File("swingtest.ser"); 
     if(!file.exists()) { 
      System.out.println("creating a new one"); 
      JFrame frame = new JFrame(); 
      JPanel panel = new JPanel(); 
      panel.add(new JLabel("Some test here:")); 
      panel.add(new JTextField(10)); 
      frame.add(panel); 
      return frame; 
     } else { 
      return (JFrame) readObjectFrom(file); 
     } 
    } 

這裏的讀/寫爲素描,有很多這裏有待改進的餘地。

/** 
    * write the object to a file 
    */ 
    private static void writeToFile(Serializable s , String fileName) { 
     ObjectOutputStream oos = null; 

     try { 
      oos = new ObjectOutputStream(new FileOutputStream(new File(fileName))); 
      oos.writeObject(s);  
     } catch(IOException ioe){ 

     } finally { 
      if(oos != null) try { 
       oos.close(); 
      } catch(IOException ioe){} 
     } 

    } 
    /** 
    * Read an object from the file 
    */ 
    private static Object readObjectFrom(File f) { 
     ObjectInputStream ois = null; 
     try { 
      ois = new ObjectInputStream(new FileInputStream(f)) ; 
      return ois.readObject(); 
     } catch(ClassNotFoundException cnfe){ 
      return null; 
     } catch(IOException ioe) { 
      return null; 
     } finally { 
      if(ois != null) try { 
       ois.close(); 
      } catch(IOException ioe){} 
     } 
    } 
} 
0

不是真的。您必須注意將值保存到文件或數據庫中。

5

優選使用Preferences API

它存儲在系統中的喜好,但這個細節被隱藏你 - 你專注於你的喜好的結構和值,而不是實現細節(這是特定於平臺)。

此API還允許在同一臺機器上的不同用戶的不同設置。

+0

要試一試 – Fluffy 2010-01-11 16:43:54

相關問題