简体   繁体   中英

Change content pane of JFrame and new component not displaying

I'm making a game and I'm trying to switch between different JPanel s to display the menu, world etc.

public static void setComponent(Component component){
        frame.getContentPane().removeAll();
        frame.getContentPane().add(component, 0);   
    }

This is the method to change the component of the JFrame frame, this works for the first time with whichever JPanel component I give it, but when I try to change it from inside any class from a keyListener method say, the content pane doesn't display anything.

@Override
        public void mousePressed(MouseEvent arg0) {
            Frame.setComponent(new MenuPanel());
        }

Method to create the JFrame and the thread that repaints the components

public static void createFrame(){
    frame = new JFrame();

    frame.setSize(size);
    frame.setTitle(title);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setLayout(new GridLayout(1,1,0,0));

    new Thread(){
        public void run(){
            while(true){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(frame.getComponentCount() != 0){
                    //System.out.println("?");
                    frame.getContentPane().repaint();   
                    System.out.println(frame.getContentPane().getComponentAt(1, 1));
                }
            }
        }
    }.start();

    setComponent(new MenuPanel());  

    frame.setVisible(true);
}

Getting this result from the Output Stream when first loading

Menu.MenuPanel[,0,0,794x571,layout=java.awt.FlowLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]

Then after using the setComponent method from another class

javax.swing.JPanel[null.contentPane,0,0,794x571,invalid,layout=java.awt.GridLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]

When you call your setComponent method the first time, you do that before you call frame.setVisible(true) that forces the frame to validate all its components and show them. When you change the components later you need to revalidate your frame manually so it gets aware of its components. Add these lines to your setComponent method and it should work.

public static void setComponent(Component component){
    frame.getContentPane().removeAll();
    frame.getContentPane().add(component, 0);
    frame.revalidate();   // revalidate all the frame components
    frame.repaint();      // and repaint the frame
}

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