Use app×
QUIZARD
QUIZARD
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
204 views
in JAVA by (178k points)
How do you display an image in a JLabel in Java?

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

To display an image in a JLabel in Java, you need to create an ImageIcon object that represents the image and set it as the icon of the label using the setIcon() method. Here is an example:

import javax.swing.*;
import java.awt.*;

public class LabelImageExample {
    public static void main(String[] args) {
        // Create a new JFrame
        JFrame frame = new JFrame("Label Image Example");

        // Load an image from a file
        ImageIcon icon = new ImageIcon("image.jpg");

        // Create a new JLabel with the image icon
        JLabel label = new JLabel(icon);

        // Add the label to the frame
        frame.add(label);

        // Set the frame's size and make it visible
        frame.setSize(300, 200);
        frame.setVisible(true);
    }
}
 

In the above example, the ImageIcon constructor is used to create an ImageIcon object that represents the image "image.jpg". Then, a new JLabel is created with the image icon using the JLabel(ImageIcon) constructor. Finally, the label is added to the frame and the frame is displayed.

Note that the path to the image file should be relative to the location of your Java file, or you can use an absolute path if needed. Additionally, make sure the image file is in a compatible format that can be loaded by ImageIcon, such as PNG, JPEG, or GIF.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...