简体   繁体   中英

JPanel repaint doesn't work

I have a simple task.

There is a frame. There are two panel in that frame. In second panel there is a button. When user click that button first panel must change its content.

Here is a code:

package test;


import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;


class MyJPanel1 extends JPanel {
    MyJPanel1() {
        this.add(new JButton("MyJPanel1"));
    }
}


class MyJPanel2 extends JPanel {
    MyJPanel2() {
        this.add(new JButton("MyJPanel2"));
    }
}


class MyFrame extends JFrame {
    JPanel topPanel = null;

    MyFrame() {        
        super("Test");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new GridLayout(0, 1, 20, 20));

        topPanel = new MyJPanel1();                
        this.add(topPanel); 

        JPanel bottomPanel = new JPanel();
        this.add(bottomPanel);

        JButton button = new JButton("switch");
        button.addMouseListener(new MouseClickListener());
        bottomPanel.add(button);

        this.pack();
        this.setVisible(true);
    }    

    class MouseClickListener extends MouseAdapter { 
        @Override
        public void mouseClicked(MouseEvent e) {        
            topPanel = new MyJPanel2();
            System.out.println("switch");

            topPanel.invalidate();
            topPanel.validate();
            topPanel.repaint();

            MyFrame.this.invalidate();
            MyFrame.this.validate();
            MyFrame.this.repaint();
        }
    }
}


public class Test {
    public static void main(String[] args) {        
        SwingUtilities.invokeLater(new Runnable() {            
            @Override
            public void run() {                
                new MyFrame();                
            }
        });
    }
}

But that don't work. After I click on button I see text in console, but first panel remain the same. I read that I must use invalidate() validate() and repaint() methods and I did, but it isn't help.

Any help would be appreciated.

If you want to "switch" panels then you should be using a CardLayout . The CardLayout allows 2 (or more) components to share the same space in a container but only one is ever visible at a time.

Read the section from the Swing tutorial on How to Use CardLayout for more information and working examples.

In your mouseClicked() method you create a new topPanel, but you don't do anything with it. Perhaps you meant to remove the original topPanel from myFrame, create a new topPanel, and then add the new toipPanel to myFrame.

Note that this may not be the best strategy (creating a new topPanel).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM