得到未知的错误

时间:2010-07-27 22:50:27

标签: java

好的,这是作业:

创建一个简单的图片查看器,允许用户单击一个按钮,然后从文件系统中选择一个图像,并将该图像显示在JLabel中。

这是我的代码:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class Main implements ActionListener{

 JButton openButton;
 JFileChooser fc;
 File fileName;
 JLabel image;
 JFrame frame;

 public Main(){
  frame = new JFrame("Picture Viewer");
  frame.setBounds(100,100,750,750);
  frame.setLayout(null);
  frame.setVisible(true);

  openButton = new JButton("Choose an image to display...");
  openButton.setBounds(0,0,750,50);
  openButton.setLayout(null);
  openButton.setVisible(true);
  frame.add(openButton);
  openButton.addActionListener(this);
 }

 public static void main(String[] args){
  Main m = new Main();
 }

 @Override
 public void actionPerformed(ActionEvent arg0) {
  fc = new JFileChooser();

  fc.showOpenDialog(null);
  fileName = fc.getSelectedFile();
  ImageIcon icon = new ImageIcon(fileName.getPath());
  image = new JLabel(icon);
  image.setBounds(15,65,720,655);
  image.setLayout(null);
  image.setVisible(true);
  frame.add(image);
 }
}

这是我得到的错误:

sun.awt.image.ImageFormatException: Unsupported color conversion request
 at sun.awt.image.JPEGImageDecoder.readImage(Native Method)
 at sun.awt.image.JPEGImageDecoder.produceImage(Unknown Source)
 at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
 at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
 at sun.awt.image.ImageFetcher.run(Unknown Source)

1 个答案:

答案 0 :(得分:1)

可能是你的jpeg使用的是CMYK颜色模型而不是RGB。 This thread有一些处理这个问题的提示。

要验证这一点,请尝试另一种您知道为RGB的JPEG。

编辑:您没有使用框架布局。而不是

frame.setLayout(null);

frame.setLayout(new BorderLayout());

然后,在创建图像标签时,将标签大小调整为图标的大小。 E.g。

image.setWidth(icon.getIconWidth());
image.setHeight(icon.getIconHeight());
frame.add(image, BorderLayout.CENTER);