我想使用 JavaBeans Persistence 机制将我的 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;
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"));
frame.setVisible(true);
}
public void registry(){
Registry re = new Registry();
}
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 class Registry {
public Registry(){
JFrame 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);
}
}
当我按下保存按钮时,我想同时保存两个帧。现在我只能保存主框架。请帮我解决这个问题。非常感谢。