如何在JavaFX应用程序中检索HTML表单字段

时间:2015-07-06 06:11:55

标签: javafx javafx-8 javafx-webengine

<html lang="en">
<head>
    <title>WebView</title>    
</head>
<body>
<form action="">
   <input type="text" name="tb1" id="ib1">
   <button id="btn">Submit</button>
</form>
</body>
</html>

package webviewsample;

public class WebViewSample extends Application {

    private Scene scene;

    @Override
    public void start(Stage stage) {      
        stage.setTitle("Web View");
        scene = new Scene(new Browser(), 750, 500, Color.web("#666970"));
        stage.setScene(scene);   
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
class Browser extends Region {

    private HBox toolBar;
    private static String[] imageFiles = new String[]{
        "help.png"
    };
    private static String[] captions = new String[]{
        "Help"
    };
    private static String[] urls = new String[]{
        WebViewSample.class.getResource("help.html").toExternalForm()
    };
    final ImageView selectedImage = new ImageView();
    final Hyperlink[] hpls = new Hyperlink[captions.length];
    final Image[] images = new Image[imageFiles.length];
    final WebView browser = new WebView();
    final WebEngine webEngine = browser.getEngine();
    final Button showPrevDoc = new Button("Toggle Previous Docs");
    final WebView smallView = new WebView();
    final ComboBox comboBox = new ComboBox();
    private boolean needDocumentationButton = false;

    public Browser() {
        //apply the styles
        getStyleClass().add("browser");

        for (int i = 0; i < captions.length; i++) {
            // create hyperlinks
            Hyperlink hpl = hpls[i] = new Hyperlink(captions[i]);
            Image image = images[i] =
                    new Image(getClass().getResourceAsStream(imageFiles[i]));
            hpl.setGraphic(new ImageView(image));
            final String url = urls[i];
            final boolean addButton = (hpl.getText().equals("Documentation"));

            // process event 
            hpl.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent e) {
                    needDocumentationButton = addButton;
                    webEngine.load(url);
                }
            });
        }

        webEngine.setOnAlert((WebEvent<String> event) -> {
        System.out.println("ALERT!!!! " + event.getData());

        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle("Information Dialog");
        alert.setHeaderText(null);
        alert.setContentText(event.getData());

        alert.showAndWait();

        JSObject jso = (JSObject) webEngine.executeScript("window");
        jso.setMember("bridge", new Bridge());

    });

        comboBox.setPrefWidth(60);

        // create the toolbar
        toolBar = new HBox();
        toolBar.setAlignment(Pos.CENTER);
        toolBar.getStyleClass().add("browser-toolbar");
        toolBar.getChildren().add(comboBox);
        toolBar.getChildren().addAll(hpls);
        toolBar.getChildren().add(createSpacer());

        //set action for the button
        showPrevDoc.setOnAction(new EventHandler() {
            @Override
            public void handle(Event t) {
                webEngine.executeScript("toggleDisplay('PrevRel')");
            }           
        });

        smallView.setPrefSize(120, 80);

        //handle popup windows
        webEngine.setCreatePopupHandler(
            new Callback<PopupFeatures, WebEngine>() {
                @Override public WebEngine call(PopupFeatures config) {
                    smallView.setFontScale(0.8);
                    if (!toolBar.getChildren().contains(smallView)) {
                        toolBar.getChildren().add(smallView);
                    }
                    return smallView.getEngine();
                }
             }
        );        


        //process history
        final WebHistory history = webEngine.getHistory();
        history.getEntries().addListener(new 
            ListChangeListener<WebHistory.Entry>(){
                @Override
                public void onChanged(Change<? extends Entry> c) {
                    c.next();
                    for (Entry e : c.getRemoved()) {
                        comboBox.getItems().remove(e.getUrl());
                    }
                    for (Entry e : c.getAddedSubList()) {
                        comboBox.getItems().add(e.getUrl());
                    }
                }
        });

        //set the behavior for the history combobox               
        comboBox.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent ev) {
                int offset =
                        comboBox.getSelectionModel().getSelectedIndex()
                        - history.getCurrentIndex();
                history.go(offset);
            }
        });



        // process page loading
        webEngine.getLoadWorker().stateProperty().addListener(
            new ChangeListener<State>() {
                @Override
                public void changed(ObservableValue<? extends State> ov,
                    State oldState, State newState) {
                    toolBar.getChildren().remove(showPrevDoc);    
                    if (newState == State.SUCCEEDED) {
                            JSObject win = 
                                (JSObject) webEngine.executeScript("window");
                            win.setMember("app", new JavaApp());
                            if (needDocumentationButton) {
                                toolBar.getChildren().add(showPrevDoc);
                            }
                        }
                    }
                }
        );

        // load the home page        
        webEngine.load("http://www.oracle.com/products/index.html");

        //add components
        getChildren().add(toolBar);
        getChildren().add(browser);
    }

    // JavaScript interface object
    public class JavaApp {

        public void exit() {
            Platform.exit();
        }
    }

    private Node createSpacer() {
        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);
        return spacer;
    }

    @Override
    protected void layoutChildren() {
        double w = getWidth();
        double h = getHeight();
        double tbHeight = toolBar.prefHeight(w);
        layoutInArea(browser,0,0,w,h-tbHeight,0,HPos.CENTER,VPos.CENTER);
        layoutInArea(toolBar,0,h-tbHeight,w,tbHeight,0,HPos.CENTER,VPos.CENTER);
    }

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

    @Override
    protected double computePrefHeight(double width) {
        return 600;
    }
}

我将在JavaFX应用程序中呈现此HTML页面,我将在文本框中输入内容并点击提交按钮。我想在JavaFX应用程序中输入文本框值。有人可以告诉我怎样才能实现这个目标?

我想在我的Java类中输入文本框值。再次感谢

2 个答案:

答案 0 :(得分:0)

我还没有使用过webengine,但是查看文档会显示以下代码段,这可能是一个起点

EventListener listener = new EventListener() {
    public void handleEvent(Event ev) {
        Platform.exit();
    }
};

Document doc = webEngine.getDocument();
Element el = doc.getElementById("exit-app");
((EventTarget) el).addEventListener("click", listener, false);

因此,您可以尝试将处理程序附加到提交按钮,然后查找您的disired字段以获取文本。

答案 1 :(得分:0)

index.html
<fieldset>
    <legend>LoginForm</legend>
    USERNAME: <input type="text" id="uname" name="uname">
    PASSWORD: <input type="password" id="password" name="password">
    <button onclick="app.submit(document.getElementById('uname').value)">Submit</button>
</fieldset>

public class JavaApp {

        public void submit(String userName) {
            System.out.println("Inside exist application method");          
            System.out.println("userName-->"+userName);
            //Platform.exit();
        }
    }

JSObject win = (JSObject) webEngine.executeScript("window");
                win.setMember("app", new JavaApp());

我确实喜欢这个并且能够在我的Java类中拥有textfield值,有人可以告诉我这是正确的方法吗?

相关问题