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

后端 未结 3 1028
天涯浪人
天涯浪人 2020-12-22 04:00

I\'m building a program that requires swapping out the current, visible JPanel with another. Unfortunately there seems to be multiple to go about this and all of my attempts

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-22 04:36

    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!

提交回复
热议问题