Mert Karakas
Mert Karakas

Reputation: 178

JLabel not showing in JFrame

I have searched this problem in stackoverflow,however, i couldn't resolve my problem. So I have a simple image that I assign to a JLabel and add that label in to JFrame but it doesn't appear. Any help? PS: If the image that I set is not same with the screen size, how can I "readjust" or fit it in as in rescale?

package electricscreen;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;

/**
 *
 * @author MertKarakas
 */
public class ElectricScreen extends JFrame{

    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int width = (int) screenSize.getWidth();
    int height = (int) screenSize.getHeight();
    private String url = "el.jpg";
    private ImageIcon img;
    private JLabel lbl;

    public ElectricScreen() {
        setLayout(new FlowLayout());
        setSize(width, height);
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        img = new ImageIcon(getClass().getResource("/electricscreen/el.jpg"));
        lbl = new JLabel(img);
        add(lbl);
        lbl.setVisible(true);    
    }
    public static void main(String[] args){
        ElectricScreen e = new ElectricScreen();
    }
}

Upvotes: 2

Views: 7097

Answers (2)

Bhupinder Singh
Bhupinder Singh

Reputation: 9

always add the setvisible(true); of frame at the end of constructor

Upvotes: 0

copeg
copeg

Reputation: 8348

You are adding Components to an already visible JFrame. Either add the Components before calling setVisible (preferred - you may also want to call pack to lay out the components as well)

add(lbl);
pack();
setVisible(true);

or call revalidate on the JFrame after adding the Component(s)

setVisible(true);
add(lbl);
revalidate();

Upvotes: 6

Related Questions