Get JPanel in a JScrollPane

1k Views Asked by At

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 :)

1

There are 1 best solutions below

0
On

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