0

我遇到了一个问题,即输入的数据不能持久化。我想将 java Swing GUI 存储到 XML 文件并在以后重用它们。现在我成功存储了 GUI。但是在我在文本字段中输入一些数据之后。输入的数据不能编码成 XML 文件。你能帮我存储 GUI 和键入的内容吗?下面是使用 javabeans XMLencoder 的代码:

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();

}
}

请帮我解决这个问题。非常感谢!

4

1 回答 1

0

可能是text属性 is transient,这意味着它不会被自动保存到输出中ObjectOutputStream。您可能必须明确编写该字段。

于 2012-10-26T16:09:36.920 回答