问题
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