java 将 JTable 动态添加到 JScrollPane
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14899918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically adding JTable to JScrollPane
提问by Matt
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?
问题是,表格永远不会显示。我只看到 ScrollPane 所在位置的轮廓,里面没有表格。为什么表格不显示,我该如何解决?
回答by Mikhail Vladimirov
You should add component not to JScrollPane but to its JViewport:
您不应该将组件添加到 JScrollPane,而是添加到它的 JViewport:
scrollPane.getViewport ().add (table);
回答by Vishal K
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)
而不是将表格添加到 JScrollPane 创建一个滚动窗格的视口,然后将其视图设置为表格。改用以下代码:scrollPane.setViewportView(table)
回答by Gilbert Le Blanc
Generally, you create the JTable
and the JScrollPane
together, even though you have no values yet.
通常,您会一起创建 theJTable
和 the JScrollPane
,即使您还没有任何值。
It's better to use a DefaultTableModel, or a TableModel
that you extend, for a dynamic table.
对于动态表,最好使用DefaultTableModel或TableModel
您扩展的 。