【发布时间】:2016-03-03 05:26:38
【问题描述】:
所以,我的程序是用户在运行时添加按钮。当他/她单击“保存”按钮时,程序将保存到文件中。但是当我再次运行它时,按钮消失了。我尝试使用 XMLEncoder 和 XMLDecoder 序列化我的按钮,但是当我运行我的程序时,它没有保存任何东西,它又重新开始了。 如何正确序列化它,以便在我启动程序时,按钮在那里?任何帮助将不胜感激。
这是我的代码的 sn-p:
public class saveButton
{
//JFrame and JPanels have been declared earlier
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
str = JOptionPane.showInputDialog("What is the name of the new button?");
JButton b = new JButton(str);
frame.add(b);
try
{
XMLEncoder encdr = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("file.ser")));
encdr.writeObject(new JButton(str));
encdr.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
ActionListener addButtonClicked = new ClickListener();
b.addActionListener(addButtonClicked);
class ClickListenerTwo implements ActionListener
{
public void actionPerformed(ActionEvent f)
{
try
{
XMLDecoder d = new XMLDecoder(new BufferedInputStream(new FileInputStream("file.ser")));
Object result = d.readObject();
d.close();
}
catch (IOException decoder)
{
decoder.printStackTrace();
}
}
}
【问题讨论】:
-
序列化你的按钮不是这里的方法。首先,你为什么要序列化它们?为了定位?还是为了别的?
-
我正在对它们进行序列化,以便以后运行程序时可以检索它们。
-
你的解码没有做任何事情,它应该将按钮添加回屏幕
-
可能对整个容器进行编码/解码
-
由于您似乎将按钮直接添加到框架的内容窗格中,因此可能对其进行编码
标签: java swing button serialization