Get JPanel in JScrollPane

I have a JScrollPane and I have placed a JPanel in a JScrollPane. JPanel has a variable number of JLabels.

This is how I am "new":

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 can I get the JLabel in another class? I have tried the following code but does not work with ClassCastException. In this class I manage to get the JScrollPane and I will use scrollPane to present 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, in the statement:

JPanel panel = scrollPane.getComponent(0);

      

A ClassCastException is thrown.

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

      

Score for help :)

+3


source to share


1 answer


JScrollPane # getViewport # getView

You will have to drop your component type



Better solution would be to keep the list JLabel

in an array, orList

+5


source







All Articles