[英]Get JPanel in a JScrollPane
I have a JScrollPane and I put a JPanel in the JScrollPane. 我有一个JScrollPane,我在JScrollPane中放了一个JPanel。 The JPanel holds a variable amount of JLabels.
JPanel拥有可变数量的JLabel。
Here is how I "new" it: 这是我如何“新”它:
JPanel dataPanel = new JPanel();
//then do a for loop to put a few JLabels in dataPanel
JScrollPane scrollPane = new JScrollPane(dataPanel);
I was wondering how I can get those JLabel in another class? 我想知道如何在另一堂课中获得这些JLabel? I tried the following code but doesn't work coming with a ClassCastException.
我尝试了以下代码,但无法使用ClassCastException。 In that class, I succeed to get the JScrollPane and I will use scrollPane to represent it.
在那个类中,我成功获得了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);
}
In fact, at the statement: 事实上,在声明中:
JPanel panel = scrollPane.getComponent(0);
The ClassCastException is thrown. 抛出ClassCastException。
java.lang.ClassCastException: javax.swing.JViewport cannot be cast to javax.swing.JPanel
Appreciated for help :) 赞赏求助:)
JScrollPane#getViewport#getView JScrollPane的#getViewport#getView
You'll have to cast out back to your component type 您必须退回到您的组件类型
The better solution would be to maintain a list of the JLabel
s in an array or List
更好的解决方案是在数组或
List
维护JLabel
的List
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.