Just using the paint method and my image won’t show up initially. Once I minimize the java window and resize it, the image shows up. Is there any code I’m missing?
public class Lil extends JFrame {
Image image = Toolkit.getDefaultToolkit().getImage("images/Untitled.png");
public Lil(){
setTitle("flame");
setBackground(Color.WHITE);
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
public void paint(Graphics g){
g.clearRect(0, 0, 400, 400);
g.drawImage(image, 60, 25, null);
//repaint();
}
public static void main(String [] args){
new lil();
}
}
Don’t draw directly in a JFrame. Instead draw in a JPanel’s paintComponent method and then add that JPanel onto your JFrame’s contentPane. Better still, if you’re not going to be using the image-component as a container (to hold other components), just create an ImageIcon with the Image, place the icon into a JLabel via its constructor or its setIcon method, and simply display the JLabel. No muss, no fuss, no trouble. Also, likely there’s no need to call clearRect if you call super’s paintComponent method as the first call in the JPanel’s paintComponent override method.
For instance, if going the more complex route of drawing directly in a JPanel, you’d do something like so:
Again, only do this if you’re going to be placing components on the image such as text fields, buttons, and so forth. If not, then use the simpler ImageIcon/JLabel idea.