Button template class by Graphics Properties X and Y are the center positions of the buttons Shadow, hover method, press method, click judgment It is OK to make it an abstract class and add a click method
GraphicBtn.java
public class GraphicBtn {
int X, Y; //Button center position
int w, h; //Button width, height
String text; //Button text
Color btnC, textC; //Button color, text color
Font font; //Text font
boolean hover, press; //Hover, press
//constructor
public Button(Game game,int x,int y,int w,int h,
String text,Color btnC,Color textC,Font font) {
X = x;
Y = y;
this.w = w;
this.h = h;
this.text = text;
this.btnC = btnC;
this.textC = textC;
this.font = font;
hover = false;
press = false;
}
//Drawing method
public void draw(Graphics g,Canvas canvas) {
g.setColor(btnC.darker());
g.fillRoundRect(X-w/2, Y-h/2+5, w, h, 10, 10);
g.setColor(btnC);
g.fillRoundRect(X-w/2, Y-h/2+(press?2:0), w, h, 10, 10);
g.setColor(textC);
if(hover) setAlpha(g,180);
drawStrCenter(g,X,Y+(press?2:0));
}
//Centered text
public void drawStrCenter(Graphics g,int x,int y){
g.setFont(font);
FontMetrics fm = g.getFontMetrics();
Rectangle rectText = fm.getStringBounds(text, g).getBounds();
x = x-rectText.width/2;
y = y-rectText.height/2+fm.getMaxAscent();
g.drawString(text, x, y);
}
//Change only alpha value
public void setAlpha(Graphics g, int alpha) {
int R = g.getColor().getRed();
int G = g.getColor().getGreen();
int B = g.getColor().getBlue();
g.setColor(new Color(R, G, B, alpha));
}
//Hover method
public void mouseMoved(int x,int y) {
if(X-w/2 < x && x < X+w/2 && Y-h/2 < y && y < Y+h/2) {
hover = true;
} else {
hover = false;
press = false;
}
}
//Press method
public void mousePressed(int x,int y) {
if(hover) press = true;
}
//Release method
public void mouseReleased(int x,int y) {
press = false;
}
//Click judgment
public boolean isClick(int x,int y) {
if(X-w/2 < x && x < X+w/2 && Y-h/2 < y && y < Y+h/2) {
return true;
}
return false;
}
}
Recommended Posts