java - 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();
}
}
你能帮助我吗?
解决方案
这是由于图像文件的位置存在问题。
要修复它,我建议使用这种方法。
new ImageIcon(this.getClass().getResource("2.png"))
确保在运行之前清理构建,然后重新构建。
或者您可以使用从src文件夹开始的路径
new ImageIcon("src/..../2.png") //put your correct path
编辑:
您必须放在finestra.setVisible(true);
构造函数的最后一行DON()
,否则会出现黑屏(正如您在已删除的答案中已经提到的)
推荐阅读
- css - Safari CSS 问题(Z-index?变换?)
- http - JMeter:如何使用 BeanShell 发送 HTTP GET 请求
- typescript - 如何为使用括号表示法访问的对象指定字符串类型?
- android - OpenCV JavaCameraView 显示空白/黑屏
- python - 使用我通过 pandas.to_sql 创建的 Flask Sqlalchemy 访问类/模型
- azure - 如何将文件从 Azure 存储文件共享复制到发布管道代理
- sql - Charindex 返回额外的字母
- wpf - 组合框下拉列表中的项目全部为空
- html - 如何在 Outlook 2016+ 的电子邮件中插入 HTML(包括图像)
- javascript - 我可以使用 jspdf 将不同方向的 pdf 组合在一起吗?