tags:

views:

62

answers:

2

Hi I have a panel on my frame .and by clicking on a button I want to delete the old panel and make the other panel and add that panel to my frame.(also I use netbeans) would you please help me that how can i do that?thanks

+2  A: 
JFrame frame = new JFrame();
final JPanel origPanel = new JPanel();
frame.add(origPanel, BorderLayout.CENTER);

MouseListener ml = new MouseAdapter() {
  public void mouseClicked(MouseEvent evt) {
    // Mouse clicked on panel so remove existing panel and add a new one.
    frame.remove(origPanel);
    frame.add(createNewPanel(), BorderLayout.CENTER);

    // Revalidate frame to cause it to layout the new panel correctly.
    frame.revalidate();

    // Stop listening to origPanel (prevent dangling reference).
    origPanel.removeMouseListener(this);
  }
}

origPanel.addMouseListener(ml);
Adamski
thanksI have written your code in my Frame and I use "this" instead of "frame",is this correct?? also I can not write this.revalidate(). please help me thanks
Johanna
I knew you would come back for spoon feeding trying to fix your compile error. Can you not do any thinking on your own? Do you not know how to use the API to look up valid methods and the Objects they apply to?
camickr
Can I replace revalidate() with repaint()
Johanna
what should I do when i can not use revalidate here? thanks
Johanna
Frustrating when people ignore you isn't it? You have continued to ignore all my suggestions over the months. You still haven't posted your SSCCE showing what you are doing. I could probably give you the solution and tell you its a "2 character" solution to your problem. But I'm not going to be that generous until you learn how to properly ask a question (which means include a SSCCE with every question) and use the forum (which means accept answers when they are given).
camickr
A: 

This way:

    final JFrame frame = new JFrame();
    frame.setSize(200, 200);

    final JPanel panelA = new JPanel();
    final JPanel panelB = new JPanel();
    JButton button = new JButton("Switch");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            frame.remove(panelA);
            frame.add(panelB);
            frame.show();
        }
    });
    JLabel label = new JLabel("This is panel B. Panel A is gone!");
    panelB.add(label);
    panelA.add(button);
    frame.add(panelB);
    frame.add(panelA);
    frame.show();
rodrigoap
I can not write this.show!!!!
Johanna