在以下代碼中,primaryScene.lookup(第30行)返回null。但在調試模式(IntelliJ)中,我可以鑽入並查看場景圖中的節點。javafx 8,未使用fxml,scene.lookup未找到節點
這是一個獨立的例子。沒有FXML。
該應用只是繪製舞臺和場景,然後嘗試使用Scene.lookup選擇標記爲id =「drawPane」的窗格。
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import static javafx.application.Application.launch;
public class Main extends Application {
Scene primaryScene;
Pane drawPane;
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) {
primaryScene = buildUI(primaryStage);
if (primaryScene == null) throw new NullPointerException();
drawPane = (Pane)primaryScene.lookup("#drawPane");
if (drawPane == null) {
throw new NullPointerException();
}
primaryStage.show();
}
private Scene buildUI(Stage primaryStage) {
ScrollPane scrollPane;
ImageView iv;
BorderPane root = new BorderPane();
Scene primaryScene = new Scene(root, 900, 800);
initializePrimaryStage(primaryStage, primaryScene);
initializeFrameContent(root);
initializeContent(root);
return primaryScene;
}
private void initializePrimaryStage(Stage primaryStage, Scene primaryScene) {
primaryStage.setTitle("Image Clip Test");
primaryStage.setScene(primaryScene);
primaryStage.setWidth(400);
primaryStage.setHeight(300);
primaryStage.minWidthProperty().setValue(400);
primaryStage.minHeightProperty().setValue(300);
}
private void initializeFrameContent(BorderPane root) {
Button leftButton = new Button("LEFT");
leftButton.setId("leftButton");
Button rightButton = new Button("RIGHT");
rightButton.setId("rightButton");
Button topButton = new Button("TOP");
rightButton.setId("topButton");
StackPane leftPane = new StackPane(leftButton);
leftPane.setAlignment(Pos.TOP_LEFT);
StackPane rightPane = new StackPane(rightButton);
rightPane.setAlignment(Pos.TOP_RIGHT);
root.setLeft(leftPane);
root.setTop(topButton);
root.setRight(rightButton);
}
private void initializeContent(BorderPane root) {
Pane drawPane = new Pane();
drawPane.setId("drawPane");
drawPane.setPrefSize(1000, 800);
drawPane.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
ScrollPane scrollPane = new ScrollPane(drawPane);
scrollPane.setPrefSize(300, 300);
scrollPane.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
scrollPane.setFitToHeight(true);
scrollPane.setFitToWidth(true);
scrollPane.setStyle("-fx-focus-color: transparent");
root.setCenter(scrollPane);
}
}
哇。我一直在Google上搜索,沒有提到這個小塊。謝謝! – vocalionecho
不知道這個,非常感謝 – stjepano