有两个问题:
图片路径没有写对,图片在 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)
}
}
下面是一个JAVA显示图片的例子,请参考:package com.tarena.java
import t.Image
import .File
import .IOException
import ageio.ImageIO
import javax.swing.ImageIcon
import javax.swing.JFrame
import javax.swing.JLabel
import javax.swing.SwingUtilities
/**
* 加载显示图象,需要JDK1.5或以上
*/
public class showtu extends JFrame {
public showtu(String bmpFile) {
Image image = null
try {
image = ad(new File(bmpFile))
} catch (IOException ex) {
}
JLabel label = new JLabel(new ImageIcon(image))
add(label)
setDefaultCloseOperation(EXIT_ON_CLOSE)
pack()
}
public static void main(String[] args){
final String fileName = "F:\\456备用\\亮个相.JPG"//换成你要显示的图片
vokeLater(new Runnable(){
public void run(){
new showtu(fileName).setVisible(true)
}
})
}
}