I want to set a background to my jFrame, and I\'m using this code:
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java
Print the width of loaded image if it's -1 then image is not properly loaded.
img = Toolkit.getDefaultToolkit().createImage("red.png");
System.out.println(img.getWidth(null)); // check what it prints
It's worth reading Java Tutorial on Loading Images Using getResource
You can try any one based on image location.
// Read from same package
ImageIO.read(getClass().getResourceAsStream("c.png"));
// Read from images folder parallel to src in your project
ImageIO.read(new File("images/c.jpg"));
// Read from src/images folder
ImageIO.read(getClass().getResource("/images/c.png"))
// Read from src/images folder
ImageIO.read(getClass().getResourceAsStream("/images/c.png"))
Read more...
Some Points:
call super.paintComponent(g);
at first line in the overridden paintComponent()
method.
Use ImageIO
instead of Toolkit
to load the image.
Use frame.pack()
instead of frame.setSize()
that fits the components as per component's preferred size.
Override getPreferredSize()
to set the preferred size of the JPanel
in case of custom painting.
Use SwingUtilities.invokeLater() or EventQueue.invokeLater() to make sure that EDT is initialized properly.
Read more
Why to use SwingUtilities.invokeLater in main method?
SwingUtilities.invokeLater
Should we use EventQueue.invokeLater for any GUI update in a Java desktop application?