gpt4 book ai didi

java - 简单的消息框作业给了我色轮

转载 作者:行者123 更新时间:2023-11-30 03:44:51 25 4
gpt4 key购买 nike

我们在类里面做了这个 JavaFX 练习题,当我单击“打我”按钮时,它不断地给我一个色轮。我已经查看了代码,甚至让我的教授也这样做了,但我看不到任何问题。有可能是 Mac 的问题吗?我 friend 的代码在他的 Windows 机器上运行得很好。

package csc502_classexample_events_1;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javax.swing.JOptionPane;

/**
*
* @author aufty
*/
public class CSC502_ClassExample_Events_1 extends Application
{

@Override
public void start(Stage stage)
{
// Single centered button in HBox
Button button = new Button("Hit me");
button.setOnAction(new ClickHandler());
HBox hBox = new HBox();
hBox.getChildren().add(button);
hBox.setAlignment(Pos.CENTER);

stage.setTitle("My Event Handler Example");
Scene scene = new Scene(hBox, 400, 80);
stage.setScene(scene);
stage.show();
}

public static void main(String [] args)
{
launch(args);
}


}

class ClickHandler implements EventHandler<ActionEvent>
{

@Override
public void handle(ActionEvent event)
{
JOptionPane.showMessageDialog(null, "Ouch");
}

}

最佳答案

您正在尝试从 FX 应用程序线程显示 JOptionPane。 Swing UI 操作应在 AWT 事件处理线程上执行。在此示例中,情况特别糟糕,因为 AWT 工具包(可能)甚至尚未初始化。

类似的东西

class ClickHandler implements EventHandler<ActionEvent> {

@Override
public void handle(ActionEvent event) {
SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(null, "Ouch"));
}

}

应该修复它。

(这是 Java 8 代码,如果您仍在使用旧的 Java 版本,则可以对 Runnable 使用匿名内部类而不是 lambda 表达式。)

关于java - 简单的消息框作业给了我色轮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25996247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com