Using Serialization on JToggleButton

JToggleButton & Serializable


Now, let's talk about JToggleButton and apply serialization on it. It is quite similar to that of applying serialization on JCheckBox, i think you've already with it. As methods and creation of JCheckBox and JToggleButton are similar, i've done the following program in a very simple way by just replacing CheckBox with ToggleButton. So, the same explanation works here and hence you can refer it, all you need to do is to manually assume JCheckBox as JToggleButton, when referring that post.

JToggleButton & Serializable Example



ToggleButton Serialized

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class SerializeToggleButton extends JFrame implements ItemListener
{
JToggleButton jc1,jc2,jc3,jc4;
public SerializeToggleButton()
{
setTitle("ToggleButton Serialized.");
setSize(400,400);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);

jc1=new JToggleButton("Apples");
jc2=new JToggleButton("Mangoes");
jc3=new JToggleButton("Oranges");
jc4=new JToggleButton("Bananas");

try
{

FileInputStream fin=new FileInputStream("ch.dat");
ObjectInputStream oin=new ObjectInputStream(fin);

ChData ch=(ChData)oin.readObject();
jc1.setSelected(ch.apples);
jc2.setSelected(ch.mangoes);
jc3.setSelected(ch.oranges);
jc4.setSelected(ch.bananas);

}catch(Exception e){
// Exception is throwed for first time since file is not found.
}

jc1.addItemListener(this);
jc2.addItemListener(this);
jc3.addItemListener(this);
jc4.addItemListener(this);

add(jc1);
add(jc2);
add(jc3);
add(jc4);
}
public void itemStateChanged(ItemEvent ie)
{
try
{

FileOutputStream fout=new FileOutputStream("ch.dat");
ObjectOutputStream out=new ObjectOutputStream(fout);

ChData ch=new ChData();
ch.apples=jc1.isSelected();
ch.mangoes=jc2.isSelected();
ch.oranges=jc3.isSelected();
ch.bananas=jc4.isSelected();

out.writeObject(ch);

out.close();
fout.close();
}catch(Exception e){}
}
public static void main(String args[])
{
new SerializeToggleButton();
}

                  class ChData implements Serializable
                  {
                  boolean apples,mangoes,oranges,bananas;
                  }

}


Posted by at on

Tags: Serialization on Swing,