I'm unsure about how to assign values to a JTable without directly assigning values to the initial 2D Array, i.e. String data[][]= new String[5][5]{"abc","def","ghi","jkl","mno"};
If I declared my array of 2D String, followed by defaultTableModel
, is there any way I can assign the values of abc, def, ghi, jkl, mno to the Array/JTable without doing it as above in a separate method maybe?
Update
JPanel invoiceViewPanel= new JPanel(null);
String data[][]= new String[4][10];
String columnHeaders[]={"Invoice ID","Invoice Name","Customer", "Complete?"};
DefaultTableModel model = new DefaultTableModel(data, columnHeaders) {
boolean[] Editable= new boolean[]{
false, false, false, true
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return editableCells[columnIndex];
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
return columnClass[columnIndex];
}
};
JTable table=new JTable(model);
JScrollPane tableContainer=new JScrollPane(table);
final Class[] columnClass = new Class[]
{
Integer.class, String.class, String.class, Boolean.class
};
public void launch()
{
this.setLayout(new FlowLayout());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(invoiceViewPanel);
invoiceViewPanel.add(tableContainer);
this.add(tableContainer);
this.setTitle("Invoices");
this.setSize(500,600);
this.setVisible(true);
this.setResizable(false);
}
This is a basic version of my code. It is just the initialising of my JTable.
I have a text file of the format
001/ TV Purchase/ John Smith/ true
002/ Refrigerator Purchase/ Jean Smith/ false
All Swing components work with a Model
. To update the component you update the model.
So in the case of a JTable you can create an "empty" model for your table by using:
String[] columnNames = { "Column1", "Column2", ... };
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
JTable table = new JTable( model );
Now when you want to add data to the model you can use:
Object[] row = {"data1", data2", ... };
model.addRow( row );
Read the DefaultTableModel
API for more methods to change the data. You can also add a Vector
of data to the model.