簡體   English   中英

如何使用JFileChooser在JFrame中上傳和顯示圖像

[英]how to upload and display image in JFrame using 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();
        }
    }
}

我自己解決了。 我選擇了一個圖像並在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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM