Keyboard Entry Seems To Need Mouse Click To Work

keyPressed() does not seem to work at all until I click the mouse. I think others have had this problem but I am not clear as to what the answer was.

I assume you are using the Processing IDE and probably Java mode. Let me know if I am wrong.

The most likely cause is that your sketch window is not ‘activated’ when it first opens.

The operating system sends any keyboard events to the ‘active’ application. When you click on the sketch window with the mouse it actives application which will then receive keyboard events from the OS.

I am using the Processing IDE and the code is Java. How do i activate my sketch window?

A good question :grin: and I was net certain of the answer so I tried to create the same scenario with this sketch

int g = 128;

void setup(){
  size(320,240);
}

void draw(){
  background(255,255,200);
  noStroke();
  fill(g);
  rect(20,20,width - 40,height-40);
}

void keyTyped(){
  if(key =='c'){
    g = floor(random(256));
  }
}

I launched this sketch from the IDE and every time I typed the C key the colour of the rectangle changed to a random grey value. I did not have to click on the sketch window to make it active.

It might be OS specific, I used Processing 4.5.1 on macOS 15.7.4 so perhaps you might try this yourself and see whether it works for your system.

I copied your sketch and had the same result as you did: it worked just fine, repeatedly!

Two things to try

  1. add the statement println(key); inside your keyPressed() method
  2. check the spelling and capitalisation of the keyPressed method in your sketch. If not exact match it will be ignored.

I encountered the same issue long ago.

Below from an older code:

