欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

swing重绘按钮为任意形状图案的方法

程序员文章站 2023-12-16 15:18:04
swing自带的metalbutton是非常丑的,不能满足我们的实际需求,所以需要定制自己喜欢的按钮,比如一个图片按钮等等。如下图所示。 接着说明如何制作。 (...

swing自带的metalbutton是非常丑的,不能满足我们的实际需求,所以需要定制自己喜欢的按钮,比如一个图片按钮等等。如下图所示。

swing重绘按钮为任意形状图案的方法

接着说明如何制作。

(1)找一些好看的按钮图片,但是按钮可能在图片内部,所以我们需要用美图秀秀或者ps将按钮抠出来。如下图:

swing重绘按钮为任意形状图案的方法

(2)将其保存为透明背景就可以了。

(3)然后写一个我的按钮类:

import javax.imageio.imageio; 
import javax.swing.*; 
import java.awt.*; 
import java.awt.image.bufferedimage; 
 
public class newbutton extends jbutton{ 
 imageicon img; 
 public newbutton(string icon){ 
  super(); 
  this.img = new imageicon(demo.class.getresource(icon)); 
  setborderpainted(false); 
  setcontentareafilled(false); 
  setopaque(false); 
  setsize(img.geticonwidth(),img.geticonheight()); 
  try{ 
   bi = imageio.read(demo.class.getresource(icon)); 
  }catch(exception e){ 
   joptionpane.showmessagedialog(this,"可能是图片文件不存在","imageio异常",joptionpane.error_message); 
   system.exit(0); 
  } 
 } 
 @override 
 public void paintcomponent(graphics g){ 
  if(this.getmodel().ispressed()){ 
   g.drawimage(img.getimage(),1,1,this); 
  }else{ 
   g.drawimage(img.getimage(),0,0,this); 
  } 
  super.paintcomponent(g); 
 } 
 bufferedimage bi ; 
 int rgb,alpha; 
 /** 
  * 设置按钮点击范围仅在图片的非透明区域。 
  */ 
 @override 
 public boolean contains(int x,int y){ 
  try{ 
   rgb = bi.getrgb(x,y); 
   alpha = (rgb>>24)&0xff; 
   if(alpha==0){ 
    return false; 
   }else{ 
    return true; 
   } 
  }catch(arrayindexoutofboundsexception e){ 
   //当搜索到透明区域时,就getrgb抛出下表越界异常 
   return false; 
  } 
 } 
} 

上面的程序重写了contains函数保证党鼠标点击区域限制在图片的有效区域内。

(4)写一个demo类测试:

import javax.swing.*; 
import java.awt.*; 
import java.net.url; 
 
public class demo { 
 public demo(){ 
  jframe jf=new jframe("任意形状图片按钮测试"); 
  jf.setbounds(500,200,700,500); 
 
  myjpanel jp = new myjpanel(demo.class.getresource("bg.jpg")); 
  jp.setlayout(null); 
 
  newbutton jb1 = new newbutton("bt1.png"); 
  jb1.setlocation(44,44); 
  jp.add(jb1); 
 
  jb1 = new newbutton("snowflower.png"); 
  jb1.setlocation(200,44); 
  jp.add(jb1); 
 
  jb1 = new newbutton("bt2.png"); 
  jb1.setlocation(350,64); 
  jp.add(jb1); 
 
  jb1 = new newbutton("bt3.png"); 
  jb1.setlocation(450,64); 
  jp.add(jb1); 
 
  jf.add(jp); 
  jf.setdefaultcloseoperation(jframe.exit_on_close); 
  jf.setvisible(true); 
 } 
 public static void main(string[] args){ 
  new demo(); 
 } 
 private class myjpanel extends jpanel{ 
  imageicon bg; 
  public myjpanel(url bg) { 
   this.setopaque(false);//要设置为透明。 
   this.bg = new imageicon(bg); 
  } 
  //用于设置背景图片 
  @override 
  public void paintcomponent(graphics g){ 
   g.drawimage(bg.getimage(),0,0,this.getwidth(),this.getheight(),this); 
   super.paintcomponent(g); 
  } 
 } 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: