有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我看不到图片或按钮?

我试图在图片上添加一个按钮。但既看不到按钮也看不到图像。为什么?在IDE调用initComponents方法之后,我从构造函数调用这个方法

public void initD() {
    try {
        BufferedImage myPicture = ImageIO.read(new File("C:\\Users\\user\\Documents\\NetBeansProjects\\JavaApplication1\\src\\javaapplication1\\meaning.JPG"));
        JLabel picLabel = new JLabel(new ImageIcon(myPicture));
        JButton b = new JButton("Press me");
        jPanel1.add(picLabel);
        jPanel1.add(b);
        System.out.println("last statement");
    }catch(Exception exc) {
        exc.printStackTrace();
    }
}

我只将帧视为输出


共 (1) 个答案

  1. # 1 楼答案

    我不知道你使用的是哪种布局,但是你应该像这样实现button.setIcon();

    public void initD() {
        JButton button = new JButton("Press me");
        try {
            BufferedImage myPicture = ImageIO.read(new File("C:\\Users\\user\\Documents\\NetBeansProjects\\JavaApplication1\\src\\javaapplication1\\meaning.JPG"));
            JLabel picLabel = new JLabel(new ImageIcon(myPicture));
    
            button.setIcon(new ImageIcon(myPicture));
    
            System.out.println("last statement");
        }catch(Exception exc) {
            exc.printStackTrace();
        }
    }
    
    <> P>此外,您可能需要考虑您的图像资源,这一实施可能是有用的;

    ImageIO.read(getClass().getResource("resources/meaning.JPG")));