0

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?

Community
  • 1
  • 1
User123
  • 71
  • 3
  • 14

2 Answers2

1

Yes you are right.

A scroll pane may be added directly to the card layout:

JPanel myPanel = new JPanel();
JScrollPane myScroll = new JScrollPane(myPanel);
this.add(myScroll, "NAME");
CardLayout cl = (CardLayout) this.getLayout();
cl.show(this, "NAME");
0

Simple Way to add a Scroll pane :

JPanel panel = new JPanel();
add(new JScrollPane(panel));
Programmer
  • 445
  • 4
  • 12