JPanel doesn't update until resize Jframe

前端 未结 5 952
孤独总比滥情好
孤独总比滥情好 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:31

    Take a look at the docs for JPanel.add(), which it inherits from java.awt.Container:

    Appends the specified component to the end of this container. This is a convenience method for addImpl(java.awt.Component, java.lang.Object, int). This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to display the added component.

    Emphasis added.

    Therefore, if you modify a Container after it's already been displayed, you must call validate() in order for it to show up. Just invoking repaint() is not enough. You may have noticed that calling setVisible(true) also works; this is because it calls validate() internally.

提交回复
热议问题