2016-11-29 73 views
-3

調用此方法,以我的主窗體類,將選擇該文件,但難道不顯示圖像.. 片段圖像不顯示在我的JLabel

p

ublic class imageSending { 

public static File setpix(File k) throws IOException { 


    //  throw new UnsupportedOperationException("Not supported yet."); 


     JFileChooser choose=new JFileChooser(); 
     choose.setDialogTitle("Browse Image"); 
     choose.setFileSelectionMode(2); 
     int a=choose.showOpenDialog(null); 
     if (a==0){ 
     File file=new File(choose.getSelectedFile().getPath()); 

      BufferedImage img=ImageIO.read(file); 


      ImageIcon o = new ImageIcon(img.getScaledInstance(300, 300, 300)); 
    }return k; 
    } 
} 
+1

沒有什麼在該代碼,將顯示圖像。如果您有其他圖像顯示代碼,請顯示它,並請詳細解釋您的問題。 –

+0

還有,1)JFileChooser,'getSelectedFile()'返回一個文件 - 爲什麼你通過獲取路徑使它變得更復雜,然後得到一個帶路徑的文件? 2)你回來的是什麼? 3)你正在創建一個BufferedImage,然後用這個創建一個ImageIcon,但對你創建的圖標無所作爲 - 爲什麼? –

+0

啊,我看到'k'是參數 - 爲什麼該方法甚至採用參數,然後簡單地返回它?就好像方法主體中的所有代碼都只是忙於工作而程序將被忽略,所以這變得更加令人困惑 - 請通過解釋此代碼應該做什麼來幫助我們解決問題。 –

回答

0

這是上面簡單地說你的方法

public static File setpix(File k) throws IOException { 
    // do lots of busy work that accomplishes nothing 
    // and then return k: 
    return k; 
} 

就是這樣。如果你想在GUI中實際顯示圖像,你應該改爲:

  1. 獲取從JFileChooser獲得的文件。只需撥打getSelectedFile()無需將其轉換爲一個字符串,然後得到一個文件
  2. 從文件中獲取您的BufferedImage並將其轉換爲一個ImageIcon
  3. 有方法返回的ImageIcon
  4. 別的地方,請撥打方法並通過setIcon(...)將Icon插入到JLabel中。

例如(代碼未測試)

public Icon getIcon() throws IOException { 
    JFileChooser choose = new JFileChooser(); 
    choose.setDialogTitle("Browse Image"); 
    // choose.setFileSelectionMode(2); // no "Magic" numbers 
    choose.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); // Better 
    int a = choose.showOpenDialog(null); 
    if (a == 0) { 
     File file = choose.getSelectedFile(); 
     BufferedImage img=ImageIO.read(file); 
     Icon o = new ImageIcon(img.getScaledInstance(300, 300, 300)); 
     return o; 
    } else { 
     // throw an exception here 
     // or return null if that's what the program expects 
     // or return some "default" icon 
    } 
} 

然後別處:

Icon icon = getIcon(); 
myLabel.setIcon(icon); 

// or 
JOptionPane.showMessageDialog(null, icon);