Java: the image will not be displayed until I resize the window.

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

+4
source share
4 answers

Toolkit.getImage() works asynchronously. Either use ImageIO.read() , or add MediaTracker .

+4
source

In the GUI constructor, you must call super () first.

Also move:

 gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gui.pack(); gui.setVisible(true); gui.setTitle("Title"); 

in the GUI constructor.

0
source

does

 Toolkit.getDefaultToolkit().getImage("image.png") 

display image?
I tried:

 public class Gui extends JFrame{ public Gui() { this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLayout(new BorderLayout()); this.setBounds(100, 100, 300, 300); JPanel pnl = new JPanel(){ public void paintComponent(Graphics g){ super.paintComponent(g); this.setBackground(Color.WHITE); try { g.drawImage(new Robot().createScreenCapture(new Rectangle(90, 90)), 0, 0, null); } catch (AWTException e) { e.printStackTrace(); } } }; getContentPane().add(pnl, BorderLayout.CENTER); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new Gui().setVisible(true); } }); } 

and it works.

0
source

Your problem should be somewhere else in your code. I copied and pasted your three classes into my IDE. The only thing I changed was in GUI.java, I added setLayout(new GridBagLayout()); and GridBagConstraints c = new GridBagConstraints(); , and I changed the location of the image to one of mine. The window works, as expected, with the image displayed immediately.

I assume that you have additional code that does not appear here, such as the initialization c, which I added. Check your other code to make sure you are not redrawing the image. Also, if you publish another code, I can help you identify the problem.

0
source

All Articles