CUBは子供の白熊

Java SE 8 実践プログラミングの練習問題を解く

第4章 JavaFX による GUI プログラミング : 問題 10 : ブラウザ

問題

WebViewerを使用して、URLバーと戻るボタンを持つブラウザを実装せよ

解答

やってみましょう

public void start(Stage stage) throws Exception {
    // 末端のコントロール
    Button backButton = new Button("戻る");
    TextField urlField = new TextField();
    WebView browser = new WebView();
    // バインディング
    WebEngine engine = browser.getEngine();
    backButton.setOnAction(                // 戻るボタン → Web
        event -> { engine.getHistory().go(-1); }
    );
    backButton.disableProperty().bind(     // 戻るボタンの有効/無効
        Bindings.equal(0, engine.getHistory().currentIndexProperty())
    );
    urlField.setOnAction(                  // URLバー → Web
        event -> { engine.load(urlField.getText()); }
    );
    engine.locationProperty().addListener( // Web → URLバー
        (location, oldLocation, newLocation) -> { urlField.setText(newLocation); }
    );
    engine.load("http://closedunbounded.hatenablog.com/");
    // コンテナ
    HBox box = new HBox(backButton, urlField);
    HBox.setHgrow(urlField, Priority.ALWAYS);
    BorderPane pane = new BorderPane();
    pane.setTop(box);
    pane.setCenter(browser);

    stage.setScene(new Scene(pane, 1100, 800));
    stage.setTitle("ClosedUnBounded Browser");
    stage.show();
}

f:id:ClosedUnBounded:20150814185307p:plain

こんだけのコードで、いっぱしの Web ブラウザができちゃうんですね