views:

19

answers:

2

Hey there, i have just tried to put an image that is taken with JFileChooser on a label; but it did not work the way i want to. Here is the code that i tried;

import java.io.*;
import javax.swing.*;
import java.util.*;


public class Main {

    public static void main(String[] args) {


        JFileChooser chooser = new JFileChooser();

        JFrame frame = new JFrame("My Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();

        chooser.showOpenDialog(null);

        File file = chooser.getSelectedFile();
        ImageIcon icon = new ImageIcon(file.getName());
        JLabel label = new JLabel(icon);

//        JLabel label2 = new JLabel("try try catch it");

        panel.add(label);
//        panel.add(label2);


        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);


    }

}

Any suggestion?

+1  A: 

Close.

You will notice that when you look at file.getName() you see that it will give you the name of the file that you selected. You're looking for the path instead of the name of the file.

See if you can look in the API for File for how to get the path.

KLee1
+1  A: 

You should be using file.getPath() instead of file.getName(). You should also be doing your painting work in the EDT.

akf