下面是我使用javabeans保存和加载JavaGUI的代码。
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后,将显示第二帧。我该怎么做才能意识到这一点?
1条答案
按热度按时间kx5bkwkv1#
使用时
XMLDecoder
保存的每一帧都将按写入的顺序读出。记住分配和使用readObject
: