static String path=System.getProperty("user.dir")+"\\WebRoot\\Img\\"
public static ImageIcon add(String ImageName){
ImageIcon icon = new ImageIcon(path+ImageName)
return icon
}
}
先定义一个方法,然后下面调用,注意把图片放在项目的WebRoot\\Img的目录下即可
final JLabel label = new JLabel()ImageIcon loginIcon=CreateIcon.add("backImg.jpg")
label.setIcon(loginIcon)
// 不加包,图片跟类文件在一个目录,命令行下编译执行就行了
// 如果建工程,图片放到工程根目录
import java.awt.Container
import java.awt.FlowLayout
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.ImageIcon
import javax.swing.JButton
import javax.swing.JFrame
import javax.swing.JLabel
import javax.swing.JPanel
public class Student extends JFrame {
public Student() {
init()
}
private void init() {
final Container c = getContentPane()
final JLabel imgLabel = new JLabel()
JButton btnPic = new JButton("换背景图片")
btnPic.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon img = new ImageIcon(System.getProperty("user.dir") + "\\a.png")
imgLabel.setIcon(img)
imgLabel.setBounds(0, 0, img.getIconWidth(), img.getIconHeight())
}
})
((JPanel)getContentPane()).setOpaque(false)
getLayeredPane().add(imgLabel, new Integer(Integer.MIN_VALUE))
setLayout(new FlowLayout())
add(btnPic)
setSize(500, 500)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
}
public static void main(String[] args) {
new Student().setVisible(true)
}