swing自帶的metalbutton是非常丑的,不能滿足我們的實際需求,所以需要定制自己喜歡的按鈕,比如一個圖片按鈕等等。如下圖所示。
接著說明如何制作。
(1)找一些好看的按鈕圖片,但是按鈕可能在圖片內部,所以我們需要用美圖秀秀或者ps將按鈕摳出來。如下圖:
(2)將其保存為透明背景就可以了。
(3)然后寫一個我的按鈕類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
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類測試:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
import javax.swing.*; import java.awt.*; import java.net.url; public class demo { public demo(){ 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); } } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/A694543965/article/details/78410828