Dynamically adding JTables to JScrollPane

430 views Asked by At

Similar to this question: Dynamically adding JTable to JScrollPane

I am trying to add a JTable every time that the user clicks a button. Firstly my problem was the same as in that question; nothing would display, once I used the getViewport I could get it to display, except now I can't see any of my buttons.

I should have buttons above and below each JTable. (they are also in the scroll pane. I'm guessing that they are removed because getViewport will get the entire scroll pane (that I can see) and put my JTable over that).

Why is it necessary to getViewport()? I can easily do what I want if I simply change the JTable for a JButton for example.

Also if I move the button to outside the scrollpane then clicking to add another JTable looks like it does nothing. I'm assuming that it just keeps putting another JTable over the previous one.

So to sum up: how I can use buttons within a JScrollPane to add JTables to the same JScrollPane?

Thank you for your help.

Edit: Action that happens when user clicks the button: The button works correctly, being added on each click but no tables ever appear.

public void actionPerformed(ActionEvent e)
    {
        JTableList.add(new JTable(getModel()));
        panelClass.this.panel.add(JTableList.get(JTableList.size()-1));
        panelClass.this.panel.add(new JButton("test"));

        panelClass.this.validate();
        panelClass.this.repaint();
    }
1

There are 1 answers

5
Aequitas On

It seems that a JTable must be in a scroll pane by itself.

So to solve the problem, instead of adding the JTable to the panel, first add it to a new JScrollPane and then add that scroll pane to the panel. Validate and repaint and it will work.

See Code snippet:

public void actionPerformed(ActionEvent e)
{
    JTableList.add(new JTable(getModel()));
    JScrollPane tableContainer = new JScrollPane(JTableList.get(JTableList.size()-1));
    panelClass.this.panel.add(tableContainer);
    panelClass.this.panel.add(new JButton("test"));

    panelClass.this.validate();
    panelClass.this.repaint();
}

Only problem is that the list of tables won't scroll if the mouse is over any of the tables. See here: Why JScrollPane does not react to mouse wheel events? for solving this issue.