保存在JFrame中所做的更改

时间:2014-11-10 11:32:36

标签: java swing jframe

我有一个简单的JFrame,用户正在使用JPopupMenu更改其背景颜色。当用户退出应用程序时,我想保存在后台进行的更改。

我尝试使用windowClosing()类中的方法WindowAdapter处理此问题,但是当我再次启动应用程序时,我没有看到我之前做出的更改。我不知道问题是什么。我将不胜感激任何帮助。这是我的代码。

/*i have removed unnnecessary codes*/

public class Popupframe extends JFrame{
private JRadioButtonMenuItem[] items;
private final Color[] colorvalues={Color.BLUE,Color.YELLOW,Color.RED};
static Color bgcolor=Color.CYAN;
JRadioButtonMenuItem[] cheek;

public Popupframe() {
    super("using popups");
    String[] colors = {"Blue","Yellow","Red"};

    setBackground(bgcolor);
    addMouseListener(new Handler());
}

private class Handler extends MouseAdapter implements ActionListener {


    @Override
    public void actionPerformed(ActionEvent event) {
        for(int i=0; i<items.length; i++) {
           if(event.getSource()==items[i]) {
               getContentPane().setBackground(colorvalues[i]);
               bgcolor=colorvalues[i];
           }
       }    
    }
}

public static void main(String[] args) {
    Popupframe frame=new Popupframe();
    frame.setSize(width,height);
    frame.setDefaultCloseOperation(Popupframe.DO_NOTHING_ON_CLOSE);
    frame.addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosing(WindowEvent e) {
            int ok=JOptionPane.showConfirmDialog(frame,"are sure?","close",JOptionPane.WARNING_MESSAGE);
            if(ok==JOptionPane.OK_OPTION) {
                bgcolor=frame.getContentPane().getBackground();
                System.out.println(bgcolor);
                System.exit(0);
            }
        }
    });
    frame.setVisible(true);
}

2 个答案:

答案 0 :(得分:2)

您需要在System.exit(0)之前将颜色代码保存到文件(如设置文件或共享首选项)中,并在main中读取并设置该颜色代码。然后它工作正常。

答案 1 :(得分:1)

你没有坚持这种颜色。颜色是可序列化的,因此您只需将对象保存在程序根目录中即可。将此代码放在WindowClosing方法中:

//serialize the Color
try (
  OutputStream file = new FileOutputStream("myBgColor.ser");
  OutputStream buffer = new BufferedOutputStream(file);
  ObjectOutput output = new ObjectOutputStream(buffer);
){
  output.writeObject(bgColor);
}  
catch(IOException ex){
  log.log(Level.SEVERE, "Cannot perform output.", ex);
}

当您重新加载应用程序时,您需要恢复颜色。在 PopupFrame()构造函数中,在调用 setBackground(color)之前,请在此处输入以下代码:

//deserialize the Color file
try(
  InputStream file = new FileInputStream("myBgColor.ser");
  InputStream buffer = new BufferedInputStream(file);
  ObjectInput input = new ObjectInputStream (buffer);
){
  //deserialize the List
  bgColor = (Color)input.readObject();
}
catch(ClassNotFoundException ex){
  fLogger.log(Level.SEVERE, "Cannot perform input. Class not found.", ex);
}

这应该可以解决问题。

相关问题