Processing中实现鼠标点击后Stop界面持续显示直至再次点击的方法
Fixing the Toggle Between Walk/Stop Screens in Processing
Let's break down why your current code only shows the Stop screen briefly, then fix it step by step:
The Core Issue
Processing's draw() function runs continuously (default 60 times per second). Right now, when you click the mouse, mousePressed() draws the red Stop screen once—but the very next draw() call immediately overwrites it with the green Walk screen. That's why it flashes and disappears.
Key Problems in Your Code
- You declared a
walkboolean but never used it, and tried to usestopwithout declaring it first (this would actually throw an error in Processing!) - All your drawing logic isn't tied to the state of your toggle variable—you're drawing Walk every time
draw()runs, regardless of clicks. - You're setting
xandypositions insidedraw()every frame, which is unnecessary (they don't change).
Fixed Code
boolean stop; // Declare our toggle variable properly String textStop; String textWalk; float x; float y; void setup() { size(400, 500); stop = false; // Start in Walk state textStop = "STOP!"; textWalk = "WALK!"; x = 150; y = 250; textSize(40); textAlign(CENTER, CENTER); // Optional: centers text on x/y position } void draw() { // Use the stop variable to decide what to draw if (stop) { background(255, 0, 0); // Red background for Stop text(textStop, width/2, height/2); // Using width/2/height/2 centers perfectly } else { background(0, 255, 0); // Green background for Walk text(textWalk, width/2, height/2); } } void mousePressed() { // Just flip the state of stop—draw() handles the rest! stop = !stop; }
What Changed & Why
- Proper Variable Declaration: We clarified the
stopboolean (removed unusedwalkvariable) to track our current state. - State-Based Drawing in
draw(): All rendering logic lives indraw(), where we check thestopvariable every frame to show the correct screen. This way, the screen stays consistent until we toggle the state. - Simplified
mousePressed(): Instead of drawing directly here, we just flip thestopvalue (stop = !stopmeans "set stop to the opposite of its current value"). - Better Text Positioning: Using
width/2andheight/2ensures your text stays perfectly centered even if you change the window size, andtextAlign(CENTER, CENTER)makes the text's center match those coordinates.
Now when you click, the screen will switch to Stop and stay there until you click again to go back to Walk!
内容的提问来源于stack exchange,提问作者Lauryn
相关产品推荐
相关产品推荐

