如何显示由JFileChooser在java中选择的图像(所有主要格式)

时间:2012-06-02 20:59:32

标签: java image jfilechooser javax.imageio

我正在开发一个图片编辑应用,所以想要显示JFileChooser选择的图片,那么最好的方法就是显示所有格式jpgpnggifOpenButton用于调用filechooser。

private void OpenActionPerformed(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 :(得分:1)

最简单的方法可能是从文件的URL(或从文件的内容中作为字节或文件名)创建ImageIcon,并将此ImageIcon包装到JLabel中:

iconLabel.setIcon(new ImageIcon(file.toURI().toURL()));

但是如果你的应用程序应该编辑图像,那么你将不得不学习如何操作java.awt.Image实例,而最简单的方法是不够的。