ClassCastException Processing.core

ClassCastException Processing.core

我正在使用 Processing 3 制作一个简单的工具。

我希望我的草图在按下 "X" 按钮时不关闭。我在 Whosebug 上找到了一个 ,但是当我尝试这样做时,出现了这个错误:ClassCastException: processing.core.PApplet cannot be cast to javax.swing.JFrame

我已经尝试添加更多库,但现在错误提示不是库错误。

这里有一段代码:

import javax.swing.JFrame;
void setup() {
  size(640, 360);
  ((JFrame)frame).setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
void draw() {
  textSize(50);
  text("some text", width/2, height/2)
}
void exit() {
  println("Not exiting");
}

当我尝试 运行 草图时出现错误 ClassCastException: processing.core.PApplet cannot be cast to javax.swing.JFrame

您链接到的答案是处理 2,但您使用的是处理 3。

您的错误说明了一切:frame 无法转换为 JFrame,这正是您在此处尝试执行的操作:

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

要了解此错误的来源,您可以查看 PApplet class here.

的来源

在该文件中搜索 "frame" 以查看 frame 变量现在是 java.awt.Frame 而不是 javax.swing.JFrame。 Processing 还覆盖了 java.awt.Frame 中的一些函数,以提供特定于 Processings 的行为和警告消息。

您可以开始研究如何防止 java.awt.Frame 关闭,但我也会考虑重新考虑您是否要这样做。阻止 windows 关闭有点反模式,因此您应该仔细考虑是否真的需要这样做。您还可以考虑其他选项,例如使用全屏 window 而不是不可关闭的