2

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();
    }
}
Mert Karakas
  • 178
  • 1
  • 4
  • 22
  • 1
    `Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();` **No!** This does not account for the task-bar. Instead use [`setExtendedState(Frame.MAXIMIZED_BOTH )`](https://docs.oracle.com/javase/8/docs/api/java/awt/Frame.html#setExtendedState-int-). – Andrew Thompson May 14 '15 at 04:07

2 Answers2

6

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();
copeg
  • 8,290
  • 19
  • 28
  • Don't forget to discourage calling `setSize` on a JFrame. Calling `setPreferredSize` on the content pane is generally better. – Radiodef May 13 '15 at 21:57
  • And [Initial Threads](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html) – MadProgrammer May 13 '15 at 23:56
  • Thank you for the great support. So i have my ImageIcon, if it is smaller than the screen, how can i make it fit to screen? – Mert Karakas May 14 '15 at 13:16
  • 1
    You can [resize](http://stackoverflow.com/questions/6714045/how-to-resize-jlabel-imageicon) the ImageIcon. – copeg May 14 '15 at 16:47
0

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

QuickSilver
  • 3,915
  • 2
  • 13
  • 29