1

I am making a project in java where an image pops up in an if statement. I have looked online for about an hour and anything I found gave me an error that I had no idea how to fix. Heres an example, Java, how can I popup a dialog box as only an image?. After using the code suggested by whiskeyspider and after importing java.awt.image.BufferedImage; javax.swing.ImageIcon; javax.swing.JLabel; I got an error at ImageIo and File on the first line. If you can help me in anyway please let me know I am using netbeans and I have javax.swing.JOptionPane;imported already so if that helps there you go (sorry for sounding like I was to lazy to research things, for I am only 12 and my attention span isn't the greatest)

Community
  • 1
  • 1

2 Answers2

3

Here is what you are looking for. It will show you how to create a dialog box with an image only.

However if you do not wish to go read it there, I have entered the code snippet below for you to have a look at.

(Tried and tested)


import javax.swing.JOptionPane; //imports
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import java.awt.Toolkit;
import java.awt.Dimension;

public class ProjectileSim{

    public static void main(String[] args){
        JFrame f = new JFrame(); //creates jframe f

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); //this is your screen size

        f.setUndecorated(true); //removes the surrounding border

        ImageIcon image = new ImageIcon("IMAGEURL.jpg"); //imports the image

        JLabel lbl = new JLabel(image); //puts the image into a jlabel

        f.getContentPane().add(lbl); //puts label inside the jframe

        f.setSize(image.getIconWidth(), image.getIconHeight()); //gets h and w of image and sets jframe to the size

        int x = (screenSize.width - f.getSize().width)/2; //These two lines are the dimensions
        int y = (screenSize.height - f.getSize().height)/2;//of the center of the screen

        f.setLocation(x, y); //sets the location of the jframe
        f.setVisible(true); //makes the jframe visible
    }
}

This will solve you problem. Please remember to paste the image you want to be displayed within the compiling folder, so that the "ImageIcon" can find it easily. Also remember to specify the correct picture extension! (i.e. .jpg, .png, .gif)

All the best :)

Do let me know of the outcome.

Good luck!

Community
  • 1
  • 1
TejjD
  • 2,571
  • 1
  • 17
  • 37
1

To fix, You should add

import javax.imageio.ImageIO;
import java.io.File;

To the top of your file

You may also need to add

import java.io.IOException;
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80