El-Hadj Chikhaoui
El-Hadj Chikhaoui

Reputation: 69

Populating a jTable using txt file

Thanks for reading. I have a problem, I can't seem to find a way to populate a jTable using data from a .txt file.

I'm using Netbeans' GUI builder. Methods like insertRow, addRow...etc are not acknowledged. After some research on Google, I've tried using models but that doesn't seem to work either. Or maybe I didn't do it right.

Finally, I have found something :

public class InsertFileDataToJTable extends AbstractTableModel {
Vector data;
Vector columns;

public InsertFileDataToJTable() {
        String line;
        data = new Vector();
        columns = new Vector();
        try {
                FileInputStream fis = new FileInputStream("monfichier.txt");
                BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
                while (st1.hasMoreTokens())
                        columns.addElement(st1.nextToken());
                while ((line = br.readLine()) != null) {
                        StringTokenizer st2 = new StringTokenizer(line, " ");
                        while (st2.hasMoreTokens())
                                data.addElement(st2.nextToken());
                }
                br.close();
        } catch (Exception e) {
                e.printStackTrace();
        }
}

public int getRowCount() {
        return data.size() / getColumnCount();
}

public int getColumnCount() {
        return columns.size();
}

public Object getValueAt(int rowIndex, int columnIndex) {
        return (String) data.elementAt((rowIndex * getColumnCount())
                        + columnIndex);
}

That's what I'm getting : i.imgur.com/7xqUD.jpg

The only thing bothering me now is the columns' names, how do I change them ?

Upvotes: 1

Views: 1612

Answers (1)

Jay
Jay

Reputation: 27492

Include a getColumnName function ...

public String getColumnName(int col)

It will be called passing in the column number. Based on this return a column name. Either make an array of column names and "return columnName[col]", have a case statement based on col, etc.

See the Javadocs for AbstractTableModel for more details on everything you can do.

Upvotes: 2

Related Questions