breadkun breadkun - 2 years ago 81
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(){
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
tablepanel.add(scrollPane, BorderLayout.SOUTH);


And the button I use to add the data

class AddHandler implements ActionListener {

public void actionPerformed(ActionEvent e) {

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};



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

private DefaultTableModel model = new DefaultTableModel();

Any suggestions are appreciated

Answer Source

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().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download