7

I have a table that I want to populate when the user prompts me to do so. Problem is, I can't anticipate how many rows the table will end up having. In the constructor for my panel where the table will be displayed I have

    // add empty scrollPane to JPanel which will later hold table
              scrollPane = new JScrollPane(); 
    add(scrollPane);

This class contains a method that will be called when I want to finally display the table

    public void displayTable(String[] columnNames, String[][] dataValues)
{
    table = new JTable(dataValues, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(300, 80)); 
    table.setFillsViewportHeight(true); 
    scrollPane.add(table);

    this.setVisible(true);
    scrollPane.repaint();

}

Problem is, the table never displays. I just see an outline of where the ScrollPane is with no table inside. Why isn't the table displaying and how can I fix it?

mre
  • 43,520
  • 33
  • 120
  • 170
Matt
  • 295
  • 3
  • 6
  • 17
  • For better help sooner, please include an [SSCCE](http://sscce.org). – mre Feb 15 '13 at 17:26
  • I thought this was short and to the point. Was my question not clear? – Matt Feb 15 '13 at 17:29
  • There are many nuances when it comes to Swing. The more information you give us, the easier it is for us to help you. Otherwise, we're all left shooting in the dark, although sometimes we get lucky. – mre Feb 15 '13 at 17:30

3 Answers3

20

You should add component not to JScrollPane but to its JViewport:

scrollPane.getViewport ().add (table);
Mikhail Vladimirov
  • 13,572
  • 1
  • 38
  • 40
  • 1
    Alternativly you could use `JViewport.setView(Component)`, but it'll do the same thing. – MadProgrammer Feb 15 '13 at 19:51
  • That worked like charm. What I was doing was scrollPane.add(table), this solved it. – yuva Nov 20 '14 at 10:45
  • omg... for a day now I've been trying to figure out why my jTable wasn't showing up. Seriously, why wouldn't it just be `scrollPane.add(Component)`? I mean, what else would I be adding a component to? Shouldn't it just default to the viewPort? – Rabbit Guy Aug 08 '16 at 21:26
5

Instead of adding table to the JScrollPane Create a viewport of scrollpane and then sets its view as table. using following code instead:
scrollPane.setViewportView(table)

Vishal K
  • 12,976
  • 2
  • 27
  • 38
3

Generally, you create the JTable and the JScrollPane together, even though you have no values yet.

It's better to use a DefaultTableModel, or a TableModel that you extend, for a dynamic table.

Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111