0

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

breadkun
  • 13
  • 3
  • 1
    `Any suggestions are appreciated` - Create a [SSCCE](http://sscce.org/) that demonstrates the problem. So you create a frame with a JTable and an "Add Row" button. The add row button will simply add a row of hard coded data to the table. Then once you get that working you get the data dynamically from the text fields on your frame. If you have a problem with the SSCCE then you have code that we can compile and test to see what you are doing. – camickr Apr 23 '16 at 18:28

2 Answers2

1

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

lkq
  • 2,326
  • 1
  • 12
  • 22
1

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.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045