button click Need to let JPanel implement mouse click event. Follow the effect of the switch, you can achieve the effect of the button.
As an example:
There is a "buy" button, images as follows
Normal
MouseOver:
Disabled
Pressed
The code is as follows:
Public classShopbuttonextendsJPanelImplementsMouseListener {PrivateShop Shopui; Privateimage[] img; PrivateImage Normalimage; PrivateImage Rolloverimage; PrivateImage Pressedimage; PrivateImage Disabledimage; PrivateImage Currentimage; Private BooleanEnabled =true; PrivateString name =NULL; Privatecontrol control; PublicShopbutton (Shop shopui,string name,intXintY,control Control) { This. Shopui =Shopui; This. name = name;//Set name This. Control =control; This. IMG = This. shopui.createcardimg (name);//This is the use of the Factory mode to get IMG Resources This. Normalimage = This. img[0]; This. Rolloverimage = This. img[1]; This. Pressedimage = This. img[2]; This. Disabledimage = This. img[3]; This. Currentimage =Normalimage; This. setbounds (x, Y, This. Img[0].getwidth (NULL), This. Img[0].getheight (NULL)); This. Addmouselistener ( This); } Public Booleanisenabled () {returnenabled; } Public voidSetEnabled (Booleanenabled) { This. Enabled =enabled; } Public voidPaint (Graphics g) { This. Setopaque (false);//Transparent Background if(enabled) {G.drawimage (Currentimage, This. GetX (), This. GetY (), This. GetWidth (), This. GetHeight (), This); } Else if(! (Name.equals ("buy") | | name.equals ("Cancel")) {g.drawimage (disabledimage, This. GetX (), This. GetY (), This. GetWidth (), This. GetHeight (), This); }} @Override Public voidmouseclicked (MouseEvent e) {} @Override Public voidmousepressed (MouseEvent e) {currentimage=Pressedimage; if(enabled) {if( This. Name.equals ("close")) {//exit the store This. Shopui.movetoback (); This. Control.exitshop (); } Else if( This. Name.equals ("Cancel")) {//Cancel Current selection This. Shopui.setchoosecard (NULL); } Else if( This. Name.equals ("buy")) {//Buy Current selection This. Control.buycard ( This. Shopui.getshop ()); } Else { This. Shopui.setchoosecard ( This); } }} @Override Public voidmousereleased (MouseEvent e) {currentimage=Rolloverimage; } @Override Public voidmouseentered (MouseEvent e) {currentimage=Rolloverimage; } @Override Public voidmouseexited (MouseEvent e) {currentimage=Normalimage; }}
An appropriate extension can be made into a generic class that simulates a variety of button classes.
The following is the store interface within the mini monopoly: the red box is the extension implementation
[Java swing tycoon] is implemented under swing using the JPanel simulation button.