3
votes

I have a JPanel that contains a JScrollPane that contains a JTable. Inside my panel constructor it's created this way:

    //inside MyPanel extends JPanel class constructor
public void MyPanel(){
    TitledBorder border = BorderFactory.createTitledBorder("title");
    this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    this.scrollTable = new JScrollPane(table);
    this.scrollTable.setBorder(border);
}

Now, the user should be able to load another table into application so I need to remove the previous one from the scrollpane and add a new one. I've tried the following :

public void setNewTable(JTable t ) {
    this.scrollTable.removeAll();
    this.scrollTable.add(t);
    this.scrollTable.validate();

}

The previous table is removed, but nothing happear inside the JScrollPane now.

What am I doing wrong?

public void

1

1 Answers

5
votes

You can't just add to JScrollPane, since it consists of other internal components.

From the JavaDocs:

enter image description here

By calling scrollPane.removeAll() you essentially, remove the header, view, and scrollbars, and add a component that the scrollpane doesn't understand.

First of all, you generally shouldn't pass around tables in that manner. It would be much better to instead pass in a TableModel, and change the model on the table via JTable.setModel().

That said, if you absolutely want to pass in a table, you need to set the view on the viewport in the scrollpane:

scrollPane.getViewport().setView(table)