SergSam
SergSam

Reputation: 365

Generic Class for JTable

i got a task which iam not sure of how to solve.

I have to fill a JTable with rows i get from a .txt document. The problem is that there are multiple .txt documents which have more or less rows and columns for the JTable.

example: inside the cars.txt:

id;hp;price;quantity
1;100;7000;5
4;120;20000;2
7;300;80000;3

inside the bikes.txt

id;price;quantity;color;year
3;80;20;red;2010
5;200;40;green;2011
12;150;10;blue;2007

So, when a .txt is chosen a JDialog will pop up with a JTable inside, where the data will be shown. I thought that i could maybe create a "class Anything" where i have a instance variable String[][] which i can define the sizes by reading the .txt and after saving the data in one array i can count how many rows and how many columns it has, with the cars.txt example it would be: String[4][3]

Is that a good way to work with or is there a better way to do it?

Thanks for the help :D

Upvotes: 0

Views: 516

Answers (2)

trashgod
trashgod

Reputation: 205885

As shown in How to Use Tables: Creating a Table Model, you can extend AbstractTableModel to manage models of arbitrary dimensions. Let your model manage a List<List<String>>. Parse the first line of each file into a List<String> that is accessed by your implementations of getColumnCount() and getColumnName(). Parse subsequent lines into one List<String> per row; access the List of such rows in your implementation of getValueAt(). A related example that manages a Map<String, String> is shown here. Although more complex, you can use Class Literals as Runtime-Type Tokens for non-string data; return the token in your implementation of getColumnClass() to get the default render and editor for supported types. Finally, consider one of these file based JDBC drivers for flat files.

Upvotes: 1

Jjoseph
Jjoseph

Reputation: 214

Your question is a bit vague on what you want to do specifically.

Do you want to simply fill the table with all data given? Or do you only want certain columns used? When you choose the text files are you aware of which column names they have (can you hardcode this or not).

A good start would be...

EDITED here's the solution.....

    DefaultTableModel dtm = (DefaultTableModel)yourJTable.getModel(); 
    // This divides your txt file to a string array divided by rows
    string[] RowSplit = yourTxtFileThatYouRead.split("\n"); 

//this assumes that your txt file contains the column headers
    dtm.setColumnHeaders(RowSplit[0].split(";")); 


    //Start the iteration at 1 to skip the column headers
    for (int i = 1; i < RowSplit.length; ++i) {
    dtm.addRow(RowSplit[i].split(//some delimeter //));

dtm.fireTableDataChanged();

The first part sets the column headers and enables for variation within your table column size.

The second part sequentially adds rows.

edited for formatting edited for better answer

Upvotes: 1

Related Questions