无法更新网址并更新网络视图

时间:2018-04-24 17:03:23

标签: java eclipse javafx-8

这是我的项目设置我尝试更新webview,因此每个标签都会被一个地址栏更新。我似乎无法找到我出错的地方。我是javaFX的新手。我知道我必须在那里为搜索按钮添加另一个更改侦听器,但不确定如何...我无法找到有关如何执行此操作的任何内容。除了一个没有真正解释任何事情并且代码混乱的例子。

public class Client extends Application {   
    private Scene scene;
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    BorderPane root = new BorderPane();
    Browser browseR = new Browser();
    final TabPane tabs = new TabPane();
    final Tab home = new Tab("Home");
    final Tab newtab = new Tab("+");

    HBox hbox = new HBox();
    public static TextField addressBar = new TextField();
    final Group group = new Group(tabs,root,hbox); //joins the borderpane and browser element together

    @Override public void start(Stage stage) {

        // create the scene
        stage.setTitle("Web Browser");
        scene = new Scene(group,screenSize.getWidth(),screenSize.getHeight(), Color.web("#666970")); //create scene with root pane and browser pane

        hbox.setSpacing(10);
        hbox.setStyle("-fx-background-color: #FFFFFF;");
        hbox.setPadding(new Insets(5, 24, 5, 12));

        Button backButton = new Button("<");
        backButton.setOnAction(this::backButtonHandler);
        backButton.setPrefSize(25, 20);

        Button forwardButton = new Button(">");
        forwardButton.setOnAction(this::forwardButtonHandler);
        forwardButton.setPrefSize(25, 20);

        HBox.setHgrow(addressBar, Priority.ALWAYS);
        //addressBar.setMaxWidth(screenSize.getWidth()-200);

        Button searchButton = new Button("go");
        searchButton.setOnAction(this::searchButtonHandler);

        //add all menu elements to the top of the screen
        hbox.getChildren().addAll(backButton, forwardButton,addressBar,searchButton);

        setConstraints(tabs,hbox,stage);
        createHomeTab();   
        createNewTab();



        tabs.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>() {

            @Override
            public void changed(ObservableValue<? extends Tab> observable, Tab oldSelectedTab, Tab newSelectedTab) {
                if(newSelectedTab == newtab) {
                    final Tab tab = new Tab(browseR.getWebTitle());
                    tabs.getTabs().add(tab);
                    tabs.getSelectionModel().select(tab);
                    tab.setContent(new Browser());
                    loadFavicon(addressBar.getText(),tab);
                }
            }

            });

        root.setTop(hbox);
        root.setCenter(tabs);

        browseR.updateAddress();

        stage.setScene(scene);     
        stage.show();
    }

    public static void setConstraints(TabPane tabs, HBox hbox, Stage stage) {
        hbox.prefWidthProperty().bind(stage.widthProperty());
        tabs.prefHeightProperty().bind(stage.heightProperty());
    }

    private void backButtonHandler(ActionEvent event) {
        browseR.goBack();
    }
    public void createHomeTab() {
        tabs.getTabs().addAll(newtab,home);
        tabs.getSelectionModel().select(home);
        home.setContent(new Browser());
        loadFavicon(Browser.getHomePage(),home);
    }
    private void forwardButtonHandler(ActionEvent event) {
        browseR.goForward();
    }
    public void createNewTab() {
        newtab.setText(" + ");  
        newtab.setClosable(false);
    }
    private void searchButtonHandler(ActionEvent event) {
        Browser.navigate(addressBar.getText());
    }
    void loadFavicon(String location, Tab tab) {
      try {
        String faviconUrl = String.format("http://www.google.com/s2/favicons?domain_url=%s", URLEncoder.encode(location, "UTF-8"));
        Image favicon = new Image(faviconUrl, true);
        ImageView iv = new ImageView(favicon);
        tab.setGraphic(iv);
      } catch (UnsupportedEncodingException ex) {
          throw new RuntimeException(ex); // not expected
      }
    }
    public static void main(String[] args){
        //new Config();
        launch(args);
    }
}

public class Browser extends Region { 
    public static WebView browser = new WebView();
    public static WebEngine webEngine = getBrowser().getEngine();
    static String[] websites = {"http://www.google.com"};
    private static String homePage = websites[0];

    public Browser() {
        //apply the styles
        getStyleClass().add("browser");
        // load the web page
        webEngine.load(homePage);
        //add the web view to the scene
        getChildren().add(getBrowser());

    }

    public static void navigate(String website) {
        String google = "http://www.google.com/search?q=";
        String charset = "UTF-8";
        if(website.contains("http")) {
            webEngine.load(website);

            //debug
            System.out.println("found http");
        }
        else {
            try {
                webEngine.load(google+ URLEncoder.encode(website, charset));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        //debug
        System.out.println(website);
    }
    /*
    private Node createSpacer() {
        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);
        return spacer;
    }
     */     
    public String getWebTitle() {
        return webEngine.getTitle();
    }
    public void goBack() {
         Platform.runLater(() -> {
                webEngine.executeScript("history.back()");
            });
    }
    public String updateAddress() {
        webEngine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> {
             if (Worker.State.SUCCEEDED.equals(newValue)) {
                 Client.addressBar.setText(webEngine.getLocation());
             }
         });
        return null;
    }
    public void goForward() {
     Platform.runLater(() -> {
                webEngine.executeScript("history.forward()");
            });
   }
    @Override protected void layoutChildren() {
        double w = getWidth();
        double h = getHeight();
        layoutInArea(getBrowser(),0,0,w,h,0, HPos.CENTER, VPos.CENTER);
    }

    @Override protected double computePrefWidth(double height) {
        return 750;
    }

    @Override protected double computePrefHeight(double width) {
        return 500;
    }
    //getters and setters
    public static String getHomePage() {
        return homePage;
    }
    public static void setHomePage(String homePage) {
        Browser.homePage = homePage;
    }

    public static WebView getBrowser() {
        return browser;
    }

1 个答案:

答案 0 :(得分:0)

如果我正确理解了这个问题,你就会有一个文本字段和多个标签,每个标签都有一个浏览器。当在文本字段上发生操作时,您希望在当前选定的选项卡中更新浏览器的位置。

最简单的方法是保持对当前显示的浏览器的引用:

public class Client extends Application {   

    private Browser displayedBrowser ;

    // ...

}

当您创建新标签页和浏览器时,请在标签selectedProperty中添加一个监听器,以更新displayedBrowser字段:

tabs.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>() {

    @Override
    public void changed(ObservableValue<? extends Tab> observable, Tab oldSelectedTab, Tab newSelectedTab) {
        if(newSelectedTab == newtab) {
            final Tab tab = new Tab(browseR.getWebTitle());
            tabs.getTabs().add(tab);

            Browser newBrowser = new Browser();
            tab.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
                if (isNowSelected) {
                    displayedBrowser = newBrowser ;
                }
            });

            tabs.getSelectionModel().select(tab);

            tab.setContent(newBrowser);

            loadFavicon(addressBar.getText(),tab);
        }
    }

});

现在displayedBrowser将始终指向当前所选标签中的浏览器。

显然,navigate不能是静态方法,因为您想要导航特定的浏览器:事实上Browser类中的 nothing 应该是静态的:remove 来自static类的Browser关键字的所有次出现。完成这些更改后,您只需更新当前浏览器:

private void searchButtonHandler(ActionEvent event) {
    displayedBrowser.navigate(addressBar.getText());
}