Can someone tell me how to modify below program? Program's data is passed by object[][] - instead of that will just give file name which is having data should be print in a table.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class SimpleTableDemo extends JPanel {
private boolean DEBUG = false;
public SimpleTableDemo() {
super(new GridLayout(1,0));
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
Object[][] data = {
{"Kathy", "Smith",
"Snowboarding", new Integer(5), new Boolean(false)},
{"John", "Doe",
"Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black",
"Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White",
"Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown",
"Pool", new Integer(10), new Boolean(false)}
};
final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
if (DEBUG) {
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
printDebugData(table);
}
});
}
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this panel.
add(scrollPane);
}
private void printDebugData(JTable table) {
int numRows = table.getRowCount();
int numCols = table.getColumnCount();
javax.swing.table.TableModel model = table.getModel();
System.out.println("Value of data: ");
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + model.getValueAt(i, j));
}
System.out.println();
}
System.out.println("--------------------------");
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SimpleTableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
SimpleTableDemo newContentPane = new SimpleTableDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
If I understood question correct, you can replace Object[][] data with something like this:
String line;
ArrayList<String[]> toData = new ArrayList<String[]>();
File file = new File("\\file path");
try{
BufferedReader reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
String[] lineElements = line.split(",");
toData.add(lineElements);
}
}catch (Exception ex){
ex.printStackTrace();
System.out.println("File not found");
}
String[][] data = new String[toData.size()][];
int index = 0;
for(String[] a: toData){
data[index]=a;
index++;
}
In this exemple, it will work if data in file is formatted as:
name, surname, sportage, is Vegetarian. However you can change that easily, but remember to also change symbol in brackets in line.split().
EDIT:
I don't fully understand what you want to achieve, however I would do it like this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
public class Project {
private JScrollPane scrollPane;
private JFrame frame;
private JTable table;
public static void main (String[] args){
Project project = new Project();
project.createGUI();
}
public void createGUI(){
frame = new JFrame();
scrollPane = new JScrollPane();
JPanel panel = new JPanel();
JButton open = new JButton("Open");
open.addActionListener(new OpenListener());
JButton submit = new JButton("Submit");
submit.addActionListener(new SubmitListener());
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new CancelListener());
panel.add(open);
panel.add(submit);
panel.add(cancel);
frame.getContentPane().add(BorderLayout.CENTER,scrollPane);
frame.getContentPane().add(BorderLayout.SOUTH,panel);
frame.setSize(500,500);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void createAndDisplayList(String[][] data){
String[] columnNames = {"First Name","Last Name","Sport","# of Years","Vegetarian"};
table = new JTable(data, columnNames);
frame.setVisible(false);
frame.remove(scrollPane);
scrollPane = new JScrollPane(table);
frame.getContentPane().add(BorderLayout.CENTER,scrollPane);
frame.revalidate();
frame.setVisible(true);
}
private class OpenListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
String line;
ArrayList<String[]> toData = new ArrayList<String[]>();
fileChooser.showOpenDialog(frame);
try{
BufferedReader reader = new BufferedReader(new FileReader(fileChooser.getSelectedFile()));
while ((line = reader.readLine()) != null) {
String[] lineElements = line.split(",");
toData.add(lineElements);
}
reader.close();
}catch (Exception ex){
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, "File not found", "Error", JOptionPane.ERROR_MESSAGE);
}
String[][] data = new String[toData.size()][];
int index = 0;
for(String[] a: toData){
data[index]=a;
index++;
}
createAndDisplayList(data);
}
}
private class CancelListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
frame.remove(scrollPane);
scrollPane = new JScrollPane();
frame.getContentPane().add(BorderLayout.CENTER,scrollPane);
frame.revalidate();
frame.setVisible(true);
}
}
private class SubmitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.showSaveDialog(frame);
try{
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile()));
for(int i = 0; i<table.getRowCount(); i++){
for(int j = 0; j<table.getColumnCount(); j++){
System.out.println(i + "," + table.getRowCount());
bufferedWriter.write(table.getValueAt(i, j).toString() + ",");
}
bufferedWriter.newLine();
}
bufferedWriter.close();
}catch (IOException ex){
ex.printStackTrace();
JOptionPane.showMessageDialog(frame,"File not found","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}
However be aware it is a primitive and amateur written code, but it works to some extent. You can open, change content and save file(submit), but you cannot add rows in table, you need to do it in .txt file (but you cannot leave any empty space at the end of file).
Anyway, I hope you will find something usufull here.
Related
The code below takes data from a text file delimited by "|" and displays it in a JTable. When I run it on the JFrame itself it does work. However I cannot figure out how to move it to another class for itself and make it become a method such as public void viewUser(){}, then call it from the frame on click of a button.
public void viewUser(){
File file = new File("user.dat");
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
Object[] lines = br.lines().toArray();
for (Object line : lines) {
String[] row = line.toString().split("\\|");
model.addRow(row);
}
} catch (IOException ex) {
Logger.getLogger(UserManagement.class.getName()).log(Level.SEVERE, null, ex);
}
You are getting this wrong conceptually: a model by itself is meaningless. It needs to be connected to a table in order to show its content.
The code you are showing is creating and filling a new table model. Then that model and all the information is thrown away. Reading data into an object is pointless, when that object isn't made available for further usage!
You might simply change the return type from void to DefaultTableModel and return the model object in the end. And then you can use that pre-filled model for any JTable!
Run this mcve and see if it mocks what you want to do:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TablePane extends JPanel {
private final JTable table;
public TablePane() {
super(new GridLayout(1,0));
String[] columnNames = {"Name", "Age" };
Object[][] data = {
{"Kathy", new Integer(35)},
{"John", new Integer(63)},
{"Sue", new Integer(28)},
{"Joe", new Integer(70)}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
table.setPreferredScrollableViewportSize(new Dimension(300, 100));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
void refresh() {
new Updater(table).getNewData();
}
private static void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TablePane tablePane = new TablePane();
frame.add(tablePane);
JButton button = new JButton("Change data");
button.addActionListener(e -> tablePane.refresh());
frame.add(button, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
class Updater {
private DefaultTableModel model;
Object[][] testData = {
{"Bon", new Integer(15)},
{"Anna", new Integer(31)},
{"Dan", new Integer(82)},
{"Jane", new Integer(20)},
};
public Updater(JTable table) {
model = (DefaultTableModel)table.getModel();
}
void getNewData(){
//if you want to clear data : model.getDataVector().clear();
for (Object[] row : testData) {
model.addRow(row);
}
}
}
As commented by Andrew Thomson mcve with hard coded data is essential.
I have created a program where I can input data in JTextField and on hitting save button I use a JFileChooser to save the data in a .txt file where each JTextField is in a new line. I also created a button that pops up a JFileChooser to browse for that file and populate its corresponding cells.
I am new to GUIs, the code I wrote is not working. I tried different variations and cannot seem to get it. Can someone point me in the right direction please.
The input is
john
Doe
st. Jude
100
Here is the code
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import java.util.Scanner
import java.util.Vector;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
import java.io.*;
//import javax.swing.filechooser;
import javax.swing.filechooser.FileFilter;
public class Charity
{
#SuppressWarnings("deprecation")
public static void main(String[] args)
{
JFrame frame = new JFrame("Learning Team Charity Program");
Container cp = frame.getContentPane();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Charities
final String[] charityArray = {"St.Jude", "CHOC", "Cancer Research", "AIDs Foundation", "Crohns Foundation"};
final JComboBox selector = new JComboBox(charityArray);
JPanel first = new JPanel();
first.setLayout(new FlowLayout());
first.add(selector);
// User input JLabels and JTextFields
JLabel nameLabel = new JLabel("First Name: ");
final JTextField name = new JTextField();
JLabel lastLabel = new JLabel("Last Name: ");
final JTextField lastname = new JTextField();
JLabel donationAmount = new JLabel("Donation Amount: ");
final JTextField donation = new JTextField();
JPanel second = new JPanel();
second.setLayout(new GridLayout(4,2));
second.add(nameLabel); second.add(name);
second.add(lastLabel); second.add(lastname);
second.add(donationAmount); second.add(donation);
// Donate & Exit Buttons
JButton donateButton = new JButton("Donate");
JButton saveButton = new JButton("Save");
JButton exitButton = new JButton("Exit");
JButton openButton= new JButton("Open File");
JPanel third = new JPanel();
third.setLayout(new FlowLayout());
third.add(donateButton);
third.add(saveButton);
third.add(openButton);
third.add(exitButton);
// JTable display
final DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("First Name");
model.addColumn("Last Name");
model.addColumn("Charity");
model.addColumn("Donation");
table.setShowHorizontalLines(true);
table.setRowSelectionAllowed(true);
table.setColumnSelectionAllowed(true);
JScrollPane scrollPane = JTable.createScrollPaneForTable(table);
JPanel fourth = new JPanel();
fourth.setLayout(new BorderLayout());
fourth.add(scrollPane, BorderLayout.CENTER);
// Button Events
exitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(1);
}
});
openButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
JFileChooser openChooser = new JFileChooser();
int openStatus = openChooser.showOpenDialog(null);
if(openStatus == JFileChooser.APPROVE_OPTION){
try{
File myFile = openChooser.getSelectedFile();
BufferedReader br = new BufferedReader(new FileReader(myFile));
String line;
while((line = br.readLine())!= null){
model.addRow(line.split(","));
}//end while
br.close();
}//end try
catch(Exception e2){
JOptionPane.showMessageDialog(null, "Buffer Reader Error");
}//end catch
}
}
private void setValueAt(String line, int row, int col) {
// TODO Auto-generated method stub
}
});
saveButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
JFileChooser fileChooser = new JFileChooser();
int status = fileChooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION)
{
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Text", ".txt", "txt"));
//fileChooser.setFileFilter(new FileFilter("txt"));
PrintWriter output;
try {
File file = fileChooser.getSelectedFile();
output = new PrintWriter(file +".txt");
for(int row = 0; row<table.getRowCount(); row++){
for(int col = 0; col<table.getColumnCount();col++){
output.println(table.getValueAt(row, col).toString());
}
output.println();
}
output.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
donateButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
DecimalFormat df = new DecimalFormat("##,###.00");
try
{
Object[] rows = new Object[]{name.getText(), lastname.getText(), selector.getSelectedItem(),
donation.getText()};
model.addRow(rows);
name.setText("");
lastname.setText("");
donation.setText("");
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Enter a Dollar Amount", "Alert", JOptionPane.ERROR_MESSAGE);
return;
}
}
});
// Frame Settings
frame.setSize(470,300);
//frame.setLocation(300,200);
cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS));
cp.add(first);
cp.add(second);
cp.add(third);
cp.add(fourth);
frame.setVisible(true);
}
}
I understand I have to pass a value in the parenthesis after the addRow.
People don't know what that means because the code you posted here doesn't have an addRow(...) method.
I see you posted a second question 2 hours later: https://stackoverflow.com/questions/30951407/how-to-properly-read-a-txt-file-into-a-a-row-of-a-jtable.
Keep all the comments in one place so people understand what is going on.
Also, posting a few random lines of code doesn't help us because we don't know the context of how the code is used. For example, I have no idea what how you created the "model" variable. I don't know if you ever added the model to the table.
Post a proper SSCCE when posting a question so we have the necessary information. The file chooser is irrelevant to the problem because we don't have access to your real file. So instead you need to post hard coded data. An easy way to do this is to use a StringReader.
Here is a working example that shows how to read/parse/load a file into a JTable:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.io.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
try
{
DefaultTableModel model = new DefaultTableModel(0, 4);
String data = "1 2 3 4\na b c d\none two three four";
BufferedReader br = new BufferedReader( new StringReader( data ) );
String line;
while ((line = br.readLine()) != null)
{
String[] split = line.split(" ");
model.addRow( split );
}
JTable table = new JTable(model);
add( new JScrollPane(table) );
}
catch (IOException e) { System.out.println(e); }
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
All you need to do is change the code to use a FileReader instead of the StringReader.
I figured it out. Thanks for all those that tried to help.
openButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
JFileChooser openChooser = new JFileChooser();
int openStatus = openChooser.showOpenDialog(null);
if(openStatus == JFileChooser.APPROVE_OPTION){
try{
File myFile = openChooser.getSelectedFile();
//BufferedReader br = new BufferedReader(new FileReader(myFile));
Scanner br = new Scanner(new FileReader(myFile));
String line;
while((line = br.nextLine())!= null){
Object[] myRow = new Object[]{line,br.nextLine(), br.nextLine(), br.nextLine()};
model.addRow(myRow);
// line = br.readLine();
if(br.nextLine()== " "){
line=br.nextLine();
}
}//end while
br.close();
}//end try
catch(Exception e2){
return;
}//end catch
}
}
});
I am trying to populate a table from a text file using vectors. Should I be creating a new vector for each row? Is there anything else that appears wrong with my code? I'm not quite sure what to do from here.
public class myJTable {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vector<String> v = new Vector<String>();
Vector<Vector<String>> rowData = new Vector<Vector<String>>();
//String splitting
try {
FileReader fReader = new FileReader("lakedata.txt");
BufferedReader inFile = new BufferedReader(fReader);
String input;
String[] temp;
while((input=inFile.readLine())!=null) {
temp = input.split(",",3);
for(int i=0; i<temp.length; i++) {
v.addElement(temp[i]);
System.out.println(temp[i]);
}
System.out.println(v);
rowData.addElement(v);
}
inFile.close();
}
catch(Exception e) {
System.out.println("ERROR");
}
Vector<String> columnNames = new Vector<String>();
columnNames.addElement("Depth");
columnNames.addElement("Temperature");
columnNames.addElement("D.O.");
JTable table = new JTable(rowData, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(500,300);
frame.setVisible(true);
}
}
Instead of using Vector, you can create a DefaultTableModel then set it as the model of the table, then invoke its addRow method to directly put the read line result to the table. The table will automatically update itself when data to a table is added.
I took the liberty to revise your code into a cleaner one.
import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.io.FileReader;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class TablePopulation {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
JTable table = new JTable();
JScrollPane scrollPane = new JScrollPane(table);
/* Set the table data to null first since
* we will fetch data from file line by line
* -------------------------------------- */
DefaultTableModel model = new DefaultTableModel(null, new String[]{"Depth","Temperature","D.O."});
table.setModel(model);
/* String splitting
* ---------------- */
try {
FileReader fReader = new FileReader("file.txt");
BufferedReader inFile = new BufferedReader(fReader);
String input = inFile.readLine();
while(input !=null) {
String[] temp = input.split(",");
model.addRow(temp);
input = inFile.readLine();
}
inFile.close();
}catch(Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(500,300);
frame.setVisible(true);
}
});
}
}
Also, atleast put e.printStackTrace() (since you're not using any logging framework) in the catch block to see the stack trace of what's going on in case some error has been caught.
Below are the example of codes to display the table but how is it to be done when I want to retrieve the information from the user input from other file?
package components;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class SimpleTableDemo extends JPanel {
private boolean DEBUG = false;
public SimpleTableDemo() {
super(new GridLayout(1,0));
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
Rather than manually inputting each information, how can I retrieve the information from other file?
**Object[][] data = {
{"Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false)},
{"John", "Doe","Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black","Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White","Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown","Pool", new Integer(10), new Boolean(false)} };**
final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
if (DEBUG) {
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
printDebugData(table);
}
});
}
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this panel.
add(scrollPane);
}
private void printDebugData(JTable table) {
int numRows = table.getRowCount();
int numCols = table.getColumnCount();
javax.swing.table.TableModel model = table.getModel();
System.out.println("Value of data: ");
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + model.getValueAt(i, j));
}
System.out.println();
}
System.out.println("--------------------------");
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SimpleTableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
SimpleTableDemo newContentPane = new SimpleTableDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You can write the information about users in a file in csv(comma separated values) format and then use OpenCSV to parse that file and construct the matrix or array that you use for display.
So, basically your question is how to retrieve the contents of a file into an Object[][]?
Assuming that your file has lines and the lines look like:
Kathy,Smith,Snowboarding,5,false
John,Doe,Rowing,3,true
that is a CSV file. To read CSV files, your best bet is to download openCSV
However, if you still want to do it yourself and your data is in a file called "data.csv" I would use a Scanner. Also, assuming you do not know about ArrayLists and stuff like that, here's some code that can get you going.
Scanner s = new Scanner(new File("data.csv"));
int count = 0;
while (s.hasNext())
count++;
// now count has the number of lines in the file and you know
// there are 5 attributes.
Object[][] data = new Object[count][5]
Scanner s1 = new Scanner(new File("data.csv"));
count = 0;
while(s1.hasNext()){
String[] fields = s1.next().split(",");
data[count][0] = field[0];
data[count][1] = fields[1];
data[count][2] = fields[2];
data[count][3] = new Integer(Integer.parseInt(fields[3]));
data[count][4] = new Boolean(fields[4].equals("true");
count++;
}
Lastly, beware of an indexOutOfBounds error that may happen if you leave empty lines at the beginning, between lines or one line blank at the end (i.e. the last line of your file is empty)
I have created a simple GUI which includes a JTable. This table may be saved & loaded via the appropriate Object Stream.
At this point the Save function is working as intended, and I can see the table object is stored in a file when looking in the save directory.
However, when I try to load the table from the file, the GUI never displays the loaded table. The actionlistener function is called, as I have a system.out "Data loaded", but the table never displays updated data.
I have tried to call repaint(), but to no avail. To anyone who can shed some light on what I may be doing wrong, I would be most grateful.
A look at some code
import javax.swing.*;
import java.awt.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.imageio.*;
import java.io.*;
import java.awt.image.BufferedImage;
import java.util.*;
import javax.swing.table.*;
import java.awt.event.*;
public class Save3 extends JFrame implements ActionListener{
public int PADDING = 10;
public JMenuItem menuNew;
public JMenuItem menuOpen;
public JMenuItem menuSave;
public JMenuItem menuExit;
public JPanel container;
public DefaultTableModel model;
public JScrollPane scrollPane;
public JTable table;
public FileInputStream fis;
public ObjectInputStream in;
public FileOutputStream fos;
public ObjectOutputStream out;
public String filename;
public Save3(){
fis = null;
in = null;
fos = null;
out = null;
filename = "test.ref";
initGUI();
}
public void initGUI(){
setTitle("WIM Reference Data Comparison Tool");
setSize(500, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// Menu Bar and Menu Items setup
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem;
menuBar = new JMenuBar();
menu = new JMenu("Menu");
menuBar.add(menu);
menuNew = new JMenuItem("New");
menuOpen = new JMenuItem("Open");
menuSave = new JMenuItem("Save");
menuExit = new JMenuItem("Exit");
menuNew.addActionListener(this);
menuOpen.addActionListener(this);
menuSave.addActionListener(this);
menuExit.addActionListener(this);
menu.add(menuNew);
menu.add(menuOpen);
menu.add(menuSave);
menu.add(menuExit);
setJMenuBar(menuBar);
container = new JPanel(new BorderLayout());
String[] columnNames = {"", "MotorBike", " Car"};
Object[][] data = { {"Vehicle Summary", new Integer(100), new Integer(200)}, // Header 1: Green
{"Axle Numbers", new Integer(100), new Integer(200)},
{"Axle Code", new Integer(100), new Integer(200)},
{"Axle Distances (cm)", new Integer(100), new Integer(200)},
{"Vehicle Speed (km/h)", new Integer(100), new Integer(200)},
{"Gross Weight", new Integer(100), new Integer(200)},
{"Axle Weight 1", new Integer(100), new Integer(200)},
{"Axle Weight 2", new Integer(100), new Integer(200)},
};
model = new DefaultTableModel(data, columnNames);
table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
scrollPane = new JScrollPane(table);
container.add(scrollPane, BorderLayout.CENTER);
add(container);
}
public void setPanel(JTable table){
scrollPane.remove(table);
container.remove(scrollPane);
scrollPane = new JScrollPane(table);
container.add(scrollPane, BorderLayout.CENTER);
repaint();
}
public void actionPerformed(ActionEvent e){
System.out.println("Clicked item!");
// NEW
if(e.getSource() == menuNew){
System.out.println("New File");
}
// SAVE
if(e.getSource() == menuSave){
System.out.println("Save!");
try{
model.fireTableDataChanged();
table = new JTable(model);
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(table);
}catch(IOException e3){
e3.printStackTrace();
}
}
if(e.getSource() == menuOpen){
System.out.println("Open!");
JTable table = new JTable();
try{
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
table = new JTable();
table = (JTable) in.readObject();
in.close();
setPanel(table);
System.out.println("data loaded");
}catch(IOException e1){
e1.printStackTrace();
}catch(ClassNotFoundException e2){
e2.printStackTrace();
}
}
if(e.getSource() == menuExit){
System.out.println("Exit!");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
Save3 ex = new Save3();
ex.setVisible(true);
}
});
}
}
Your new table is not added anywhere, so it will not show up. Try something like this:
public void actionPerformed(ActionEvent e){
JTable oldTable = table;
// your stuff, loading the table from file
thePanelHoldingYourTable.remove(oldTable);
thePanelHoldingYourTable.add(table);
// if there are other components in that panel, make sure, your table is in the right spot
// maybe refresh your layout by using invalidate()
}
EDIT: Ok, serializing the table is not really advised, it is better to only save the table model. Here is your edited SSCCE (thanks to kleopatra for the help):
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class Save3 extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
public int PADDING = 10;
public JMenuItem menuNew;
public JMenuItem menuOpen;
public JMenuItem menuSave;
public JMenuItem menuExit;
public JPanel container;
public DefaultTableModel model;
public JScrollPane scrollPane;
public JTable table;
public FileInputStream fis;
public ObjectInputStream in;
public FileOutputStream fos;
public ObjectOutputStream out;
public String filename;
String[] columnNames = {"", "MotorBike", " Car"};
Object[][] data = { {"Vehicle Summary", new Integer(100), new Integer(200)}, // Header 1: Green
{"Axle Numbers", new Integer(100), new Integer(200)}, {"Axle Code", new Integer(100), new Integer(200)}, {"Axle Distances (cm)", new Integer(100), new Integer(200)}, {"Vehicle Speed (km/h)", new Integer(100), new Integer(200)}, {"Gross Weight", new Integer(100), new Integer(200)}, {"Axle Weight 1", new Integer(100), new Integer(200)}, {"Axle Weight 2", new Integer(100), new Integer(200)},};
public Save3() {
fis = null;
in = null;
fos = null;
out = null;
filename = "test.ref";
initGUI();
}
public void initGUI() {
setTitle("WIM Reference Data Comparison Tool");
setSize(500, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// Menu Bar and Menu Items setup
JMenuBar menuBar;
JMenu menu;
menuBar = new JMenuBar();
menu = new JMenu("Menu");
menuBar.add(menu);
menuNew = new JMenuItem("New");
menuOpen = new JMenuItem("Open");
menuSave = new JMenuItem("Save");
menuExit = new JMenuItem("Exit");
menuNew.addActionListener(this);
menuOpen.addActionListener(this);
menuSave.addActionListener(this);
menuExit.addActionListener(this);
menu.add(menuNew);
menu.add(menuOpen);
menu.add(menuSave);
menu.add(menuExit);
setJMenuBar(menuBar);
container = new JPanel(new BorderLayout());
model = new DefaultTableModel(data, columnNames);
table = new JTable();
table.setModel(model);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
scrollPane = new JScrollPane(table);
container.add(scrollPane, BorderLayout.CENTER);
add(container);
}
public void setModel(DefaultTableModel writeModel) {
table.setModel(writeModel);
}
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked item!");
if (e.getSource() == menuNew) {
System.out.println("New File");
} else if (e.getSource() == menuSave) {
System.out.println("Save!");
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
table.clearSelection();
table.setModel(new DefaultTableModel());
out.writeObject(model);
table.setModel(model);
} catch (IOException e3) {
e3.printStackTrace();
} finally {
try {
out.close();
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
} else if (e.getSource() == menuOpen) {
System.out.println("Open!");
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
DefaultTableModel modelRead = (DefaultTableModel) in.readObject();
setModel(modelRead);
System.out.println("data loaded");
in.close();
fis.close();
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e2) {
e2.printStackTrace();
}
} else if (e.getSource() == menuExit) {
System.out.println("Exit!");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Save3 ex = new Save3();
ex.setVisible(true);
}
});
}
}
Please notice that I use the following three lines to serialize the model:
table.setModel(new DefaultTableModel());
out.writeObject(model);
table.setModel(model);
So the model is detached from the table while serializing. Unfortunately the model tries to serialize its listeners as well (which fails). That's why this step is neccessary. Once saved, the model can be applied to the table again.
JTable and its XxxTableModel is based on Vector or Object[]
have to load data from FileIO to the XxxTableModel in structure as is Vector or Object[]
all updates to the XxxTableModel must be done on EventDispatchThread, otherwise any changes are visible on the screen
In the actionPerformed code, the imported table (this is a new instance) isn't added into a container.