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!
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).
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.
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
there aren't some problem with that, here is How to Use Tables with nice example, tons of examples here and here
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.
精彩评论