Java FX 应用程序加载事件

标签 java javascript swing javafx onload

我正在使用 Google map API 在 java swing java fx 中实现一个应用程序。

我的问题是这样的,我需要在加载 map 时运行 JavaScript。

我正在阅读该方法:webEngine.getLoadWorker().StateProperty().AddListener 但在我的代码中不起作用。我想知道是否有人知道如何做到这一点。

我留下我的代码: SwingHtmlDemo.Java:

public class SwingHtmlDemo {

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                ApplicationFrame mainFrame = new ApplicationFrame();
                mainFrame.setVisible(true);

            }
        });

    }

}

/* 主窗口用于显示一些HTML内容。 */

class ApplicationFrame extends JFrame {

    JFXPanel javafxPanel;
    WebView webComponent;
    JPanel mainPanel;

    JTextField urlField;
    JButton goButton;

    public ApplicationFrame() {

        javafxPanel = new JFXPanel();

        initSwingComponents();

        loadJavaFXScene();

    }

    /**
     * Instantiate the Swing compoents to be used
     */
    private void initSwingComponents() {
        mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(javafxPanel, BorderLayout.CENTER);

        JPanel urlPanel = new JPanel(new FlowLayout());
        urlField = new JTextField();
        urlField.setColumns(50);
        urlPanel.add(urlField);
        goButton = new JButton("Go");
        urlField.setText("Rio branco 1421 montevideo");
        /**
         * Handling the loading of new URL, when the user enters the URL and
         * clicks on Go button.
         */

        goButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        String url = urlField.getText();
                        if (url != null && url.length() > 0) {
                            webComponent.getEngine().executeScript("document.goToLocation(\"" + urlField.getText() + "\")");
                        }
                    }
                });

            }
        });

        urlPanel.add(goButton);
        mainPanel.add(urlPanel, BorderLayout.NORTH);

        this.add(mainPanel);
        this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        this.setSize(700, 600);

    }

    /**
     * Instantiate the JavaFX Components in the JavaFX Application Thread.
     */
    private void loadJavaFXScene() {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {

                BorderPane borderPane = new BorderPane();
                webComponent = new WebView();

                webComponent.getEngine().load(getClass().getResource("googlemap.html").toString());
                borderPane.setCenter(webComponent);
                Scene scene = new Scene(borderPane, 450, 450);
                javafxPanel.setScene(scene);

            }
        });

    }

}

googlemap.html:

<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
  html { height: 100% }
  body { height: 100%; margin: 0px; padding: 0px }
  #map_canvas { height: 100%; background-color: #666970; }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyDRtQjq-q-w0Yr6BZ6y1nRGzAUM93udakg&sensor=false">
</script>
<script type="text/javascript">
  function initialize() {
    var latlng = new google.maps.LatLng(37.39822, -121.9643936);
    var myOptions = {
      zoom: 14,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      mapTypeControl: false,
      navigationControl: false,
      streetViewControl: false,
      backgroundColor: "#666970"
    };

    document.geocoder = new google.maps.Geocoder();
    document.map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);

    document.zoomIn = function zoomIn() {
        var zoomLevel = document.map.getZoom();
        if (zoomLevel <= 20) document.map.setZoom(zoomLevel + 1);
    }

    document.zoomOut = function zoomOut() {
        var zoomLevel = document.map.getZoom();
        if (zoomLevel > 0) document.map.setZoom(zoomLevel - 1);
    }

    document.setMapTypeRoad = function setMapTypeRoad() {
        document.map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
    }
    document.setMapTypeSatellite = function setMapTypeSatellite() {
        document.map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
    }
    document.setMapTypeHybrid = function setMapTypeHybrid() {
        document.map.setMapTypeId(google.maps.MapTypeId.HYBRID);
    }
    document.setMapTypeTerrain = function setMapTypeTerrain() {
        document.map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
    }

    document.goToLocation = function goToLocation(searchString) {
         var address = searchString;
    document.geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        document.map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: document.map,
            position: results[0].geometry.location
        });
        if (results[0].geometry.viewport) 
          document.map.fitBounds(results[0].geometry.viewport);
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
    }
  }

</script>
</head>
<body onload="initialize()">
    <div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>

最佳答案

考虑添加 FirebugLite 来调试您的应用:

<script src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>

如果我正确理解了这个问题,您需要在“文档加载”事件监听器中运行它:

webComponent.getEngine().load(getClass().getResource("googlemap.html").toString());

webComponent.getEngine().stateProperty().addListener(new ChangeListener<Worker.State>() {
    @Override
    public void changed(ObservableValue<? extends Worker.State> ov, Worker.State t, Worker.State t1) {
        if (t1 == Worker.State.SUCCEEDED) {
            // this will be run as soon as WebView is initialized.
            webComponent.getEngine().executeScript("document.goToLocation(\"" + urlField.getText() + "\")");               
        }
    }
});

更新

该消息意味着没有这样的功能,因此您需要将 JS 从原始 HTML 文件复制到 googlemap.html 中:

document.goToLocation = function goToLocation(searchString) {
    document.geocoder.geocode( {'address': searchString}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        document.map.setCenter(results[0].geometry.location);
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
}

更新2

此后为我工作(需要对所有功能执行此操作):


document.goToLocation = function  <strike>goToLocation</strike>(searchString) {

您可以考虑添加 FirebugLite 来调试您的 JS 应用:

<script src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>

关于Java FX 应用程序加载事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20073837/

相关文章:

java - 获取 JSON 数组中的特定值 (Java)

javascript - jQuery 无法在 Safari 中运行

javascript - 如何从 SVG 路径的交集找到新路径(形状)?

java - UIDefaults.getUI() 失败 : error when loading a JFrame into another project

java - JTable 行标题文本

java - 如何通过反射找到所有具有特定参数的方法?

java - 从ArrayList中获取文本

java - 如何设置最后一行或除最后一行之外的所有行不知道 MigLayout 中的行数?

php - 在ckeditor中集成Javascript虚拟键盘插件

java - 图像未加载到 JPanel 上?