开发者

How to put an image icon, which is taken with JFileChooser, on a label?

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?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