-->

ImageIcon method not working for all images

2020-04-21 07:56发布

问题:

I'm trying to get a jpeg to display on a JFrame and I'm noticing that some image files work while others do not. I'm using Eclipse and all of my images are in the project's root dir. When I run the Debugger and it hits my breakpoint it reports the imageheight and imagewidth as -1 on the images that will not display. It reports the correct values on the images that do display.

at first I thought it had something to do with the image sizes but after playing with resolutions in mspaint I've realized that this is not the case.

Here is my code so far:

import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import javax.imageio.*;
import java.io.File;

public class icon {

    public static void main(String[] args) {
        constructVNCForm();
    }

public static void constructVNCForm() {
        //Vars for GUI and essential layout code
        final JFrame frame = new JFrame("This should be on top");
        frame.setSize(800, 640);
        Container content = frame.getContentPane();
        frame.setVisible(true);

        //image code here:
        ImageIcon image = new ImageIcon("trial4.jpg");
        //ABOVE WORKS

        JLabel imageLabel = new JLabel(image);
        FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
        //add the image to the frame
        content.add(imageLabel);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        content.setLayout(flow);
    }
}

Have any of you had any issues with ImageIcons? all of my jpegs are various sizes under 300x300. I'm kind of new to Java so if you have any suggestions on my code please advise.

回答1:

Tested with few various size of images, the following works fine. Usually setVisible(true) method should be called at the end.

public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("This should be on top");
                frame.setSize(800, 640);
                ImageIcon image = new ImageIcon("someImage.jpg");
                JLabel imageLabel = new JLabel(image);
                FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
                frame.getContentPane().add(imageLabel);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(flow);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }