第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(); }
こんだけのコードで、いっぱしの Web ブラウザができちゃうんですね