1

这是我使用 javabeans 保存和加载 java GUI 的代码。

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

public class BeansTest {
  private static JFileChooser chooser;
private JFrame frame;
Registry re;

public static void main(String[] args){
    chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    BeansTest test = new BeansTest();
    test.init();
}

public void init(){
    frame = new JFrame();
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setTitle("PersistentFrameTest");
    frame.setSize(400,200);

    JButton registryButton = new JButton("Registry");
    frame.add(registryButton);
    registryButton.addActionListener(EventHandler.create(ActionListener.class, this, "registry"));

    JButton saveButton = new JButton("Save");
    frame.add(saveButton);
    saveButton.addActionListener(EventHandler.create(ActionListener.class, this, "save"));

    JButton loadButton = new JButton("Load");
    frame.add(loadButton);
    loadButton.addActionListener(EventHandler.create(ActionListener.class, this, "load"));

    frame.setVisible(true);
}

public void registry(){

re = new Registry();
//re.getFrame();
}

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);
            if (re.getFrame() != null) {
                encoder.writeObject(re.getFrame());
            }
            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 class Registry {

JFrame frame;

public Registry(){

    frame = new JFrame();
    frame.setLayout(new FlowLayout());
    frame.setSize(400,200);

    JLabel nameL = new JLabel("Name:");
    JTextField nameF = new JTextField(8);

    frame.add(nameL);
    frame.add(nameF);


    frame.setVisible(true);

}
public JFrame getFrame(){

    return frame;
}
}

在这个程序中,我有两个框架:主框架和注册表框架。因为我将这两帧保存在一个 XML 文件中。所以当我加载这个文件时,我会同时得到这两个帧。我想要做的是,当用户加载 XML 文件时,他只获得主框架。用户单击registryButton 后,会出现第二个框架。我应该怎么做才能意识到这一点?

4

1 回答 1

2

使用XMLDecoder保存的每一帧时,将按照写入时的相同顺序读出。请记住分配并使用以下结果readObject

JFrame mainFrame = (JFrame) xmlDecoder.readObject();
mainFrame.setVisible(true);
于 2012-08-25T11:24:41.637 回答