Dynamically adding JTable to JScrollPane

帅比萌擦擦* 提交于 2019-12-07 03:58:47

问题


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?


回答1:


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

scrollPane.getViewport ().add (table);



回答2:


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)




回答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.



来源:https://stackoverflow.com/questions/14899918/dynamically-adding-jtable-to-jscrollpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!