以下是我使用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后,将出现第二帧。我该怎么做才能实现这个目标?
答案 0 :(得分:2)
使用XMLDecoder
时,每个保存的帧将以与写入时相同的顺序读回。请记住分配&使用readObject
:
JFrame mainFrame = (JFrame) xmlDecoder.readObject();
mainFrame.setVisible(true);