3

I have a JScrollPane and I put a JPanel in the JScrollPane. The JPanel holds a variable amount of JLabels.

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? I tried the following code but doesn't work coming with a ClassCastException. In that class, I succeed to get the JScrollPane and I will use scrollPane to represent it.

//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.

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

Appreciated for help :)

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user1888955
  • 626
  • 1
  • 9
  • 27

1 Answers1

5

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 JLabels in an array or List

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366