-1

For my program I have two buttons, "Add" and "Save". When I click "Add" a button is added to the JPanel. My question is, how do I save the current state of my program with all the buttons the user added? Do I use serialization? Here is a snippet of my code:

public class saveButton
{
   //JFrame and JPanels have been declared earlier

   class ClickListener implements ActionListener
   {
       public void actionPerformed(ActionEvent e)
       {
           String str = JOptionPane.showInputDialog("Name of button");
           JButton b = new JButton(str);
           frame.add(b);
       }
   }
   ActionListener addButtonClicked = new ClickListener();
   b.addActionListener(addButtonClicked);

   class ClickListenerTwo implements ActionListener
   {
       public void actionPerformed(ActionEvent f)
       {
           //save all of the program 
       }

   } 

}

D.Maximov
  • 53
  • 1
  • 8
  • Yep, serialization may work – Scary Wombat Mar 02 '16 at 02:38
  • @Scary Wombat How would I use serialization for this part? I'm sure I'm not supposed to serialize the buttons, since there could be a million of them. Should I serialize the JFrame or JPanel? – D.Maximov Mar 02 '16 at 02:40
  • 1) *"Here is a snippet of my code:"* Does this.. `String str = JOptionPane.showMessageDialog(null, "Name of button");` ..even compile? 2) See [Detection/fix for the hanging close bracket of a code block](http://meta.stackexchange.com/q/251795/155831) for a problem I could no longer be bothered fixing. – Andrew Thompson Mar 02 '16 at 02:51
  • @Andrew Thompson I fixed it – D.Maximov Mar 02 '16 at 02:53
  • *"Sorry."* Don't be sorry, be smart. For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). And copy it to a new project & confirm it does all it states, before claiming it is an MCVE. – Andrew Thompson Mar 02 '16 at 02:54
  • As a general suggestion, serialization is not meant for the long term storage of objects and you should generally avoid it (want to send an object over the network, probably okay) – MadProgrammer Mar 02 '16 at 02:56
  • *"I fixed it"* That edit replaced one piece of uncompilable code with another piece of uncompilable code. – Andrew Thompson Mar 02 '16 at 02:57
  • 2
    @MadProgrammer *"As a general suggestion, serialization is not meant for the long term storage of objects.."* I think it's useful to clarify that advice applies to "object serialization' using Java's default object serialization. There are many other ways to serialize data/program state. I will typically make a Java bean of whatever needs storing, and use `XMLEncoder` & `XMLDecoder` to write/read it. As far as 'other methods' of serialization go, there are many options. See [this answer](http://stackoverflow.com/a/7954955/418556) for details of some. – Andrew Thompson Mar 02 '16 at 03:04

3 Answers3

1

You can only serialize (meaning straight Java serialization) if your object and every non-transient member within the class supports serialization. This is not always possible.

However, you could define your own configuration object that contains the necessary state information and save it whenever (could be just before closing app, could be every time the state changes, it's up to you) and serialization might be a way to do it

Scott Sosna
  • 1,443
  • 1
  • 8
  • 8
  • How would I do the serialization part? Because I'm pretty sure I'm not supposed to serialize my buttons, cause there could be a lot of them. Could I serialize my JPanel or JFrame? – D.Maximov Mar 02 '16 at 02:43
  • JPanels are serializable, though I must admit I've never tried to serialize. The other problem with serializing base JDK classes is you might not be able to reinflate into a different version. Personally, I would have separate objects tracking what needs to be serialized and then using ObjectOutputStream/ObjectInputStream on that, decoupling the state of the app from the actual implementation. BUt that's just me. – Scott Sosna Mar 02 '16 at 02:49
0

It depends on how you save it. You can write the state onto a file and then recover it from there by reading it. The number of buttons and the order etc. You have to decide on the format on how you want to save it too. For example you may want to store in one line

Save,JButton,imageSrc,xpos,ypos

So when you read that line and split on ',' you know that Save is the text, JButton is the class, etc.

Hope this helps

Zaid Qureshi
  • 1,203
  • 1
  • 10
  • 15
0

I would write my own file format rather than deal with the overhead of Java's serialization. This has the benefit of being more easily readable in other languages and of slightly better performance. Furthermore, as @MadProgrammer pointed out the Serialization of Swing object is not currently supported and will not be compatible with future releases:

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeans™ has been added to the java.beans package. Please see XMLEncoder.

(link)

Here is an example:

public void saveState(){
    File stateFile = new File("./stateFile");
    FileOutputStream fos = new FileOutputStream(stateFile);
    DataOutputStream dos = new DataOutputStream(fis);

    for(JButton button : jButtons){ //store the buttons in an arraylist when they are created (you could also iterate over the added components and use instanceof)
        dos.writeUTF(button.getText());
    }

    dos.writeUTF("end"); //have some sort of end marker

    dos.flush();
    dos.close();
    fos.flush();
    fos.close()
}

public void loadState(){
    File stateFile = new File("./stateFile");
    FileInputStream fis = new FileInputStream(stateFile);
    DataInputStream dis = new DataInputStream(fis);
    String name;

    while(!(name = dis.readUTF()).equals("end")){
        add(new JButton(name));
    }

    fis.close();
}
john01dav
  • 1,842
  • 1
  • 21
  • 40
  • Would I then add this into my actionListener for my "Save" button? – D.Maximov Mar 02 '16 at 02:49
  • You would call these methods wherever you needed them -- that could very well be in your save button although it is something that we can't decide for you as it is your program. – john01dav Mar 02 '16 at 02:50
  • 1
    Straight from the [JavaDocs](https://docs.oracle.com/javase/8/docs/api/javax/swing/JButton.html) *"Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeans™ has been added to the java.beans package. Please see XMLEncoder."* – MadProgrammer Mar 02 '16 at 02:57
  • @MadProgrammer So I shouldn't use Serialization? – D.Maximov Mar 02 '16 at 03:00
  • 1
    @D.Maximov As a general rule "object serialization" (using an `ObjectOutputStream`) is not generally recommended, there are a number of other ways to do this, maybe using JAXB or Java Bean's XML encoder/decoder or `Properties` or `Preferences`, which you use will come down to what you want to achieve, there is no "easy one fits all" answer – MadProgrammer Mar 02 '16 at 03:08
  • 1
    @MadProgrammer I'll try to use properties then. – D.Maximov Mar 02 '16 at 03:13