What is the proper way to swap out an existing JPanel in a JFrame with another?

落爺英雄遲暮 提交于 2019-11-29 16:25:21

that requires swapping out the current, visible JPanel with another

Have a look at CardLayout for a complete example of how to do it properly.

I have a Swing app which 'swaps' Panels when the user press the 'SPACE' key, showing a live plot of a running simulation. What i did goes like this:

public class MainPanel extends JPanel implements Runnable {

    // Called when the JPanel is added to the JFrame
    public void addNotify() {

        super.addNotify();
        animator = new ScheduledThreadPoolExecutor(1);
        animator.scheduleAtFixedRate(this, 0, 1000L/60L, TimeUnit.MILLISECONDS);
    }

    public void paintComponent(Graphics g) {

        super.paintComponent(g);

        if (spacePressed) 
            plot.render(g);
        else
            simulation.render(g);
    }

    public void run() {

        simulation.update(); 
        repaint();
    }
}

public class PlotView {

    public void render(Graphics g) {
         //draw the plot here
    }
}

public class SimulationView {

    public void render(Graphics g) {
         //draw simulation here
    }
}

This works very well for my 'show live plot' problem. And there's also the CardLayout approach, which you may turn into a new separate question if you having trouble. Good luck!

You should do .setVisible(false); to the panel which you want to be replaced.

Here is a working example, it switches the panels when you press "ENTER"; If you copy this in an IDE, automatically get the imports (shift+o in Eclipse);

public class MyFrame extends JFrame implements KeyListener {

    private JButton button = new JButton("Change Panels");
    private JPanel panelOnFrame = new JPanel();
    private JPanel panel1 = new JPanel();

    public MyFrame() {
        // adding labels to panels, to distinguish them
        panelOnFrame.add(new JLabel("panel on frame"));
        panel1.add(new JLabel("panel 1"));      

        setSize(new Dimension(250,250));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        add(button);
        add(panelOnFrame);
        setVisible(true);
        addKeyListener(this);

        addKeyListener(this);
        setFocusable(true);
    }

    public static void main(String[] args) {
        MyFrame frame = new MyFrame();
    }

    @Override
    public void keyPressed(KeyEvent k) {
        if(k.getKeyCode() == KeyEvent.VK_ENTER){

//+-------------here is the replacement:

            panelOnFrame.setVisible(false);
            this.add(panel1);
        }
    }

    @Override
    public void keyReleased(KeyEvent arg0) {
    }

    @Override
    public void keyTyped(KeyEvent arg0) {
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!