
可以先使用createElement()方法创建一个img元素,并向img元素的src属性赋图片的URL地址值。然后使用appendChild()方法将img元素添加到指定dom对象中即可。
参数:nodename:必须。创建元素的名称。
用Swing包下的ImageIcon类就可以实现,比如在一个按钮中添加一张图片,就可以用以下代码实现:ImageIcon imageicon =new ImageIcon(String s)JButton b=new JButton(imageicon)其中参数s是所要添加图片的路径(绝对路径或相对路径)和名字。如想添加D盘下的图片1.jpg,就可以将上面改成:ImageIcon imageicon =new ImageIcon("D:\1.jpg")JPanel jp=new JPanel()://定义面板并初始化
Icon iocn=new ImageIcon("C:/My Documents/tupian.jpg")//定义图片并初始化,写上图片的绝对路径
JLabel jl=new JLabel(icon)://把图片放在标签上
jp.add(jl)//往面板上添加标签注意:面板JPanel不能之间添加图片iocn,icon需要放在标签JLabel上,才能在JPanel上显示
import java.awt.event.*
import javax.swing.*
public class MainJFrame extends JFrame{
private ImageJPanel ip
public MainJFrame() {
initial()
}
public void initial()
{
ip=new ImageJPanel()
this.setTitle("Demo")
this.setSize(400,300)
this.setResizable(false)
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
this.setLocationRelativeTo(this)
Container c=this.getContentPane()
c.setLayout(null)
ip.setBounds(0,0,this.getWidth(),this.getHeight())
c.add(ip)
this.setVisible(true)
}
public static void main(String[] args)
{
new MainJFrame()
}
}
class ImageJPanel extends JPanel
{
private ImageIcon ii
public ImageJPanel()
{
//bk.jpg是指背景图片的名称 ii=new ImageIcon("bk.jpg")
}
//绘制背景图片 public void paintComponent(Graphics g)
{
super.paintComponent(g)
g.drawImage(ii.getImage(),0,0,this)
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)