私は JScrollPane を持っていて、JPanel を JScrollPane に入れました。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
助けてくれてありがとう:)