breadkun
breadkun

Reputation: 13

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

Upvotes: 0

Views: 298

Answers (2)

trashgod
trashgod

Reputation: 205775

As an alternative to invoking setPreferredScrollableViewportSize(), consider overriding the table's implementation of getPreferredScrollableViewportSize() and making the height a multiple of getRowHeight(); a compete example is shown here.

JTable table = new JTable(tableModel) {

    @Override
    public Dimension getPreferredScrollableViewportSize() {
        return new Dimension(200, table.getRowHeight() * N);
    }
};

image

You can learn more about the Scrollable interface in Implementing a Scrolling-Savvy Client.

Upvotes: 1

lkq
lkq

Reputation: 2366

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

Upvotes: 1

Related Questions