vijay
vijay

Reputation: 1139

From file to JTable

I had a file with 3 columns of data and I would like to pass them into the JTable. Could any one suggest how can I do this?

Upvotes: 1

Views: 844

Answers (2)

Waleed Almadanat
Waleed Almadanat

Reputation: 1037

In Swing you need to deal with Model objects in order to manage several UI components such as JTree, JTable and JList.

You can use the Default implementation provided to you out of the box, or extend either it or implement the Model interface.

In the case of JTables the default Model class is called DefaultTableModel and the interface is called TableModel.

Now back to your problem, you'll have to read the file, then obtain a model instance so that you can pass the data to it in order for it to be shown on the table. Don't forget to associate your new table model with the table.

Here's a guide to help you more.

Upvotes: 0

makciook
makciook

Reputation: 1555

The data in java is not stored in a table, but in a table's model - e.g. DefaultTableModel to operate on it easily. JTable automatically "sees" the data changes in a model.

DefaultListModel myModel = new DefaultListModel();
myModel.setColumnIdentifiers([column names]);

In this case, if your columns are delimitted in some unique way, the easiest way to read the data is using java Scanner:

Scanner s = new Scanner(new FileInputStream(new File(filePath)));
s.useDelimiter(delim);
while (s.next()) {
   System.out.println(s.nextInt());
   // or put data directly into the table:
   myModel.addRow([data from s]);
}

Where delim is the sign dividing your file into columns. You'll also finally need to assign the created model to the existing JTable:

myTable.setModel(myModel);

Upvotes: 2

Related Questions