实现JPanel切换

首发于Enaium的个人博客


public static void main(String[] args) {
    JFrame jFrame = new JFrame("Test");
    jFrame.setSize(500, 500);
    jFrame.setLocationRelativeTo(jFrame.getOwner());
    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jFrame.setLayout(new BorderLayout());
    var jPanel = new JPanel(new BorderLayout());
    
    jFrame.add(jPanel, BorderLayout.CENTER);
    AtomicBoolean b = new AtomicBoolean(false);
    jFrame.add(new JButton("Switch") {
        {
            addActionListener(e -> {
                b.set(!b.get());
                jPanel.removeAll();
                jPanel.repaint();
                jPanel.revalidate();
                jPanel.add(b.get() ? new JPanel() {
                    @Override
                    protected void paintComponent(Graphics g) {
                        setBackground(Color.RED);
                        super.paintComponent(g);
                    }
                } : new JPanel() {
                    @Override
                    protected void paintComponent(Graphics g) {
                        setBackground(Color.GREEN);
                        super.paintComponent(g);
                    }
                });
                jPanel.repaint();
                jPanel.revalidate();
            });
        }
    }, BorderLayout.SOUTH);
    jFrame.setVisible(true);
}

主要就是这几行

jPanel.removeAll();//移除全部
jPanel.repaint();//重绘
jPanel.revalidate();//重新验证
jPanel.add();//需要切换的JPanel
jPanel.repaint();
jPanel.revalidate();

最新在写JFrame,需要切换多个窗口太麻烦,就直接切换JPanel,最初使用的是CardLayout,限制太多,需要提前把JPanel全部加进去才能切换,后来就用这个方法来动态切换

posted @   Enaium  阅读(76)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示