Jonas
Jonas

Reputation: 1234

Adding an Array to JTable in Java

Since you create the JTable with an matrix for data and array for the columns I figured there should be a way to after created the JTable adding an array (row). Or how is it meant to add a row with Strings?

Thanks!

Upvotes: 2

Views: 20850

Answers (5)

Dame Lyngdoh
Dame Lyngdoh

Reputation: 352

You can also create a class of your own which extends AbstractTableModel and implement the abstract methods. This class can also contain the array (or whichever collection or data structure you use) and the abstract methods which you implement will use this array, methods such as getValueAt and setValueAt. Then you can create a new instance of this class and set the table model of the table to this object. Adding rows to this table is now possible by adding entries/elements to the array.

Upvotes: 0

mKorbel
mKorbel

Reputation: 109815

there aren't some problem with that, here is How to Use Tables with nice example, tons of examples here and here

Upvotes: 1

Pratik
Pratik

Reputation: 30855

you can add/insert row in JTable like this way

table.getModel().insertRow(table.getRowCount(),new Object[]{"hello","50"});

here is the tutorial link

http://www.roseindia.net/java/example/java/swing/InsertRows.shtml

Upvotes: 1

You cannot add to a JTable directly, you have to get the underlying TableModel. You get this by calling JTable.getModel(). TableModel is an interface, in a standard JTable it's implementation is DefaultTableModel. So you have to cast the underlying TableModel to a DefaultTableModel, and then you can apply DefaultTableModel.addRow( Object[] ). (You do, of course, check that the cast is safe and all that).

Upvotes: 3

aioobe
aioobe

Reputation: 420951

To change the data displayed by the JTable, you need to go through the TableModel.

Have a look at the JTable.getModel() method and the methods in the TableModel interface.

Upvotes: 1

Related Questions