Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 马蒂斯正确设置面板的图像_Java_Image_Swing_Netbeans_Matisse - Fatal编程技术网

Java 马蒂斯正确设置面板的图像

Java 马蒂斯正确设置面板的图像,java,image,swing,netbeans,matisse,Java,Image,Swing,Netbeans,Matisse,我在将映像设置为pannel时遇到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

我在将映像设置为pannel时遇到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");
}
名为“图像”的文件夹位于主项目文件夹中。有几个文件夹: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);
}
}

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

用于您的
图像面板

  • super.在所有其他东西之前先绘制[组件]
  • 不要覆盖
    paint
    ,而是覆盖
    paintComponent
  • 不要在
    paintComponent
    方法ie
    set不透明()
    中设置属性。此外,
    JPanel
    默认为不透明
  • 覆盖
    getPreferredSize()
  • 用于加载图像

    养成不从文件系统读取图像的习惯,除非应用程序只针对您的机器

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

  • 更改文件结构

    ProjectRoot
             src
                images
                     3D.jpg
    
  • 从类路径读取。使用
    ImageIO
    确保路径正确。如果无效,将引发异常

    URL url = getClass().getResource("/images/3D.jpg"); 
    Image image = ImageIO.read(url);
    
  • 用于Netbeans GUI构建器

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

  • 从导航器或设计视图中选择标签
  • 转到右侧的属性窗口,找到属性
    图标
  • 单击属性右侧的椭圆按钮,将显示一个对话框
  • 找到您的图像并选择OK(确保您的图像位于src中的包中)

  • 看到和