There's a button btn
in my JavaFX GUI interface. When clicking btn
, a graph will be drawn.
But when I close the graph, my JavaFX GUI will auto-close as well, which is not desired.
How can I prevent the JavaFX GUI from auto-close?
If the solution involve embedding the generated graph inside the JavaFX GUI, I am also fine. Thanks!
import javax.swing.JFrame;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.view.mxGraph;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class MainFx extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Draw Graph");
btn.setOnAction(new EventHandler<ActionEvent>() {
// draw graph when clicking the button
@Override
public void handle(ActionEvent event) {
JGraphXLearning1 frame = new JGraphXLearning1();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 320);
frame.setVisible(true);
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
public class JGraphXLearning1 extends JFrame {
public JGraphXLearning1() {
super("JGraphXLearning1");
mxGraph graph = new mxGraph();
Object defaultParent = graph.getDefaultParent();
graph.getModel().beginUpdate();
Object v1 = graph.insertVertex(defaultParent, null, "Hello", 20, 20, 80, 30);
Object v2 = graph.insertVertex(defaultParent, null, "World", 240, 150, 80, 30);
graph.insertEdge(defaultParent, null, "Edge", v1, v2);
graph.getModel().endUpdate();
mxGraphComponent graphComponent = new mxGraphComponent(graph);
getContentPane().add(graphComponent);
}
}
}