您好,对于程序我必须创建3个按钮,并且当鼠标按下每个按钮时颜色必须改变,我很困惑如何在按下鼠标时将按钮切换为不同的颜色使用处理语言,任何提示?到目前为止这是我的代码!
小部件主程序
PFont stdFont;
final int EVENT_BUTTON1=1;
final int EVENT_BUTTON2=2;
final int EVENT_BUTTON3=3;
final int EVENT_NULL=0;
Widget widget1, widget2,widget3;
ArrayList widgetList;
void setup(){
stdFont=loadFont("AbadiMT-CondensedLight-48.vlw");
textFont(stdFont);
widget1=new Widget(100, 100, 180, 40,
"RED", color(100),
stdFont, EVENT_BUTTON1);
widget2=new Widget(100, 200, 180, 40,
"GREEN", color(100),
stdFont, EVENT_BUTTON2);
size(400, 400);
widget3=new Widget(100, 300, 180, 40,
"BLUE", color(100),
stdFont, EVENT_BUTTON2);
size(400, 400);
widgetList = new ArrayList();
widgetList.add(widget1); widgetList.add(widget2); widgetList.add(widget3);
}
void draw(){
for(int i = 0; i<widgetList.size(); i++){
Widget aWidget = (Widget)widgetList.get(i);
aWidget.draw();
}
}
void mousePressed(){
int event;
for(int i = 0; i<widgetList.size(); i++){
Widget aWidget = (Widget) widgetList.get(i);
event = aWidget.getEvent(mouseX,mouseY);
switch(event) {
case EVENT_BUTTON1:
println("button 1!");
break;
case EVENT_BUTTON2:
println("button 2!");
break;
case EVENT_BUTTON3:
println("button 3!");
break;
}
}
}
main widget class
class Widget {
int x, y, width, height;
String label; int event;
color widgetColor, labelColor;
PFont widgetFont;
Widget(int x,int y, int width, int height, String label,
color widgetColor, PFont widgetFont, int event){
this.x=x; this.y=y; this.width = width; this.height= height;
this.label=label; this.event=event;
this.widgetColor=widgetColor; this.widgetFont=widgetFont;
labelColor= color(0);
}
void draw(){
fill(widgetColor);
rect(x,y,width,height);
fill(labelColor);
text(label, x+10, y+height-10);
}
int getEvent(int mX, int mY){
if(mX>x && mX < x+width && mY >y && mY <y+height){
return event;
}
return EVENT_NULL;
}
}
答案 0 :(得分:1)
听起来像是家庭作业。一般答案:
class RectangularThing {
float x, y, w, h;
color boxColor = 0;
[...]
boolean over(float mx, float my) {
// return "true" if mx/my is inside this rectangle,
// otherwise return "false"
}
void setColor(color c) {
boxColor = c;
}
void draw() {
stroke(boxColor);
fill(boxColor);
rect(x,y,w,h);
}
}
[...]
ArrayList<RectangularThing> allmythings;
void setup() {
...
allmythings = new ArrayList<RectangularThing>();
...
}
void draw() {
// this kind of looping is the same as
// "for(int i=0, last=allmythings;i<last;i++) {
// RectangularThing t = allmythings[i];
// ..." except that it's less code and easier
// to read. If you're just iterating without
// needing the iteration counter, this is nicer.
for(RectangularThing t: allmythings) {
t.draw();
}
}
void mouseClicked() {
for(RectangularThing t: allmythings) {
if(t.over(mouseX,mouseY)) {
t.setColor(...);
}
}
redraw();
}
所以:让自己负责绘制自己,并给予他们正确完成所需的所有属性。然后在需要时根据代码或用户交互更改这些属性。