I cannot load Images in .JAR [duplicate] - java

This question already has answers here:
Once exported, java cannot find/draw images
(2 answers)
Closed 6 years ago.
I'm a student currently studying Java Programming and using Netbeans to create the application. The program is already done and loads nicely in the IDE (with images). I have to build it into JAR for a presentation to my lecturer and has done it but the images are not present in the JAR.
First of all, I've checked all the available answers for allowing images to be present in the JAR but I couldn't get it right with the program as it doesn't load even in IDE and shows error. Which most have pointed out that I have to input (getClass().getClassLoader().getResource("image.jpg")). I tried inputting it but it shows errors, mostly because my codes for placing the ImageIcon are different.
Below is my full code of the JFrame presenting the program:
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.*;
import javax.swing.ImageIcon;
import java.util.logging.Level;
import java.util.logging.Logger;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class A2{
public void GUI () throws IOException {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setTitle("Minus");
frame.setSize(700,500);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
//Set the layout
JPanel panel;
panel = new JPanel();
panel.setLayout(null);
frame.setContentPane(panel);
// Create all components
JLabel ctgy = new JLabel("Minus");
JLabel minus2 = new JLabel("What is 6 squares minus 3 squares?");
JButton ans_a = new JButton("9");
JButton ans_b = new JButton("3");
JButton ans_c = new JButton("7");
JButton back = new JButton("Back");
JLabel min2 = new JLabel();
//Add objects to layout
panel.add(ctgy);
panel.add(minus2);
panel.add(min2);
panel.add(ans_a);
panel.add(ans_b);
panel.add(ans_c);
panel.add(back);
// Set position of objects in content pane
min2.setLocation(100,100);
minus2.setLocation(20,50);
ctgy.setLocation(10,3);
ans_a.setLocation(500,100);
ans_b.setLocation(500,150);
ans_c.setLocation(500,200);
back.setLocation(500, 400);
//Set size of object
min2.setSize(300,300);
ctgy.setSize(200,50);
minus2.setSize(350,50);
ans_a.setSize(100,30);
ans_b.setSize(100,30);
ans_c.setSize(100,30);
back.setSize(100, 30);
//Set the fonts and colors
Font font1 = new Font("Cooper Black", Font.BOLD, 26);
Font font2 = new Font("Calisto MT", Font.BOLD, 20);
ctgy.setFont(font1);
ctgy.setBackground(Color.white);
minus2.setFont(font2);
minus2.setBackground(Color.red);
panel.setBackground (Color.RED);
ans_a.setBackground(Color.white);
ans_b.setBackground(Color.white);
ans_c.setBackground(Color.white);
min2.setIcon(new ImageIcon("src/images/6-3.png"));
ans_b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Correct!");
try {
A3.main(null);
} catch (IOException ex) {
Logger.getLogger(A1.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
ans_a.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Incorrect! Please try again.");
}
});
ans_c.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Incorrect! Please try again.");
}
});
frame.repaint();
back.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent f){
Categories.main(null);
}
});
}
public static void main (String [] args) throws IOException {
A2 gd = new A2();
gd.GUI();
}
}
This is the part of my code where I state the JLabel to put my image in which I named as min2:
JLabel ctgy = new JLabel("Minus");
JLabel minus2 = new JLabel("What is 6 squares minus 3 squares?");
JButton ans_a = new JButton("9");
JButton ans_b = new JButton("3");
JButton ans_c = new JButton("7");
JButton back = new JButton("Back");
JLabel min2 = new JLabel();
This is adding the panel for the JLabel:
panel.add(min2);
The size and location:
min2.setLocation(100,100);
min2.setSize(300,300);
Lastly the image itself and location:
min2.setIcon(new ImageIcon("src/images/6-3.png"));
This part will show error because I set this to open a new Class when a user click the JButton so that would happen since you don't have the A3 Class:
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Correct!");
try {
A3.main(null);
} catch (IOException ex) {
Logger.getLogger(A1.class.getName()).log(Level.SEVERE, null, ex);
}
I've checked the JAR file with WinRAR and confirmed that images folder and the images are inside. I wanted to post the screenshots but Imgur isn't working for me.
The pathfile for all images are inside src/images.
Please suggest what changes I need to make. Thank you and sorry if it has been asked too much.

jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/img.png")));
this is how you should actually load the image file.your given file path is wrong try it with this approach.

Related

Is There a Way to Make a Java Method that Opens a .txt File as a pop-up? [duplicate]

This question already has answers here:
Loading a text file into a textarea
(4 answers)
Trying to read a text file into a JTextArea
(2 answers)
Open a text file in the default text editor... via Java?
(3 answers)
Closed 2 months ago.
I am currently making a java project that simulates a website for swimmers. It has multiple classes and incorporates the Jswing GUI. I have buttons that are used to display other classes GUI and data, but I was wondering if there was a way to have it so when I click a button, it would pull up a .txt file as a pop up externally, as opposed to just reading and writing the .txt files data into my console.
I had initially tried to display information from a .txt file into a JLabel or JTextField so it could be seen but I had abandoned that idea in order to pursue the easier and simplier idea of bringing up a entirely new window of a .txt file
package finalProject;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class FrontInterface extends JPanel {
private static JButton nSwimmer;
private static JButton cSwimmer;
private static JButton coach;
private JLabel heading;
private static JButton equipment;
public FrontInterface() {
//construct components
nSwimmer = new JButton ("New Swimmer");
cSwimmer = new JButton ("Current Swimmer");
coach = new JButton ("Coach");
heading = new JLabel ("Welcome to the Swimming Station");
equipment = new JButton ("Equipment");
//adjust size and set layout
setPreferredSize (new Dimension (752, 425));
setLayout (null);
//add components
add (nSwimmer);
add (cSwimmer);
add (coach);
add (heading);
add (equipment);
//set component bounds (only needed by Absolute Positioning)
nSwimmer.setBounds (280, 150, 200, 20);
cSwimmer.setBounds (280, 175, 200, 20);
coach.setBounds (280, 200, 200, 20);
heading.setBounds (280, 95, 195, 30);
equipment.setBounds (280, 225, 200, 25);
}
public static void showWindow(){
JFrame frame = new JFrame ("Front Interface");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new FrontInterface());
frame.pack();
frame.setVisible(true);
nSwimmer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
NewSwimmerForm w2 = new NewSwimmerForm();
w2.showWindow();
}
});
cSwimmer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
CurrentSwimmer w2_1 = new CurrentSwimmer();
w2_1.showWindow();
}
});
coach.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
NewSwimmerForm w2 = new NewSwimmerForm();
w2.showWindow();
}
});
equipment.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
NewSwimmerForm w2 = new NewSwimmerForm();
w2.showWindow();
}
});
frame.setVisible(true);
}
public static void main (String[] args) {
showWindow();
}
}
And below is the code that the cSwimmer button will take you to upon clicking the cSwimmer button:
package finalProject;
import finalProject.FrontInterface;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class CurrentSwimmer extends JPanel {
private static JTextArea informationHeader;
public static void showWindow(){
try{
File file = new File("C:\\Users\\trent\\Desktop\\Intro to Computer Science\\Eclipse Codes\\FinalProject\\src\\finalProject\\history.txt");
System.out.println(file.getCanonicalPath());
FileInputStream ft = new FileInputStream(file);
DataInputStream in = new DataInputStream(ft);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strline;
while((strline = br.readLine()) != null){
System.out.println(strline);
}
in.close();
}catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
public static void main(String [] args) {
showWindow();
}
}
Now, I am completely unsure of how to go about my situation, whether it be I display the information from the .txt file onto a jTextArea or if I should just create a method to make a .txt file open externally and replace the pop up window I would otherwise have with the writing to JTextArea.

JFrame window is not closing

so i was trying to make a quiz application but i got this error below
I Want to close the JFrame window so i tried setVisible(false); to close window if someone click back button but it is not working help me as im new. i even tried Jframe.dispose(); and other methods i dont what error i have made if you help me pls
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Login extends JFrame implements ActionListener {
JButton Rules,Back;
Login() {
getContentPane().setBackground(Color.white);
ImageIcon i1 = new ImageIcon(ClassLoader.getSystemResource("icon/login.jpeg"));//<-- to pick images from directory
setLayout(null);
JLabel image = new JLabel(i1);
JLabel heading = new JLabel("Quiz Bazzi");
heading.setBounds(750,50,300,50);
heading.setFont(new Font("Mongolian Baiti",Font.BOLD,42));
heading.setForeground(Color.ORANGE);
add(heading);
JLabel name = new JLabel("Enter Your Name");
name.setBounds(785,150,350,20);
name.setFont(new Font("Mongolian Baiti",Font.BOLD,18));
name.setForeground(Color.black);
add(name);
JTextField tfname = new JTextField();
tfname.setBounds(715,180,300,25);
tfname.setFont(new Font("Times New Roman",Font.BOLD,18));
tfname.setForeground(Color.black);
add(tfname);
Rules = new JButton("Rules");
Rules.setBounds(715,220,120,25);
Rules.setBackground(Color.black);
Rules.setForeground(Color.white);
add(Rules);
Back = new JButton("Back");
Back.setBounds(895,220,120,25);
Back.setBackground(Color.black);
Back.setForeground(Color.white);
add(Back);
image.setBounds(0,0,500,400);
add(image);
setSize(1200,439);
setLocation(180,100);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == Rules){
setVisible(true);
} else if (e.getSource() == Back) {
setVisible(false);
}
}
public static void main(String[] args) {
new Login();
}
}
Do you know what it the purpose of:
JFrame.dispose();
?
It is exactly what you need :)

