if you want to load your image or file in the resources folder, you might need to use BufferedImage
and ImageIO
:
import javax.swing.ImageIcon;
import javax.swing.JFrame ;
import javax.swing.JPanel ;
import javax.imageio.ImageIO ;
import javax.swing.SwingUtilities;
import java.awt.Graphics;
import java.awt.Graphics2D ;
import java.awt.Image;
import java.awt.image.BufferedImage ;
import java.awt.Dimension ;
import java.io.IOException;
public class LoadImage extends JFrame {
public LoadImage() {
super("Title") ;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
add(new Panel()) ;
// use this idea if you want to have exact window location
pack() ;
setLocationRelativeTo(null) ; // makes it center
}
// If you want to run the image in your panel
public static class Panel extends JPanel {
BufferedImage bufferedImage ;
ImageIcon imageIcon ;
Image image ;
public Panel() {
setLayout(null) ;
setPreferredSize(new Dimension(600, 600)) ;
// for loading your resources inside of you program, for example: src/main/resources/path/to/your/location.png
try {
bufferedImage = ImageIO.read(getClass().getResourceAsStream("/path/to/your/location.png"));
} catch (IOException e) {
e.printStackTrace() ;
}
// for loading your image outside the program, for example: saves/image.png
// if you create your jar, you need to put your files outside the jar
image = new ImageIcon("path/to/your/location.png").getImage() ;
imageIcon = new ImageIcon("path/to/your/location.png") ;
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g ;
super.paintComponent(g) ;
// for buffered image
if (bufferedImage != null) {
g2d.drawImage(bufferedImage, 0, 0, null) ;
g.drawImage(bufferedImage, 0, 0, null) ;
}
//for image icon
if (imageIcon != null) {
g2d.drawImage(imageIcon.getImage(), 0, 0, null) ;
g.drawImage(imageIcon.getImage(), 0, 0, null) ;
}
// for image
if (image != null) {
g2d.drawImage(image, 0, 0, null) ;
g.drawImage(image, 0, 0, null) ;
}
}
}
public static void main(String[] args) {
// makes it write all the codes, then shows the code
SwingUtilities.invokeLater(() -> new LoadImage().setVisible(true)) ;
}
}
hope this solution help you :) i created a library that can handle your images, wav musics, files, creating or loading saves from various locations, user home, program directory check the link if you want JStreamLoader library on GitHub