The image Icon doesn't show up

76 views Asked by At

I'm trying out the different functions of the frame and label, and the image icon doesn't show up. The code runs perfectly, but the image doesn't appear.

import java.awt.Color;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.Border;

public class Label {
public static void main(String[] args) {
    
    ImageIcon icon = new ImageIcon("momos.jpeg");
    
    Border border = BorderFactory.createLineBorder(Color.pink,10);
    
    JLabel label = new JLabel();
    label.setText("MOMAZOS!?!??!?!");
    label.setIcon(image);
    label.setHorizontalTextPosition(JLabel.CENTER);// set text CENTER, RIGHT OR LEFT of image icon
    label.setVerticalTextPosition(JLabel.BOTTOM);//set text TOP, CENTER OR BOTTOM of image icon
    label.setForeground(new Color(0xFF00AA));
    label.setFont(new Font("Times New Roman", Font.ITALIC,40));
    label.setIconTextGap(100);
    label.setBorder(border);
    label.setVerticalAlignment(JLabel.TOP);
    label.setHorizontalAlignment(JLabel.RIGHT);

    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1000,1000);
    frame.getContentPane().setBackground(new Color(0x39FF14));
    frame.add(label);

    }

}

I need for the image to work.

1

There are 1 answers

0
Stanimir On

new ImageIcon("momos.jpeg") searches for a file named momos.jpeg in the current working directory. Are you sure you're starting the application from the directory containing momos.jpeg?

It is generally better to specify URL to a classpath resource, like:

        ImageIcon icon = new ImageIcon(Label.class.getResource("momos.jpeg"));

As long as momos.jpeg is in the same directory/package as the application Label class, it will be located no matter the current working directory.