JPanel doesn't update until resize Jframe

前端 未结 5 953
孤独总比滥情好
孤独总比滥情好 2020-12-01 20:58

I subclass JPanel to overwrite paintComponent(Graphics), I want to draw an image onto jpanel in a jframe.

But my image hasn\'t shown up until I make a change to jfra

5条回答
  •  情歌与酒
    2020-12-01 21:35

    I had the same problem and fixed it by call setVisible(true); the JFrame I was using.

    Example : if your JFrame does not update after using :

    jframe.setContentPane(new MyContentPane());
    

    fix it with :

    jframe.setContentPane(new MyContentPane());
    jframe.setVisible(true);
    

    I know that it sounds silly to do this even though your JFrame is already visible, but that's the only way I've found so far to fix this problem (the solution proposed above didn't work for me).

    Here is a complete example. Run it and then uncomment the "f.setVisible(true);" instructions in classes Panel1 and Panel2 and you'll see the difference. Don't forget the imports (Ctrl + Shift + O for automatic imports).

    Main class :

    public class Main {
        private static JFrame f;
        public static void main(String[] args) {
            f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(new Panel1(f));
            f.pack();    
            f.setVisible(true);
        }
    }
    

    Panel1 class :

    public class Panel1 extends JPanel{
        private JFrame f;
        public Panel1(JFrame frame) {
            f = frame;
            this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
            JButton b = new JButton("Panel 1");
            b.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    f.setContentPane(new Panel2(f));
                    // Uncomment the instruction below to fix GUI "update-on-resize-only" problem
                    //f.setVisible(true);
                }
            });
            add(b);
        }
    }
    

    Panel2 class :

    public class Panel2 extends JPanel{
        private JFrame f;
        public Panel2(JFrame frame) {
            f = frame;
            this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
            JButton b = new JButton("Panel 2");
            b.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    f.setContentPane(new Panel1(f));
                    // Uncomment the instruction below to fix GUI "update-on-resize-only" problem
                    //f.setVisible(true);
                }
            });
            add(b);
        }
    }
    

    Hope that helps.

    Regards.

提交回复
热议问题