如何使用JFileChooser在JFrame中上传和显示图像

时间:2012-11-22 16:38:44

标签: java jfilechooser

我需要在JFileChooser中上传并显示使用JFrame选择的图像(即用户想要设置他/她的个人资料图片)..我应该怎么做?

以下是我选择文件的代码:

private void UploadImageActionPerformed(java.awt.event.ActionEvent evt) {
    int returnVal = fileChosser.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fileChosser.getSelectedFile();
        // What to do with the file
        // I want code for this part
        try {
            //code that might create an exception 
        } 
        catch (Exception e1) {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:5)

我自己解决了。我选择了一张图片并显示在JLabel

这是我的代码:

private void uploadImageActionPerformed(java.awt.event.ActionEvent evt) {                                            
    JFileChooser filechooser = new JFileChooser();
    filechooser.setDialogTitle("Choose Your File");
    filechooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    // below code selects the file 
    int returnval = filechooser.showOpenDialog(this);
    if (returnval == JFileChooser.APPROVE_OPTION)
    {
        File file = filechooser.getSelectedFile();
        BufferedImage bi;
        try {
            // display the image in a Jlabel
            bi = ImageIO.read(file);
            jLabel1.setIcon(new ImageIcon(bi));
        } catch(IOException e) {
           e.printStackTrace(); // todo: implement proper error handeling
        }
        this.pack();
    }
}