Graphicsによるボタンの雛形クラス
プロパティXとYはボタンの中心位置
影,ホバーメソッド,プレスメソッド,クリック判定
抽象クラス化して,クリックメソッドつけてもOK
GraphicBtn.java
public class GraphicBtn {
int X, Y; //ボタン中心位置
int w, h; //ボタン横幅,高さ
String text; //ボタンテキスト
Color btnC, textC; //ボタン色,文字色
Font font; //テキストフォント
boolean hover, press; //ホバー,プレス
//コンストラクタ
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;
}
//描画メソッド
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));
}
//テキストの中央表示
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);
}
//アルファ値のみ変更
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));
}
//ホバーメソッド
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;
}
}
//プレスメソッド
public void mousePressed(int x,int y) {
if(hover) press = true;
}
//リリースメソッド
public void mouseReleased(int x,int y) {
press = false;
}
//クリック判定
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;
}
}