03. ปุ่มกด

เป็นตัวอย่างแสดงการเขียนโปรแกรมจำลองการควบคุมอุปกรณ์โดยการกด ปิด-เปิดสวิต์ โดยเมื่อใช้เมาส์คลิกที่ปุ่มสีเขียวหรือสีแดง ภาพหลอดไฟจะมีการเปลี่ยนแปลง

สำหรับตัวอย่างนี้ต้องสร้างโฟลเดอร์ชื่อ data เพื่อใช้เก็บรูปภาพต่างๆ โฟลเดอร์นี้อยู่ในโฟลเดอร์โปรเจค รูปภาพทั้งหมดอยู่ที่ท้ายบทความนี้แล้ว

คลิกเพื่อดูการทำงาน

//--- define variable and constant

ImageButtons ButtonOn,ButtonOff;

PImage Lamp_On, Lamp_Off;

int xl = 150;

int yl = 30;

void setup() {

size(350, 300);

smooth();

background(255); // Set the background to black

// Define and create image button

PImage Pon_0 = loadImage("green_button_cir_0.gif");

PImage Pon_1 = loadImage("green_button_cir_1.gif");

PImage Pon_2 = loadImage("green_button_cir_2.gif");

PImage Poff_0 = loadImage("red_button_cir_0.gif");

PImage Poff_1 = loadImage("red_button_cir_1.gif");

PImage Poff_2 = loadImage("red_button_cir_2.gif");

Lamp_On = loadImage("Lamp_on.jpg");

Lamp_Off = loadImage("Lamp_off.jpg");

int x = width/6;

int y = height - (Pon_0.height)-50;

int w = Pon_0.width;

int h = Pon_0.height;

ButtonOn = new ImageButtons(x, y, w, h, Pon_0, Pon_1, Pon_2);

ButtonOff = new ImageButtons(x+1*w+40, y, w, h, Poff_0, Poff_1, Poff_2);

image(Lamp_Off, xl, yl);

stroke(255); // Set stroke color to white

loop();

}

void draw() {

PImage Lamp_On = loadImage("Lamp_on.jpg");

PImage Lamp_Off = loadImage("Lamp_off.jpg");

ButtonOn.update();

ButtonOn.display();

ButtonOff.update();

ButtonOff.display();

if (mousePressed == true)

{

if(ButtonOn.pressed)

{

image(Lamp_On, xl, yl);

}

if(ButtonOff.pressed)

{

image(Lamp_Off, xl, yl);

}

}

stroke(100);

//line(20, 20, 300,20);

}

class Button

{

int x, y;

int w, h;

color basecolor, highlightcolor;

color currentcolor;

boolean over = false;

boolean pressed = false;

void pressed() {

if(over && mousePressed) {

pressed = true;

} else {

pressed = false;

}

}

boolean overRect(int x, int y, int width, int height) {

if (mouseX >= x && mouseX <= x+width &&

mouseY >= y && mouseY <= y+height) {

return true;

} else {

return false;

}

}

}

//-------------------------------------------------------

class ImageButtons extends Button

{

PImage base;

PImage roll;

PImage down;

PImage currentimage;

ImageButtons(int ix, int iy, int iw, int ih, PImage ibase, PImage iroll, PImage idown)

{

x = ix;

y = iy;

w = iw;

h = ih;

base = ibase;

roll = iroll;

down = idown;

currentimage = base;

}

void update()

{

over();

pressed();

if(pressed) {

currentimage = down;

} else if (over){

currentimage = roll;

} else {

currentimage = base;

}

}

void over()

{

if( overRect(x, y, w, h) ) {

over = true;

} else {

over = false;

}

}

void display()

{

image(currentimage, x, y);

}

}