How to disable ESC key functionality in G4P child window

Problem: I want to disable the default functionality of the ESC key in a Processing sketch that creates a G4P child window. The standard method of doing this is:

void keyPressed() {
  if (key == ESC) {
    key = 0;
  }
}

But this only works in the main window, not the child window. So I created an event handler for the child window and registered it. It works in the sense that it captures key presses in the child window, but pressing the ESC key in the child window still closes both windows. How can I prevent this from happening? Here’s the event handler:

public void keyCheck(PApplet applet, GWinData data, KeyEvent event) {
  if (event.getAction() == event.PRESS) {
    keyCode = event.getKeyCode();
    println("keyCode = " + keyCode);
    if (event.getKeyCode() == ESC) {
      // Now do what?
    }
  }
}

Thanks.

1 Like

Here’s the complete sketch for anyone that wants to try it:

import g4p_controls.*;

GWindow window;
GButton btnMakeWindow;

void keyPressed() {
  if (key == ESC) {
    println("main window: pressed ESC key");
    key = 0;
  }
}

public void setup() {
  size(300, 240, JAVA2D);
  // Turn off mouse over icon change due to Processing bug
  G4P.setMouseOverEnabled(false);
  createGUI();
}

public void draw() {
  background(230);
}

public void keyCheck(PApplet applet, GWinData data, KeyEvent event) {
  if (event.getAction() == event.PRESS) {
    keyCode = event.getKeyCode();
    println("keyCode = " + keyCode);
    if (event.getKeyCode() == ESC) {
      println("child window: pressed ESC key");
      // Do what?
    }
  }
}

public void makeWindow(GButton source, GEvent event) {
  window = GWindow.getWindow(this,"Child Window",200,400,600,300,JAVA2D);
  window.addKeyHandler(this,"keyCheck");
} 

public void createGUI(){
  G4P.messagesEnabled(false);
  G4P.setGlobalColorScheme(GCScheme.BLUE_SCHEME);
  G4P.setCursor(ARROW);
  surface.setTitle("Main Window");
  btnMakeWindow = new GButton(this, 10, 190, 250, 30);
  btnMakeWindow.setText("Make the window");
  btnMakeWindow.setTextBold();
  btnMakeWindow.addEventHandler(this, "makeWindow");
}
1 Like

Each window is a separate PApplet so you must use the key variable for the correct applet - this worked for me

public void keyCheck(PApplet applet, GWinData data, KeyEvent event) {
  if (event.getAction() == event.PRESS) {
    applet.keyCode = event.getKeyCode();
    println("keyCode = " + keyCode);
    if (event.getKeyCode() == ESC) {
      println("child window: pressed ESC key");
      applet.key= 0;
    }
  }
}
2 Likes

Works for me too, except for the first “println()”. I had to add the “applet.” qualifier to it as well, otherwise it prints the last key pressed in the main window.

println("keyCode = " + applet.keyCode);

Thanks!

1 Like