void setup()
{
  size(600, 400);

  // possible Processing bugfix
  // when the application starts, it does not always react on key presses
  //   and one has to manucally click in the application to give it the focus
  // workaround that might solve it found at https://discourse.processing.org/t/keypressed-only-works-sometimes/22340/
  surface.setVisible(true);
  ...
  ...

the KeyPressed function has worked well in the past.
However, I did the following:

  1. Loaded Processing.
  2. Loaded the sketch
  3. Ran the sketch 6 times : worked every time!
  4. I reloaded Processing
  5. Loaded the sketch
  6. Ran the sketch again: it worked!

I have no explanation for this .
“sterreje” suggested that I add

surface.setvisible (true);

which I did immediately before Setup

I did and we will see if it works continuously.

More later.

Thank you both

Make that: the last statement in setup

It should be in setup().

I’m not sure if it needs to be the last statement. But as said, it needs to be in setup() (or rather, a function).

Hello folks!

Some diagnostic code that I cooked up with ChatGPT:

// RendererFocusDiagnostics_0_2_0_20260423_092300
/*
Objective
Display focus diagnostics for Processing sketches running with JAVA2D, P2D, or P3D.

What is reported
- Window focus
- Canvas key focus for JAVA2D
- Current Java focus owner for JAVA2D
- Key input arrival via keyPressed()

Usage
Set RENDERER to JAVA2D, P2D, or P3D.
Run the sketch.
Click inside and outside the sketch window.
Press keys and observe the screen and console output.
*/

// JAVA2D imports
import processing.awt.PSurfaceAWT;
import java.awt.Frame;
import java.awt.Component;
import java.awt.KeyboardFocusManager;
import java.awt.event.WindowFocusListener;
import java.awt.event.WindowEvent;
import java.awt.event.FocusListener;
import java.awt.event.FocusEvent;

// Timestamp imports for console diagnostics
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

// P2D / P3D imports
import com.jogamp.newt.opengl.GLWindow;
import com.jogamp.newt.event.WindowAdapter;

// Select renderer here: JAVA2D, P2D, or P3D
String RENDERER = JAVA2D;

// JAVA2D objects
Frame awtWin;
PSurfaceAWT.SmoothCanvas awtCanvas;

// P2D / P3D object
GLWindow glWin;

// Visual confirmation that keyPressed() fired
boolean bgToggle = false;

// Console timestamp format
DateTimeFormatter tf = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");

void settings()
  {
  size(600, 400, RENDERER);
  }

void setup()
  {
  surface.setTitle("Focus Diagnostics: " + RENDERER);
  textSize(24);

  // Native surface type depends on renderer
  // JAVA2D -> SmoothCanvas
  // P2D/P3D -> GLWindow
  Object nativeSurface = surface.getNative();

  // JAVA2D diagnostics
  if (nativeSurface instanceof PSurfaceAWT.SmoothCanvas)
    {
    awtCanvas = (PSurfaceAWT.SmoothCanvas) nativeSurface;
    awtWin = awtCanvas.getFrame();

    // Window focus events
    awtWin.addWindowFocusListener(new WindowFocusListener()
    {
    public void windowGainedFocus(WindowEvent e)
      {
      report("windowGainedFocus");
      }

    public void windowLostFocus(WindowEvent e)
      {
      report("windowLostFocus");
      }
    }
    );

    // Canvas focus events
    awtCanvas.addFocusListener(new FocusListener()
    {
    public void focusGained(FocusEvent e)
      {
      report("canvasFocusGained");
      }

    public void focusLost(FocusEvent e)
      {
      report("canvasFocusLost");
      }
    }
    );
    }

  // P2D / P3D diagnostics
  else if (nativeSurface instanceof GLWindow)
    {
    glWin = (GLWindow) nativeSurface;

    glWin.addWindowListener(new WindowAdapter()
    {
    public void windowGainedFocus(com.jogamp.newt.event.WindowEvent e)
      {
      report("windowGainedFocus");
      }

    public void windowLostFocus(com.jogamp.newt.event.WindowEvent e)
      {
      report("windowLostFocus");
      }
    }
    );
    }

  delay(100);   // Allow startup focus state to settle
  report("startup");
  }

void draw()
  {
  if (bgToggle)
    background(0, 120, 255);
  else
    background(40);

  fill(255);
  textSize(24);

  text("Renderer: " + RENDERER, 20, 40);
  text("Press any key", 20, 80);
  text("Click the sketch window to update focus state", 20, 120);

  if (awtWin != null)
    {
    text("Window focus: " + awtWin.isFocused(), 20, 180);
    text("Canvas key focus: " + awtCanvas.isFocusOwner(), 20, 220);

    Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
    String ownerName = (owner == null) ? "null" : owner.getClass().getName();
    text("Focus owner: " + ownerName, 20, 260, width - 40, 120);
    }
  else if (glWin != null)
    {
    text("Window focus: " + glWin.hasFocus(), 20, 180);
    text("Key input status: watch keyPressed() output", 20, 220);
    }
  }

String ts()
  {
  return LocalTime.now().format(tf);
  }

void report(String tag)
  {
  // timestamp  
  String timeStamp = "[f " + frameCount + " | " + ts() + "]";

  println();
  println(timeStamp + " " + tag);
  println("Renderer: " + RENDERER); // Can be commented out

  if (awtWin != null)
    {
    Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
    String ownerName = (owner == null) ? "null" : owner.getClass().getName();

    println("Window focus: " + awtWin.isFocused());
    println("Canvas key focus: " + awtCanvas.isFocusOwner());
    println("Focus owner: " + ownerName);
    }
  else if (glWin != null)
    {
    println("Window focus: " + glWin.hasFocus());
    println("Key input status: use keyPressed() for confirmation");
    }
  }


void keyPressed()
  {
  bgToggle = !bgToggle;

  report("keyPressed: " + key);
  }


void mousePressed()
  {
  report("mousePressed");
  }

They are almost always both true or both false :

Occasionally I would get this:

Update:
I tested this with Windows 10 and Processing 4.5.3 and Processing 3.5.4
I would get keyboard focus when I started the sketch with the code I provided.
There were occasional expiations where I did not have focus.

:)

Thank you!
I added:

surface.setVisible(true);

to Setup and its working fine

Hello @fredstout,

This is what is happening under the hood (in the source code):

I like to dig into the source and this is just a general post for those taking interest.
It is easy to get lost in there… be careful of the dragons!

:)

What version of Processing are you using?
Which operating system?
Older or newer PC if you can share.
JAVA2D or P2D?

This should work without adding that and I am trying to track this down and understand why.
It is a rare occurrence for me and want to determine the root cause.

I will experiment with the source code in the future and have some ideas already.

:)

Thanks @glv for investigating this! Feel free to open an issue in the processing4 repo and update it with your findings.

I am a beginner. I am using a Dell Inspiron 16 with Windows 11. My version of Processing is 3.5.4
The sketch that I am currently working on makes extensive use of basic Processing graphic functions. I use whatever renderer the current version calls for (I make no specific request). The code is JAVA.
Fred