繁体   English   中英

在JScrollPane中获取JPanel

[英]Get JPanel in a JScrollPane

我有一个JScrollPane,我在JScrollPane中放了一个JPanel。 JPanel拥有可变数量的JLabel。

这是我如何“新”它:

JPanel dataPanel  = new JPanel();
//then do a for loop to put a few JLabels in dataPanel
JScrollPane scrollPane = new JScrollPane(dataPanel);

我想知道如何在另一堂课中获得这些JLabel? 我尝试了以下代码,但无法使用ClassCastException。 在那个类中,我成功获得了JScrollPane,我将使用scrollPane来表示它。

//I only put a panel in the JScrollPane, so I used 0 in the getComponent() method
JPanel panel = scrollPane.getComponent(0);
for(int i = 0; i < panel.getComponentCount(); i++){
    JLabel label = (JLabel)panel.getComponent(i);
}

事实上,在声明中:

JPanel panel = scrollPane.getComponent(0);

抛出ClassCastException。

java.lang.ClassCastException: javax.swing.JViewport cannot be cast to javax.swing.JPanel

赞赏求助:)

JScrollPane的#getViewport#getView

您必须退回到您的组件类型

更好的解决方案是在数组或List维护JLabelList

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM