實現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全部加進去才能切換,後來就用這個方法來動態切換

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章