在处理中禁用关闭按钮

Disable close button in Processing

有没有办法在特定事件期间禁用处理中 window 的关闭按钮?

这是代码片段:

frame.addWindowListener(new WindowAdapter()
  {
    public void windowClosing(WindowEvent we)
    {
      if (youWin == 0) // condition that is supposed to keep the application opened
      {
        JOptionPane.showMessageDialog(frame,"You can't exit until you finish this game. OK?");
        // keep applet opened
      }
    }
  }
);

编辑:我想在不使用 JFrames 的情况下完成。

编辑:此答案适用于 Processing 2。它不适用于较新版本的 Processing。

I want to do it without using JFrames.

太糟糕了。您已经在使用 JFrame,只是您不知道而已。

处理将为您创建一个 JFrame,即使它存储在 Frame 变量中。如果你不相信我,请查看 PSurfaceAWT.

的第 453 行

这意味着您可以使用 JFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); 告诉框架在您单击 X 按钮时什么也不做。这将禁用自动关闭 JFrame 的低级侦听器。

import javax.swing.JFrame;
void setup() {
  ((JFrame)frame).setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
void draw() {
  background(0);
  ellipse(mouseX, mouseY, 10, 10);
}

但这只是成功的一半。 Processing 也有自己的侦听器,用于检测用户何时在低级侦听器之上单击 X 按钮。此侦听器调用 exit() 函数,该函数无论如何都会关闭草图。

要避开 ,您必须重写 exit() 函数。 (您也可以删除 Processing 添加的侦听器,但这更容易恕我直言。)

import javax.swing.JFrame;
void setup() {
  ((JFrame)frame).setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
void exit() {
  println("not exiting");
}
void draw() {
  background(0);
  ellipse(mouseX, mouseY, 10, 10);
}

好的,我们已经完全删除了使用 X 按钮关闭框架的功能。现在我们必须添加在需要时关闭它的功能。您可以通过在 exit() 函数中添加对 super.exit() 的调用来执行此操作:

void exit() {
  if(reallyExit){
    super.exit();
  }
}

调用 super.exit() 将为您关闭草图。如何设置 reallyExit 变量取决于您。

另一种方法是将 WindowListner 添加到处理关闭事件的 JFrame

void setup() {

  ((JFrame)frame).setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

  frame.addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent we) {
      if (reallyExit) {
        frame.dispose();
      }
    }
  }
  );
}

这是使用这两种方法的完整示例。不过,您只需要 调用 frame.dispose() 调用 super.exit()。完全看个人喜好。

import javax.swing.JFrame;

void setup() {

  ((JFrame)frame).setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

  frame.addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent we) {
      if (mouseX < 10) {
        frame.dispose();
      }
    }
  }
  );
}

void exit() {
  if(mouseX <10){
    super.exit();
  }
}


void draw() {
  background(0);
  ellipse(mouseX, mouseY, 10, 10);
}