Classe de modèle de bouton par Graphics Les propriétés X et Y sont les positions centrales des boutons Ombre, méthode de survol, méthode de presse, jugement de clic C'est OK pour en faire une classe abstraite et ajouter une méthode de clic
GraphicBtn.java
public class GraphicBtn {
	int X, Y; //Position centrale du bouton
	int w, h; //Bouton largeur, hauteur
	String text; //Texte du bouton
	Color btnC, textC; //Couleur du bouton, couleur du texte
	Font font; //Police du texte
	boolean hover, press; //Survolez, appuyez sur
	//constructeur
	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;
	}
	//Méthode de dessin
	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));
	}
	//Texte centré
	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);
	}
	//Changer uniquement la valeur alpha
	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));
	}
	//Méthode de survol
	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;
		}
	}
	//Méthode de presse
	public void mousePressed(int x,int y) {
		if(hover) press = true;
	}
	//Méthode de libération
	public void mouseReleased(int x,int y) {
		press = false;
	}
	//Cliquez sur le jugement
	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