Store JList Selection using Serialization

Store JList Selection


It's my pleasure again, all of the below are completed.


Now, let us see the JList, storing multiple selected items and selecting them back for the users. I usually, at the very first time tried storing a single selected item, but what about when users select multiple items in a list. Then i've modified the program, if your JList allows only single selection, don't worry this code works, only one thing you need to do is to call setSelectionMode(0), if you have decided to work with items rather than indices, then i've kept them in comments. You can use them.


Fire Now!


Serialized JList Screenshot

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.util.*;
import java.io.*;

class SerializeJList extends JFrame
{
JList<String> jl;
JButton jb;
public SerializeJList()
{
setTitle("Serialize JList");
setLayout(new FlowLayout());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

Vector<String> v=new Vector<String>();
v.add("C");
v.add("C++");
v.add("Java");
v.add("Python");
v.add("Perl");
v.add("Ruby");

jl=new JList<String>(v);
// jl.setSelectionMode(0);
jl.setSelectionForeground(Color.white);
jl.setSelectionBackground(new Color(0,153,255));
jb=new JButton("Set");

try
{
FileInputStream fin=new FileInputStream("li.dat");
ObjectInputStream oin=new ObjectInputStream(fin);

JLData l=(JLData)oin.readObject();

//jl.setSelectedValue(l.selectedItem,true);
jl.setSelectedIndices(l.items);

oin.close();
fin.close();
}catch(Exception e){}

jl.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent le)
{
jb.setEnabled(true);
}
});

jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
try
{
FileOutputStream fout=new FileOutputStream("li.dat");
ObjectOutputStream out=new ObjectOutputStream(fout);

JLData l=new JLData();
//l.selectedItem=jl.getSelectedValue();

l.items=jl.getSelectedIndices();

out.writeObject(l);

out.close();
fout.close();
}catch(Exception e){}

jb.setEnabled(false);
}
});

jl.setPreferredSize(new Dimension(200,200));

JScrollPane js=new JScrollPane(jl);

add(js);
add(jb);

setExtendedState(MAXIMIZED_BOTH);
}
public static void main(String args[])
{
new SerializeJList();
}

class JLData implements Serializable
{
int items[];
        //String selectedItem;
}
}

Explanation


Note: Everything in comments targets for the people who want to work with item values instead of indices and that too only with one item at a time.

v=new Vector<String>(): Create a java.util.Vector object for storing  java.lang.String objects.

v.add(): This method in the java.util.Vector class adds an item to the vector. The type of item to be added is the type which was previously coded at the time of it's creation.

jl=new JList<String>(v): This constructor takes a vector object with the type with which the JList is created. If you can observed, <String> for both java.util.Vector and JList

// jl.setSelectionMode(0): Means single selection, i.e. only 1 item at a time is selectable.

jl.setSelectionForeground(Color.white): Set the text color of each item in JList when selected.

jl.setSelectionBackground(new Color(0,153,255)): Set the background color for each item in JList when selected.

fin=new FileInputStream("li.dat"): Create FileInputStream object pointing li.dat

oin=new ObjectInputStream(fin): Create ObjectInputStream object pointing fin

l=(JLData)oin.readObject(): Read object from the file li.dat and store in l. This method returns java.lang.Object so typecasting is necessary.

//jl.setSelectedValue(l.selectedItem,true): This method takes the item and makes it selected. The true value is to select it.

jl.setSelectedIndices(l.items,true): This method takes an int[] array containing indices (plural of index) that are to be selected. The true sets those indices selected. Here, we're passing the indices of the items that the user had selected previously. For, the first time when the program is executed however, this statement is not executed as li.dat was not found and as a result an exception is thrown and the control jumps to corresponding catch block.

jb.setEnabled(true): When selection is changed, ListSelectionEvent is fired and the corresponding code as usual is written in the method of the corresponding listener (here the listener ListSelectionListener and method in it is valueChanged)

When button is clicked..


fout=new FileOutputStream("li.dat"): Create a FileOutputStream object pointing li.dat

out=new ObjectOutputStream(fout): Create an ObjectOutputStream object pointing fout

l.items=jl.getSelectedIndices(): Get the list of indices of the items that the user has selected on JList and then store that indices (plural of index) array in items which is a variable of type int[]

out.writeObject(l): Write object to the file li.dat. The object l contains the data of indices of selected items by the user.

jb.setEnabled(false): Make the button disabled. If you can observe, in the above there is jb.setEnabled(true) when user selects some other item other than this.

jl.setPreferredSize(new Dimension(200,200)): This method is just to make it fat :). It actually looked thin. This method takes java.awt.Dimension object and this class' constructor takes (int width,int height) respectively.

js=new JScrollPane(jl): Add a scrollpane, if in future items are be added, may be helpful. But here, the purpose is the look. This statement means to add a scroll pane for jl (JList object)

setExtendedState(MAXIMIZED_BOTH): Let the frame widen.


Posted by at on

Tags: Serialization on Swing,