You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 walk boolean but never used it, and tried to use stop without 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 x and y positions inside draw() 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

  1. Proper Variable Declaration: We clarified the stop boolean (removed unused walk variable) to track our current state.
  2. State-Based Drawing in draw(): All rendering logic lives in draw(), where we check the stop variable every frame to show the correct screen. This way, the screen stays consistent until we toggle the state.
  3. Simplified mousePressed(): Instead of drawing directly here, we just flip the stop value (stop = !stop means "set stop to the opposite of its current value").
  4. Better Text Positioning: Using width/2 and height/2 ensures your text stays perfectly centered even if you change the window size, and textAlign(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 18:34:09