1

Good day,

I have created multiple panels and the first one is showing. I need the panel to be removed and a new one added when the user clicks a next icon. In the code below, the panel reference is not recognized in the action listener. How can I work round this?

    int n=0;
    for (int l=0; l < layOutPanelCount; l++) {
        layOutPanel[l] = new JPanel();
        layOutPanel[l].setLayout(null);
        layOutPanel[l].setBounds(0, 0, screenWidth, screenHeight);

        ImageIcon nextIcon = new ImageIcon("src/icons/next.png");
        JLabel nextLabel = new JLabel(nextIcon);
        nextLabel.setBounds(xPos, yPos, 48, 48);
        nextLabel.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e){
                layOutFrame.remove(layOutPanel[l]);
                layOutFrame.add(layOutPanel[l + 1]);
                //Here the problem occurs, the layOutPanel[] is not recognized.
            }
        });

        layOutPanel[l].add(nextLabel);
   }
   layOutFrame.add(layOutPanel[1]);
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Chris Shaw
  • 23
  • 4

2 Answers2

3

1) after remove/add a new JComponent(s) to the visible container you have to call

revalidate();
repaint();

2) maybe you'd want to re_layout container, then you can call pack() too

3) there I can't see reason for re_creating JPanel on the runtime, use

JLabel#setIcon(myIcon)

instead of

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • Thanks for trying to help. The problem is something to do with trying to access local variables from a sub class. I have had to do a complete rethink to solve the problems. – Chris Shaw Mar 01 '12 at 05:39
2

Use a CardLayout instead, as shown here.

Game view High Scores view


Other notes

  1. Use a JButton with an ActionListener rather than a JLabel with a MouseListener.

    1. The former will respond to mouse as well as keyboard, whereas the latter will respond only to mouse.
    2. Icons in buttons can produce exactly the same 'prettyness' as icons in labels (given they can be made to look identical). But buttons still provide extra functionality that might be useful 'out of the box'. E.G. Disabled icons that appear different to the usual icon, while still conveying the same general meaning, roll-over icons, selected icons..
  2. Use layout managers (with appropriate layout padding, and borders on the components) rather than null layouts and setBounds().

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433