Erweiterung der Klasse Button zu einem Bildbutton

Aus DDSWiki
Wechseln zu: Navigation, Suche

Homer .gif

Der Code zum selbst Ausprobieren

Button button;

void setup() {
  size(400, 400);
  PImage i = loadImage("homer.png");
  button = new Button("",i,0, 10,10,100,100,20, 0);
}

void draw() {

  button.showAndCheckButton();

}


// ===================KLASSE BUTTON=================================
class Button {

  // Interne Variablen der Klasse. Man könnte auch das Schlüsselwort 'private' voranstellen
  String label;
  int id;
  int xPos, yPos, width_, height_;
  int textSize_;
  int nextScreen;
  boolean buttonIsTransparant = false;
  PImage img = null;

  // Constructor 
  Button(String l, int i, int x, int y, int w, int h, int ts, int s) {
    label = l; // Beschriftung des Knopfes
    id = i; // Eine eindeutige ID für den Knopf
    xPos = x; // Für die Positionierung und Dimensionierung des Knopfes
    yPos = y; 
    width_ = w; 
    height_ = h;
    textSize_ = ts;
    nextScreen = s; // Zu welchem Screen führt der Button?
  }
  
  // Constructor für Bildknopf
  Button(String l, PImage img_, int i, int x, int y, int w, int h, int ts, int s) {
    label = l; // Beschriftung des Knopfes
    id = i; // Eine eindeutige ID für den Knopf
    xPos = x; // Für die Positionierung und Dimensionierung des Knopfes
    yPos = y; 
    width_ = w; 
    height_ = h;
    textSize_ = ts;
    nextScreen = s; // Zu welchem Screen führt der Button?
    img = img_; // Knopfhintergrund
  }  

  int showAndCheckButton() {
    int r = -1;
    push();
    if ((mouseX>=xPos) && (mouseX<=xPos+width_) && (mouseY>=yPos) && (mouseY<=yPos+height_)) {
      strokeWeight(1);
      stroke(204, 102, 0);
      fill(255);
      if (mousePressed) {
        r = nextScreen;
        fill(120);
      }
    } else {
      strokeWeight(1);
      stroke(0, 0, 0);
      fill(255);
    }  
    if (!buttonIsTransparant) {
      rect(xPos, yPos, width_, height_);
      fill(0);
      textAlign(CENTER, CENTER);
      textSize(textSize_);
      if (img !=null) {
        img.resize(width_-2,height_-2);
        image(img, xPos+1,yPos+1);
      }
      text(label, xPos+width_/2, yPos+height_/2); 
    }
    pop();
    return r;
  }
  
  int getWidth() {
    return width_;
  }
  
  int getHeight() {
    return height_;
  }
  
  void makeTransparant(boolean t) {
    buttonIsTransparant = t;
  }
  
  void setLabel(String l) {
    label = l;
  }
}