0

在将图像设置为面板时,我遇到了 NetBeans 资源管理问题:

这是我不工作的代码:

try {
    BufferedImage myPicture = ImageIO.read(new File("images/3D.jpg"));
    JLabel picLabel = new JLabel(new ImageIcon(myPicture));
    pnlMain.add(picLabel); //the main and only pannel made by matisse is called pnlMain
} catch (IOException e) {
    JOptionPane.showMessageDialog(this, "Cannot set image");
}

名为“images”的文件夹位于 MAIN 项目文件夹中。有几个文件夹:build、nbproject、src 和“images”。
我遇到的问题是程序运行但它没有设置图像......

有人建议我用这个代码在不同的包中创建另一个类:

public class PanelImage extends JPanel{
private Image imag;

public PanelImage(Image img){
    if(imagen != null){
        this.imagen = img;
    }
}

@Override
public void paint(Graphics g){
    g.drawImage(img, 0,0, getWidth(), getHeight(), this);
    setOpaque(false);
    super.paint(g);
}
}

但我找不到合适的方法来实现它......

4

1 回答 1

2

为你的ImagePanel班级

  1. super.paint[Component] 所有其他东西之前。
  2. 不要覆盖paint,而是paintComponent
  3. 不要在paintComponent方法 ie中设置属性setOpaque()。旁边,JPanel默认不透明
  4. 覆盖getPreferredSize()面板上的绘画

用于加载图像

养成不从文件系统读取图像的习惯,除非应用程序仅特定于的机器。

而是从类路径中读取并通过将图像打包到类路径中来使图像成为资源

  1. 更改文件结构

    ProjectRoot
             src
                images
                     3D.jpg
    
  2. 从类路径中读取。用于ImageIO确保您的路径正确。如果无效,会抛出异常

    URL url = getClass().getResource("/images/3D.jpg"); 
    Image image = ImageIO.read(url);
    

对于 Netbeans GUI 构建器

您可以使用设计工具设置标签图标

  1. 从导航器或设计视图中选择您的标签。
  2. 转到右侧的属性窗口并找到该属性icon
  3. 单击属性右侧的省略号按钮,将出现一个对话框。
  4. 找到您的图像并选择确定(确保您的图像在 src 的包中)

查看相关的,也许是相关的

于 2014-05-01T14:51:09.577 回答