如何替换 JScrollPane 子组件
我有一个 JPanel,其中包含一个 JScrollPane,其中包含一个 JTable。在我的面板构造函数中,它是这样创建的:
//inside MyPanel extends JPanel class constructor
public void MyPanel(){
TitledBorder border = BorderFactory.createTitledBorder("title");
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.scrollTable = new JScrollPane(table);
this.scrollTable.setBorder(border);
}
现在,用户应该能够将另一个表加载到应用程序中,因此我需要从滚动窗格中删除前一个表并添加一个新表。 我已尝试以下操作:
public void setNewTable(JTable t ) {
this.scrollTable.removeAll();
this.scrollTable.add(t);
this.scrollTable.validate();
}
先前的表格已删除,但现在 JScrollPane 内没有任何变化。
我做错了什么?
公共空白
I have a JPanel that contains a JScrollPane that contains a JTable. Inside my panel constructor it's created this way:
//inside MyPanel extends JPanel class constructor
public void MyPanel(){
TitledBorder border = BorderFactory.createTitledBorder("title");
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.scrollTable = new JScrollPane(table);
this.scrollTable.setBorder(border);
}
Now, the user should be able to load another table into application so I need to remove the previous one from the scrollpane and add a new one.
I've tried the following :
public void setNewTable(JTable t ) {
this.scrollTable.removeAll();
this.scrollTable.add(t);
this.scrollTable.validate();
}
The previous table is removed, but nothing happear inside the JScrollPane now.
What am I doing wrong?
public void
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能只添加到 JScrollPane,因为它由其他内部组件组成。
来自 JavaDocs:
通过调用scrollPane.removeAll(),您实质上删除了标题、视图和滚动条,并添加了一个组件滚动窗格不理解。
首先,您通常不应该以这种方式传递表格。最好传入 TableModel,并通过JTable.setModel()更改表上的模型。
也就是说,如果您绝对想传入表格,则需要在滚动窗格中的视口上设置视图:
You can't just add to JScrollPane, since it consists of other internal components.
From the JavaDocs:
By calling scrollPane.removeAll() you essentially, remove the header, view, and scrollbars, and add a component that the scrollpane doesn't understand.
First of all, you generally shouldn't pass around tables in that manner. It would be much better to instead pass in a TableModel, and change the model on the table via JTable.setModel().
That said, if you absolutely want to pass in a table, you need to set the view on the viewport in the scrollpane: