Panel.repaint(); messes up layout

浪子不回头ぞ 提交于 2019-12-02 22:59:58

问题


JPanel Initiation

    p = new JPanel() {
        private static final long serialVersionUID = 1L;
        public void paintComponent(Graphics g) {
            if(errors == 1)
                g.drawOval(215, 50, 75, 75);
            else if(errors == 2)
                g.drawOval(200,200,200,200);
        }
    };

Method that calls repaint

static void drawHead() {
    System.out.println("Head");
    errors = 1;
    p.removeAll();
    p.revalidate();
    p.repaint();
}

Before repaint my frame looks like this, http://i.imgur.com/XQlQeul.png

And afterwards it looks like this, http://i.imgur.com/RnVuUzt.png

I'm thinking there is an error in my drawHead() method but I cannot seem to resolve the issue. Does anyone know what is going on? My desired outcome would be the first image, but with a head drawn in.


回答1:


You've broken the paint chain by failing to call super.paintComponent first before you performed any custom painting

Graphics is shared resource, every component painted in a during a paint cycle will share the same Graphics context, this means that whatever was previously painted to the Graphics context will remain unless you clear it.

One of the jobs of paintComponent is to prepare the Graphics context for painting by filling it with the background color of the component



来源:https://stackoverflow.com/questions/23646526/panel-repaint-messes-up-layout

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