java awt怎么给按钮添加图片

java awt怎么给按钮添加图片,第1张

JFrame j = new JFrame()

JButton b = new JButton() // // 实例化按钮对象,并且设置按钮上显示图片

b.setIcon(new ImageIcon("f://1.jpg")) ////1.jpg是要添加的图片

j.add(b)

j.setSize(300, 200)

j.setVisible(true)

代码及说明参考上面代码及注释

因为它的原理是图片是覆盖在按钮上,所以当图片的面积小于按钮的面积时,按钮的其余部分就会被显示出来。我写了段代码来修复这个问题(图片最好不要有透明背景的,否则图片的透明部分会被显示成如上图图片覆盖不到的地方)。

代码使用方法是

all a=new all(图片地址,按钮的宽度,按钮的高度)

JButton jb=new JButton(a.back())

你也可以吧这段代码打包成jar,以后需要使用就直接import就行了。

class all {//all可以改成别的,但引用时注意就好了。

private  int width,height

private Image image=null

private  ImageIcon result=null

public all(String path,int width,int height) {

result=new ImageIcon(path)

image=result.getImage()

this.width=width

this.height=height

design()

}

public void design(){

BufferedImage bi=new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB)

Graphics2D g2d=bi.createGraphics()

g2d.drawImage(image, 0, 0, width, height, null)

image=bi.getScaledInstance(width, height, Image.SCALE_SMOOTH)

result.setImage(image)

}

public ImageIcon back(){

return result

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11937738.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存