通过打开Opendialog框中的图像在JLabel上设置图像

时间:2011-11-16 10:53:30

标签: java image swing jlabel

我试图通过浏览系统文件来设置JGabel上的JPG格式图像。下面给出了代码。在运行此代码时,我得到一个非常小的白色图标,代替放在表单上的大标签。 如何将原始图像放在标签上。请帮我解决这个问题。 我在NetBeans 7.0上使用java语言。

//Code of the browse button that performs the action
private void BrowseButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                              
       final JFileChooser fc = new JFileChooser();
      int r = fc.showOpenDialog(CompareFaces.this);

      fc.setFileSelectionMode(fc.FILES_AND_DIRECTORIES);

      if (r == JFileChooser.APPROVE_OPTION) {
      String name = fc.getSelectedFile().getAbsolutePath();
      BrowseField1.setText(name);

      File f = new File(name);
      Icon icon = fc.getIcon(f);
      Preview1.setIcon(icon);  // Preview1 is the name of my JLabel 
      }

1 个答案:

答案 0 :(得分:1)

如果您尝试以原始格式显示图像,请尝试此操作,它对我有用:

Preview1.setIcon(new javax.swing.ImageIcon(name));

而不是:

File f = new File(name);
Icon icon = fc.getIcon(f);
Preview1.setIcon(icon);  // Preview1 is the name of my JLabel 

JFileChooser.getIcon文档说:

  

返回此文件或文件类型的图标,具体取决于   系统

这意味着您发布的代码将显示图像类型图标 在您的操作系统配置中定义,而不是图像本身。