I have list of JPanel
components. I want to open corresponding panel based on clicking a button. While clicking button, I pass the panel name. But in my case panel have more components, so I am adding each panel to JScrollPane
and adding these scroll panes to CardLayout
.
Based on this example, here is the code for adding panel to card layout:
final JPanel cards=new JPanel(new CardLayout());
cards.setPreferredSize(new Dimension(600, 550));
for (JPanel p:panels) {
JScrollPane scrollPanel=new JScrollPane(p);
scrollPanel.setName(p.getName());
scrollPanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
cards.add(scrollPanel);
}
CardLayout cardLayout=(CardLayout) cards.getLayout();
cardLayout.show(cards, "name");
control.add(new JButton(new AbstractAction("\u22b2Prev") {
@Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) cards.getLayout();
cl.previous(cards);
}
}));
control.add(new JButton(new AbstractAction("Next\u22b3") {
@Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) cards.getLayout();
cl.next(cards);
}
}));
But clicking button shows first panel in the card layout.
How to solve this problem? Can I use scroll pane name instead of panel name in show method?