2012-10-26 27 views
0

我遇到了類型化數據不能持久化的問題。我想將Java Swing GUI存儲到XML文件中並在後者中重用它們。現在我成功地存儲了GUI。但在我輸入一些數據到文本框後。輸入的數據不能編碼到XML文件中。你能幫我存儲GUI和輸入內容嗎?下面是使用javabeans XMLencoder的代碼:Javabeans不能持久輸入數據

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.FlowLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.BorderFactory; 
import javax.swing.BoxLayout; 
import javax.swing.JButton; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JSeparator; 
import javax.swing.JTextField; 
import javax.swing.JTextPane; 
import java.beans.*; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import javax.swing.JFileChooser; 
import javax.swing.JFrame; 
import javax.swing.JOptionPane; 


public class ResourceName extends JFrame implements ActionListener{ 
static JFileChooser chooser; 
JButton save,load; 
JTextField tf; 
static JFrame frame; 
public ResourceName(){ 

    chooser = new JFileChooser(); 
    chooser.setCurrentDirectory(new File(".")); 

    frame = new JFrame("ResourceName"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setLayout(new FlowLayout()); 
    save = new JButton("Save"); 
    save.setActionCommand("Save"); 
    save.addActionListener(this); 

    load = new JButton("Load"); 
    load.setActionCommand("Load"); 
    load.addActionListener(this); 
    tf = new JTextField(10); 

    frame.add(save); 
    frame.add(tf); 
    frame.add(load);  

    frame.pack(); 
    frame.setVisible(true); 
} 

    public void actionPerformed(ActionEvent e){ 

     if((e.getActionCommand()).equals("Save")) 
     { 
      save(); 
     }else if((e.getActionCommand()).equals("Load")) 
     { 
      load(); 
     } 
    } 


public void save() 
{ 
    if(chooser.showSaveDialog(null)==JFileChooser.APPROVE_OPTION) 
    { 
     try{ 
      File file = chooser.getSelectedFile(); 
      XMLEncoder encoder = new XMLEncoder(new FileOutputStream(file)); 
      encoder.writeObject(frame); 
      encoder.close(); 
     } 
     catch(IOException e) 
     { 
      JOptionPane.showMessageDialog(null, e); 
     } 
    } 
} 
    public void load() 
{ 
    //show file chooser dialog 
    int r = chooser.showOpenDialog(null); 

    // if file selected, open 
    if(r == JFileChooser.APPROVE_OPTION) 
    { 
     try 
     { 
      File file = chooser.getSelectedFile(); 
      XMLDecoder decoder = new XMLDecoder(new FileInputStream(file)); 
      decoder.readObject(); 
      decoder.close(); 
     } 
     catch(IOException e) 
     { 
      JOptionPane.showMessageDialog(null, e); 
     } 
    } 
} 

public static void main(String[] args) { 

    ResourceName test = new ResourceName(); 

} 
} 

請幫我解決這個問題。非常感謝!

回答

0

它可能是text財產,是transient,這意味着它不會被自動保存到輸出,由ObjectOutputStream。您可能必須明確寫入該字段。