Wednesday, April 14, 2021

[Java Code Sample] How to Display Images (in JAR file too)

 

 This is how to display images. The image is still visible even after exporting as jar.


Preparation:

1. Right click on the project foler

2. Choose "New"

3. Choose "Resource Folder"



4. type "res" for folder name and click "Finish"


5. Drag & drop your image to the res folder


Here's a sample code:


import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {

	public static void main(String[] args) {
		
		new Main();
	}
	public Main() {
		
		JFrame window = new JFrame();
		window.setSize(800, 600);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.getContentPane().setBackground(Color.black);
		window.setLayout(null);
				
		JLabel label = new JLabel();
		label.setBounds(150,50,500,500);
		
        // Type your image file name between " "
		ImageIcon image = new ImageIcon(getClass().getClassLoader().getResource("crusader 378x500.png"));				
		label.setIcon(image);
		
		window.add(label);
		
		window.setVisible(true);		
	}
}

Result:

Here's the video tutorial:


No comments:

Post a Comment