将JTable动态添加到JScrollPane [英] Dynamically adding JTable to JScrollPane
问题描述
我有一个要在用户提示时填充的表.问题是,我无法预计该表最终将具有多少行.在将要显示表格的面板的构造函数中,我有
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();
}
问题是,该表永远不会显示.我只是看到一个ScrollPane所在的轮廓,里面没有表格.为什么表格没有显示,我该如何解决?
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?
推荐答案
您不应将组件添加到JScrollPane,而应添加到其JViewport:
You should add component not to JScrollPane but to its JViewport:
scrollPane.getViewport ().add (table);
这篇关于将JTable动态添加到JScrollPane的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!