Subclassing JavaFX Stage / Scene

萝らか妹 提交于 2021-01-27 23:49:24

问题


Coming from Swing and being new to JavaFX I tried to subclass Java FX Stages and Scenes. However I quickly run into problems, like the init method not being of my subclassed sceen not being found during the initialization.

So I was wondering: Are Java FX Stages and Sceens to be subclassed like one would subclass JFrames and JPanels in Swing or is this discouraged?


回答1:


You can subclass Scene and Stage and many other FX library classes in pretty much the same way. I'm not sure I'd recommend it, and it doesn't seem to be a style that appears in any of the examples from the official tutorials. (In fact, I long ago stopped using subclasses of JFrame and JPanel in the vast majority of my swing code, preferring instead more the style in the FX examples.)

But it's certainly possible:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class SubclassingExample extends Application {

    @Override
    public void start(Stage defaultStageIgnored) {
        Stage stage = new MyStage();
        stage.show();
    }

    public static class MyStackPane extends StackPane{
        public MyStackPane() {
            getChildren().add(new Label("Hello World"));
        }
    }

    public static class MyScene extends Scene {
        public MyScene() {
            super(new MyStackPane(), 250, 75);
        }
    }

    public static class MyStage extends Stage {
        public MyStage() {
            setScene(new MyScene());
        }
    }

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


来源:https://stackoverflow.com/questions/29866798/subclassing-javafx-stage-scene

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!