Search code examples
javajavafxjoptionpane

Simple message box homework gives me color wheel


We did this JavaFX practice problem in class and it keeps giving me a color wheel when I click the "hit me" button. I've looked through the code and even had my professor do so, and I can't see any issues. Is it possible that it's a Mac problem? My friend's code ran just fine on his Windows machine.

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");
}

}

Solution

  • You're trying to display a JOptionPane from the FX Application Thread. Swing UI operations should be performed on the AWT event handling thread. In this example, it's particularly bad because the AWT toolkit (probably) hasn't even been initialized.

    Something like

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

    should fix it.

    (This is Java 8 code, you can use an anonymous inner class for the Runnable instead of the lambda expression if you're still using an old Java version.)