Take the 2-minute tour ×

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

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 ) {


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

What am I doing wrong?

public void

share|improve this question

1 Answer 1

up vote 5 down vote accepted

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:

share|improve this answer
oh thanks..and you are right: I don't have to pass JTable around. –  Heisenbug Oct 1 '11 at 0:52
+1, for changing the model instead of changing the table. –  camickr Oct 1 '11 at 1:13
changing the model if the best solution. Anyway in my case that's not possible because I'm working with a class extending JTable. –  Heisenbug Oct 1 '11 at 13:13

Your Answer


