ImageIcon方法不适用于所有图像

时间:2012-12-09 13:59:17

标签: java image swing imageicon

我正在尝试将Jpeg显示在JFrame上,并且我注意到某些图像文件有效,而有些则没有。我正在使用Eclipse,我的所有图像都在项目的根目录中。当我运行调试器并且它到达我的断点时,它会在不显示的图像上报告imageheight和imagewidth为-1。它会在显示的图像上报告正确的值。

起初我认为它与图像尺寸有关但在使用mspaint中的分辨率后,我意识到情况并非如此。

到目前为止,这是我的代码:

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);
    }
}

你们有没有与ImageIcons有任何问题?我的所有jpeg都是300x300以下的各种尺寸。我对Java很陌生,所以如果你对我的代码有任何建议,请告知。

1 个答案:

答案 0 :(得分:2)

使用少量不同大小的图像进行测试,以下工作正常。通常应该在最后调用setVisible(true)方法。

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);
            }
        });
    }