Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用JFileChooser在JFrame中上载和显示图像_Java_Jfilechooser - Fatal编程技术网

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

Java 如何使用JFileChooser在JFrame中上载和显示图像,java,jfilechooser,Java,Jfilechooser,我需要上传并在JFrame中显示使用JFileChooser选择的图像(即用户希望设置其个人资料图片)。。我该怎么做 以下是我选择文件的代码: private void UploadImageActionPerformed(java.awt.event.ActionEvent evt) { int returnVal = fileChosser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION)

我需要上传并在
JFrame
中显示使用
JFileChooser
选择的图像(即用户希望设置其个人资料图片)。。我该怎么做

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

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

我自己解决了。我选择了一个图像并显示在
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();
    }
}

由于您已将您的方法命名为UploadImageActionPerformed,请阅读以下内容。方法名称应在开头用小写字符书写。