Swing Application not appearing

Hi im am working on my Java project which I have to create a login page for users to enter, and when login is successful, an alert is supposed to tell them that the login was ok. However, I am having some troubles as my application is not showing up at all, I think it is something to do with the code that I have written. Below is the code:
public class UserLoginPage implements ActionListener {
//Put all JLabels,Frames and buttons here etc
JPanel panel = new JPanel();
JFrame frame = new JFrame();
JLabel userLabel = new JLabel("Username");
JLabel passwordLabel = new JLabel("Password");
JTextField userText = new JTextField();
JTextField passwordText = new JTextField();
JButton loginButton = new JButton("Login");
//Label for successful login
JLabel success = new JLabel("Login Successful");
//Default Constructor to add the frames and panels etc
public UserLoginPage(){
panel.setLayout(null);
userLabel.setBounds(10,20,80,25);
panel.add(userLabel);
passwordLabel.setBounds(10,50,80,25);
panel.add(passwordLabel);
userText.setBounds(100,20,165,25);
panel.add(userText);
passwordText.setBounds(100,50,165,25);
panel.add(passwordText);
loginButton.setBounds(10,80,80,25);
loginButton.addActionListener(new UserLoginPage());
panel.add(loginButton);
success.setBounds(10,110,300,25);
panel.add(success);
//success.setText();
frame.setSize(500,500);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(panel);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new UserLoginPage();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked");
}
I think the problem lies with loginButton.addActionListener(new UserLoginPage()); But I might be wrong, do let me know of how to solve the problem, thank you.
There are multiple issues in your program:
panel.setLayout(null); and .setBounds(...). You shouldn't be using null-layouts, as Swing has to deal with multiple PLAFs, OS, screen sizes and resolutions. You might end up with issues like this one. Pixel-perfect layouts might seem like the easiest way to create complex UIs but it's not, it'll just lead you to endless issues. Instead use layout managers or combinations of them.
loginButton.addActionListener(new UserLoginPage()); You're creating a new instance of your program every time, and on every instance of it you're creating a new object because all your code is inside the constructor. Just, don't! It's a recursive call that finally creates a java.lang.StackOverflowError, to solve this use this instead of new UserLoginPage()
frame.setVisible(true); this line should always be the last line in your program, after you've added everything to your JFrame, not before.
With the above recommendations, here's an updated version of your code:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class UserLoginPage implements ActionListener {
// Put all JLabels,Frames and buttons here etc
private JPanel panel;
private JFrame frame;
private JLabel userLabel;
private JLabel passwordLabel;
private JTextField userText;
private JTextField passwordText;
private JButton loginButton;
// Label for successful login
private JLabel success;
// Default Constructor to add the frames and panels etc
public UserLoginPage() {
}
private void createAndShowGUI() {
frame = new JFrame(getClass().getSimpleName());
panel = new JPanel();
panel.setLayout(new GridLayout(0, 2));
userLabel = new JLabel("Username");
passwordLabel = new JLabel("Password");
userText = new JTextField(10);
passwordText = new JPasswordField(10);
loginButton = new JButton("Login");
success = new JLabel("Login Successful");
loginButton.addActionListener(this);
panel.add(userLabel);
panel.add(userText);
panel.add(passwordLabel);
panel.add(passwordText);
panel.add(loginButton);
frame.add(panel);
frame.add(success, BorderLayout.SOUTH);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new UserLoginPage().createAndShowGUI();;
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked");
}
}
You were correct. loginButton.addActionListener(new UserLoginPage()) causes a java.lang.StackOverflowError. The constructor is always calling itself without a base case to default to. You should be passing that very instance of the UserLoginPage as a parameter, not a new instance.
Use this code instead:
loginButton.addActionListener(this);

