Jay Kandy
Posts: 77
Nickname: jay
Registered: Mar, 2002
|
|
Re: JTable - Save preferences
|
Posted: Apr 19, 2002 3:16 PM
|
|
Nice question Wally. One way is to serialize the table and read back without the traditional "saving properties" hassels. But if you have a big table, or have objects that can not be serialized (for some reason!) you should considering switching to another means. I am thinking- implement TableColumnModel and serialize it. I leave that for your experiments. Heres a simple app that saves the order of columns by serializing the table.
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.table.AbstractTableModel;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class TableEx extends JFrame
{
public TableEx(JTable aJTable)
{
final JTable table;
if(aJTable == null)
{
table = new JTable(new MyTableModel());
}
else
{
table = aJTable;
}
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
setSize(200, 200);
show();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we)
{
try /* Serialize the table before exiting the application */
{
ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("table.ser") );
out.writeObject(table);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.exit(0);
}
});
}
public static void main(String[] args)
{
try
{
/* When starting the app, check if we have a serialized object */
ObjectInputStream in = new ObjectInputStream( new FileInputStream("table.ser") );
System.out.println("Using user preferences...");
new TableEx( (JTable)in.readObject() );
}
catch(FileNotFoundException fnfe)
{
System.out.println("Using defaults..."); /* No, we dont. */
new TableEx(null);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
class MyTableModel extends AbstractTableModel
{
Object[][] data = {
{"Calories", "130"},
{"Total Fat", "0%"},
{"Sodium", "1%"},
{"Total Carbs", "12%"},
};
String[] columns = {"Item", "Amount per serving"};
public int getColumnCount()
{ return 2; }
public int getRowCount()
{ return 4; }
public String getColumnName(int c)
{ return columns[c]; }
public Object getValueAt(int rowIndex, int colIndex)
{ return data[rowIndex][colIndex]; }
public boolean isCellEditable(int rowIndex, int colIndex)
{ return false; }
}
}
|
|