views:

44

answers:

2

Ok so here is the assignment:

Create a simple picture viewer that will allow the user to click a button and then select an image from the file system and have that image displayed in a JLabel.

Here is the code I have:

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

and here is the error I'm getting:

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)
A: 

It could be that your jpeg is using the CMYK color model rather than RGB. This thread has some tips on dealing with that.

To verify this, try another JPEG that you know to be RGB.

EDIT: you are not using a layout with your frame. rather than

frame.setLayout(null);

try

frame.setLayout(new BorderLayout());

Then, when you create the image label, size the label to the size of the icon. E.g.

image.setWidth(icon.getIconWidth());
image.setHeight(icon.getIconHeight());
frame.add(image, BorderLayout.CENTER);
mdma
I tried another image, there isnt an error this time, however the image is not being displayed on the JFrame. Could you possible reference my above code to try and find the errant code?
Chris V.
so now the image is displaying, but the jframe resizes all the way down as small as possible. I dont know whats causing this or how to stop it from happening.
Chris V.
A: 

got it working. thanks

Chris V.