I program in java and I go into graphical interfaces and graphics. In my program, I draw an image on JPanel and add JPanel to the main window. The problem that I encountered is when I run the program, the image does not appear until I manually resize the window. Here is the relevant code:
If the image is drawn:
public class painting extends JPanel{ public void paintComponent(Graphics g){ super.paintComponent(g); this.setBackground(Color.WHITE); g.drawImage(Toolkit.getDefaultToolkit().getImage("image.png"), 0, 0, null); } }
If a JPanel is added to the JFrame (c - GridBagConstraints):
public class GUI extends JFrame{ public GUI(){ painting Pnt = new painting(); c.gridx = 1; c.gridy = 0; c.ipadx = 540; c.ipady = 395; add(Pnt, c); } }
Where is the window installed:
public class MainC{ public static void main (String args[]){ GUI gui = new GUI(); gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gui.pack(); gui.setVisible(true); gui.setTitle("Title"); } }
Thanks Bennett
EDIT: I noticed that it sometimes displays the image correctly, but then if I close the program and try again, and it does not work until I resize it.
EDIT2: Here are the files of the GUI class , MainC class
source share