Java Can';在扩展的JPanel类中看不到ImageIcon

Java Can';在扩展的JPanel类中看不到ImageIcon,java,swing,awt,Java,Swing,Awt,我有一个扩展JPanel的类,我希望它显示一个ImageIcon。有些事情似乎无法解决。找到map.png,当我在类中打印出它的大小时,它是正确的。另外,我将面板设为黑色,这样我知道面板可以工作,但图像图标不能工作 但是,当我将相同的代码从TestPanel.java放到GUI.java的构造函数中时,ImageIcon会起作用 有人能告诉我为什么ImageIcon在TestPanel.java中不起作用,但在GUI.java中起作用吗 这是我的密码 TestPanel.java public

我有一个扩展JPanel的类,我希望它显示一个ImageIcon。有些事情似乎无法解决。找到map.png,当我在类中打印出它的大小时,它是正确的。另外,我将面板设为黑色,这样我知道面板可以工作,但图像图标不能工作

但是,当我将相同的代码从TestPanel.java放到GUI.java的构造函数中时,ImageIcon会起作用

有人能告诉我为什么ImageIcon在TestPanel.java中不起作用,但在GUI.java中起作用吗

这是我的密码

TestPanel.java

public class TestPanel extends JPanel {
    
    public static JLabel map = new JLabel();

    public TestPanel() {
        this.setLayout(null); //to prevent icon from taking the whole screen
        this.setVisible(true); //make frame visible
        this.setBounds(0, 0, 100, 100);
        
        this.setBackground(new Color(0,0,0));
        
        Image imageToScale = new ImageIcon("map.png").getImage();
        double scale = .9; //scale
        int x = (int) (imageToScale.getWidth(null) * scale); //leave image observer as null because we know that the image is loaded
        int y = (int) (imageToScale.getHeight(null) * scale);
        Image scaledImage = imageToScale.getScaledInstance( x, y, java.awt.Image.SCALE_SMOOTH); //scale the image
        ImageIcon image = new ImageIcon(scaledImage); //case the image into an image icon
        
        this.setBounds(0, -4, image.getIconWidth(), image.getIconHeight()); //set position and size of panel to the size of the image. -4 on the Y position because it was not aligned with the top
     
        map.setIcon(image); //set icon for map label
        this.add(map); //add label to panel
    }
}
GUI.java

public class GUI extends JFrame {
    
    public static JPanel problemPanel = new JPanel(); //panel where the points and path will be displayed
    public static JLabel map = new JLabel();
    
    public static TestPanel test = new TestPanel();
    
    public GUI() {
        this.setLayout(null); //to prevent icon from taking the whole screen
        
        this.add(test);
        
        //Frame
        this.setVisible(true); //make frame visible
        this.setSize(1200,1000); //set frame size
        this.setTitle("Travelling Apache Pizza Delivery Driver Problem (TAPDDP)"); //set title of panel
        this.setDefaultCloseOperation(this.EXIT_ON_CLOSE); //terminates program when frame is closed
        this.setLocationRelativeTo(null); //open frame in the middle of the screen
        this.setResizable(false); //prevent resizing of GUI
        

    }

}

我通过删除
this.setLayout(null)修复了代码
测试面板
类中。

您确定正确读取了图像吗?使用ImageIO读取图像。JFrame setVisible方法应该是构建整个GUI之后的最后一个方法调用。Oracle教程将向您展示构建Swing GUI的正确方法。跳过Netbeans部分。@GilbertLeBlanc感谢您的帮助。我通过删除此.setLayout(null)修复了代码;在我的TestPanel.java classPlus中,它不仅可以自己解决这个问题,还可以报告修复程序以帮助未来的读者:)请在网站允许的情况下,让其他人在将来更容易找到。