首页 > 解决方案 > JLabel 上的图像

问题描述

我遇到了一个问题,我正在练习用 Java 编程一个程序,该程序显示带有一些文本和图像的 java GUI 问题是没有显示图像,我不明白为什么这是代码:

import java.awt.*;
import javax.swing.*;
public class DON extends JFrame {
   private JPanel panel;

   public DON() {
        //Impostazioni finestra
        JFrame finestra = new JFrame("Title of page");
        finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        finestra.setLayout(null);
        finestra.getContentPane().setBackground(Color.black);
        finestra.setResizable(false);
        finestra.setVisible(true);
        finestra.setSize(1280, 720);

        //Impostazioni pannello


        JPanel pannello = new JPanel();
        pannello.setBounds(450, 0, 200 , 30);
        pannello.setBackground(Color.black);
        JPanel startPanel = new JPanel();
        startPanel.setBounds(0, 0, 1280 , 30);
        startPanel.setBackground(Color.blue);

        //Jpanel for images
        JPanel imagePanel = new JPanel();
        imagePanel.setBounds(0, 30, 1280, 720);
        //Impostazioni label e ImageIcon
        JLabel label = new JLabel("Image on JLabel!");
        label.setBackground(Color.black);
        label.setForeground(Color.white);

        JLabel imageLabel = new JLabel( "test", new ImageIcon( "2.png" ), JLabel.LEFT );




        /* put every jlabel to jpanel and put my jpanel to a container ; */
        startPanel.add(imageLabel);
        imagePanel.add(imageLabel);
        pannello.add(imagePanel);
        pannello.add(label);

        Container con = finestra.getContentPane();

        con.add(pannello);
        con.add(imagePanel);
        con.add(startPanel);
        }
   public static void main(String args[]) {
      new DON();
   }
}

你能帮助我吗?

标签: javaswing

解决方案


这是由于图像文件的位置存在问题。

要修复它,我建议使用这种方法。

new ImageIcon(this.getClass().getResource("2.png"))

确保在运行之前清理构建,然后重新构建。

或者您可以使用从src文件夹开始的路径

new ImageIcon("src/..../2.png") //put your correct path

编辑:

您必须放在finestra.setVisible(true);构造函数的最后一行DON(),否则会出现黑屏(正如您在已删除的答案中已经提到的)


推荐阅读