我有一个 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
感谢您的帮助:)