Why doesn't JPanel get rendered

I am trying to work with grid layout, and im trying to put few panels there that has some data, but nothing gets rendered at all.
Here is the current code that I have:
package main.cache.test;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class ImageView {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ImageView window = new ImageView();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ImageView() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
JFrame frmSpitePicker = new JFrame("Title");
frmSpitePicker.setSize(658, 395);
frmSpitePicker.setResizable(false);
frmSpitePicker.setLocationRelativeTo(null);
frmSpitePicker.getContentPane().setLayout(null);
frmSpitePicker.setVisible(true);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(12, 35, 620, 303);
frmSpitePicker.getContentPane().add(scrollPane);
JPanel panel = new JPanel();
scrollPane.setViewportView(panel);
File file = new File("images/");
panel.setLayout(new GridLayout((file.listFiles().length / 6), 6));
int i = 0;
// getting files name from folder
for (String name : file.list()) {
JPanel panel_1 = new JPanel();
panel_1.setBounds(209, 362, 82, 87);
frmSpitePicker.getContentPane().add(panel_1);
panel_1.setLayout(null);
// create label
JLabel lblNewLabel = new JLabel((i++) + "");
lblNewLabel.setBounds(12, 13, 56, 16);
lblNewLabel.setIcon(new ImageIcon(new ImageIcon("images/" + name).getImage().getScaledInstance(8, 8, 1)));
lblNewLabel.setHorizontalTextPosition(JLabel.CENTER);
lblNewLabel.setVerticalTextPosition(JLabel.BOTTOM);
panel_1.add(lblNewLabel);
// create button
JButton btnNewButton = new JButton("btn");
btnNewButton.setBounds(12, 42, 58, 25);
panel_1.add(btnNewButton);
// add to the panel
panel.add(panel_1);
}
}
}
I don't know what is wrong with this, and why Jpanel when being added, it doesn't get rendered but when adding a JLabel would work.
Thanks in advance!
Using layouts correctly, we can easily get something like this:
import java.awt.*;
import javax.swing.*;
import java.awt.image.*;
public class ImageView {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
ImageView window = new ImageView();
} catch (Exception e) {
e.printStackTrace();
}
});
}
public ImageView() {
initialize();
}
private void initialize() {
int num = 32; // number of images to show..
JFrame frmSpitePicker = new JFrame("Title");
frmSpitePicker.setResizable(false);
JPanel panel = new JPanel(new GridLayout(0, 6));
JScrollPane scrollPane = new JScrollPane(panel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
frmSpitePicker.getContentPane().add(scrollPane);
for (int ii = 1; ii <= num; ii++) {
JPanel panel_1 = new JPanel(new BorderLayout());
// create label
JLabel lblNewLabel = new JLabel(ii + "");
lblNewLabel.setIcon(new ImageIcon(getImage()));
lblNewLabel.setHorizontalTextPosition(JLabel.CENTER);
lblNewLabel.setVerticalTextPosition(JLabel.BOTTOM);
panel_1.add(lblNewLabel, BorderLayout.CENTER);
// create button
JButton btnNewButton = new JButton("btn");
panel_1.add(btnNewButton, BorderLayout.PAGE_END);
// add to the panel
panel.add(panel_1);
// hack to ensure our scroll bar is active
// we require 3 rows to be visible..
if (ii==18) frmSpitePicker.pack();
}
frmSpitePicker.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// Normally we'd call pack() here!
//frmSpitePicker.pack();
frmSpitePicker.setLocationRelativeTo(null);
frmSpitePicker.setVisible(true);
}
java.util.Random r = new java.util.Random();
private BufferedImage getImage() {
int s = 16;
BufferedImage bi = new BufferedImage(
s, s, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.setColor(new Color(
r.nextInt(255), r.nextInt(255), r.nextInt(255)));
g.fillRect(0, 0, s, s);
g.dispose();
return bi;
}
}
Note that I would tend to use a JList for this type of case. The panel_1 would become a renderer for a POJO what encapsulates the label and button. But the button might not be needed, in that a list can have listeners for selection and activation. If that's what the button does, it'd be redundant in a list, and lblNewLabel could replace the entire panel_1.
BTW - please make sure all resources needed, are available to run the code. When it comes to images, we might hot link (load by URL) to images available on the net1 or generate them in the code (as done here).
One way to get image(s) for an example is to hot link to images seen in this Q&A. E.G. This answer hot links to an image embedded in this question.

I can't get image to display

I have a chat client program I am working on and currently I can get the text pane, text input on the left. I can add buttons and change the background color to the right but I can not get an image to display on the right. There is more than one way to skin a cat on this from what I've read but I'm trying to stick with the setup I currently have so I don't have to rewrite everything. I understand the basics of Java (OOP) and how it works. I'm just lost as to how to format image icon and get this image to display. Here is the code: I am compiling with IntelliJ.
package edu.lmu.cs.networking;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.ImageIcon;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ChatClient {
private BufferedReader in;
private PrintWriter out;
private JFrame frame = new JFrame("Chatter");
private JTextField textField = new JTextField(20);
private JTextArea messageArea = new JTextArea(8, 40);
private JPanel panel;
private JButton button;
private JLabel label;
public ChatClient() {
textField.setEditable(false);
messageArea.setEditable(false);
// frame.setSize(500, 500);
// frame.setVisible(true);
frame.getContentPane().add(textField, "South");
frame.getContentPane().add(new JScrollPane(messageArea), "West");
panel = new JPanel();
panel.setBackground(Color.YELLOW);
button = new JButton("Button");
label = new JLabel(new ImageIcon("x.gif"));
panel.add(button);
panel.add(label, BorderLayout.EAST);
frame.add(panel);
frame.pack();
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
out.println(textField.getText());
textField.setText("");
}
});
}
private String getServerAddress() {
return JOptionPane.showInputDialog(frame, "Enter IP Address of the Server:",
"Welcome to the Chatter", JOptionPane.QUESTION_MESSAGE);
}
private String getName() {
return JOptionPane.showInputDialog(frame, "Choose a screen name:", "Screen name selection",
JOptionPane.PLAIN_MESSAGE);
}
private void run() throws IOException {
// Make connection and initialize streams
String serverAddress = getServerAddress();
Socket socket = new Socket(serverAddress, 5910);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
while (true) {
String line = in.readLine();
if (line.startsWith("SUBMITNAME")) {
out.println(getName());
} else if (line.startsWith("NAMEACCEPTED")) {
textField.setEditable(true);
} else if (line.startsWith("MESSAGE")) {
messageArea.append(line.substring(8) + "\n");
}
}
}
public static void main(String[] args) throws Exception {
ChatClient client = new ChatClient();
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.setVisible(true);
client.run();
}
}
Thanks in advance,
-Brandon
You can just change your code as below and it will work. Just tested it on my own computer and it worked.
ImageIcon icon = new ImageIcon(getClass().getResource("x.gif"));
label = new JLabel(icon);
It seems your problem is that you didn't actually loaded the image in. Remember to use a ClassLoader to load the resource files.
You should place 'x.gif' under your project directory or your resource folder(preferred) in order to make this work.
For more details about loading resources, take a look at this link.
If the image is in your projects root directory,then you can access it the directly,similar to what you have done.
If it is inside some folder(say resources folder) in your project structure you need to use getClass().getResource("/resources/x.gif").
You can also create a scaled version of the image,specifying the height and width.It can be done using the sample code below:
ImageIcon icon = new ImageIcon("x.gif");
Image img = icon.getImage();
Image newimg = img.getScaledInstance(30, 20,
java.awt.Image.SCALE_SMOOTH);
icon = new ImageIcon(newimg);
label = new JLabel(icon);

Categories