简体   繁体   中英

How to get JavaFx TabPane title to be WebView's site title?

I am using JavaFx, and have Tabs with WebView objects on them. I am trying to have my tab title's text to read the web page's title like in most web browsers. When I use the "getTitle" method I get an empty title, Which I assume is because the page hasn't loaded yet. All the research I've done gives me an Android Solution and I'm looking for something that works with a desktop application. Here's what I have.

public class WebsiteTab extends Tab {

    final static String DEFAULT_SITE = "https://google.com";

    VBox browserBox;
    WebView webView;

    public WebsiteTab() {
        super("Site One");
        webView = new WebView();
        webView.setPrefHeight(5000);

        goToSite(DEFAULT_SITE);

        browserBox = new VBox(10,webView);
        VBox.setVgrow(browserBox, Priority.ALWAYS);

        setContent(browserBox);
    }

    public void goToSite(final String site) {
        webView.getEngine().load(site);
        setText(webView.getEngine().getTitle());
    }
}

Any help would be appreciated.

You can bind the tab's text property to the web engine's title property.

public class WebsiteTab extends Tab {

    final static String DEFAULT_SITE = "https://google.com";

    VBox browserBox;
    WebView webView;

    public WebsiteTab() {
        super("Site One");
        webView = new WebView();
        webView.setPrefHeight(5000);

        textProperty().bind(webView.getEngine().titleProperty()); // bind the properties

        goToSite(DEFAULT_SITE);

        browserBox = new VBox(10,webView);
        VBox.setVgrow(browserBox, Priority.ALWAYS);

        setContent(browserBox);
    }

    public void goToSite(final String site) {
        webView.getEngine().load(site);
    }
}

This will cause the text property to always have the same value as the title property. In other words, when the title property's value changes the text property will be automatically updated. Notice I bind the properties in the constructor as you only need to create the binding once. Also note that while bound you can no longer manually set the text property; attempting to do so will cause an exception to be thrown. For more information, see Using JavaFX Properties and Binding .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM