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)
}
})
}
}
有两个问题:
图片路径没有写对,图片在 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)、判断文件的扩展名是否是要求的图片扩展名。这种判断是用得比较多的一种方式,如果这上传的文件是shell、php或者jsp,那你的网站基本上可以说就在别人的手里面了。2)、根据文件的前面几个字节,即常说的魔术数字进行判断,不同文件类型的开头有几个字节。