breadkun breadkun - 7 months ago 15
Java Question

JTable won't dynamically add rows

So I've got a jtable which is supposed to add the fields from the Jtextfields to the table, the table exists on the pane as desired (columns names appear and no rows) but when I click to add a new row it adds a blank column instead (and only once)

The method which creates my table

public void createTable(){
model.setColumnIdentifiers(columns);
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
tablepanel.add(scrollPane, BorderLayout.SOUTH);

}


And the button I use to add the data

class AddHandler implements ActionListener {

public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnUpload)
{

String nameRow = txtName.getText();
String surnameRow = txtSurname.getText();
String phoneRow = txtPhone.getText();
String addressRow = txtAddress.getText();
String postcodeRow = txtPostcode.getText();
String emailRow = txtEmail.getText();
Object[] row = {nameRow,surnameRow,phoneRow,addressRow,postcodeRow,emailRow};
model.addRow(row);

}

}
}


I have the default model set as a global variable like this:

private DefaultTableModel model = new DefaultTableModel();


Any suggestions are appreciated

Answer

Your issue might be due to setting the scroll pane's size to 0. You should delete table.setPreferredScrollableViewportSize(table.getPreferredSize()) or set a preferred size of your table by table.setPreferredSize() before you use table.getPreferredSize().

Comments