Java图片显示不出来,怎么解决

看图

有两个问题:

    图片路径没有写对,图片在 src 下,图片路径应是 src/海洋.png,正确的写法应是 image = new ImageIcon("src/海洋.png")

    image = new ImageIcon("src/海洋.png") 应该放在 label = new JLabel(image); 前面。

如下例:

import javax.swing.*;

class JPanelDemo extends JPanel {

JLabel label;
JTextField text;
JButton button;
ImageIcon image;

public JPanelDemo() {

image = new ImageIcon("src/test.png");
label = new JLabel(image);
text = new JTextField(20);
button = new JButton("确定");

add(label);
add(text);
add(button);
}
}

public class App extends JFrame {

public App() {

this.setSize(500, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.add(new JPanelDemo());
}

public static void main(String[] args) {
new App().setVisible(true);
}
}

追问

你们两人的回答都是正确的,我不知道该采纳谁了,就按回答的时间先后采纳了,还是谢谢你~

温馨提示:内容为网友见解,仅供参考
第1个回答  2018-07-22
你把image=new ImageIcon("海洋.png");这一语句放到label=new JLabel(image);前面,public JPanelDemo()函数里面
再把image=new ImageIcon("海洋.png");改成image=new ImageIcon("src/海洋.png");因为你把图片放在了src文件夹里面
改完上述问题,你的图片就应该能显示出来了.本回答被提问者采纳
相似回答