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
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.