【问题标题】:Matisse properly setting image to panel马蒂斯将图像正确设置为面板
【发布时间】:2014-06-18 01:23:48
【问题描述】:

我在将图像设置为面板时遇到了 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);
}
}

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

【问题讨论】:

    标签: java image swing netbeans matisse


    【解决方案1】:

    为您的ImagePanel 班级

    1. super.paint[Component] 所有其他的东西之前。
    2. 不要覆盖paint,而是覆盖paintComponent
    3. 不要在paintComponent 方法中设置属性,即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 的包中)

    relatedmaybe related

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多