【问题标题】:Setting an image on a JLabel by opening the image from a Opendialog box通过从 Opendialog 框中打开图像在 JLabel 上设置图像
【发布时间】:2011-11-16 10:53:29
【问题描述】:

我正在尝试通过浏览系统文件来在 JLabel 上设置 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 
      }

【问题讨论】:

  • @heisenbug - 我也试过了,但没有结果,即使是白色的小图标也停止替换标签。现在什么都没有发生,只有字段显示打开的文件的路径。
  • 我之前的回答错了,抱歉。我删除了它。

标签: java image swing jlabel


【解决方案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 文档说:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    相关资源
    最近更新 更多