0

我正在尝试 JavaFX-2,据说其中一项功能是我们可以在 FXML 文件中使用 Javascript 创建事件处理函数。困扰我的一件事是我无法立即访问 System 类。它需要被完全引用,例如“java.lang.System”。当我们需要控制台上的简单输出时,这变得很丑陋,我的意思是,“System.out.println”丑到可以打印一些东西。而且,即使我的 FXML 具有所有 <?import java.lang.*?> 语句,显然它不会影响 <fx:script> 标记的内部。

示例代码:(注意<?language javascript?>指令)

<?xml version="1.0" encoding="UTF-8"?>

<?language javascript?>

<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.collections.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.text.*?>

<AnchorPane fx:id="rootPane">
  <fx:script>
    function buttonAction(event){
      java.lang.System.out.println("finally we get to print something.");
      // System.out.println("This wouldn't work even if it wasn't a comment line, anyway");
    }
  </fx:script>
  <children>
    <Button id="close" mnemonicParsing="false" onAction="buttonAction(event)" text="">
      <graphic>
        <ImageView pickOnBounds="true">
          <image>
            <Image url="@../resources/close.png" preserveRatio="true" smooth="true" />
          </image>
        </ImageView>
      </graphic>
    </Button>
  </children>
</AnchorPane>

所以我的问题是:有没有办法将类导入 <fx:script>?我记得我在 Actionscript3.0 中这样做真的很容易:import flash.events.MouseEvent...

4

2 回答 2

1

使用 javascript 内置importPackageimportClass函数。

 <fx:script>
    importPackage(java.lang);
    function buttonAction(event){
        System.out.println("finally we get to print something.");
    }
</fx:script>

有关更多详细信息,请参阅:http ://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html#jsimport

于 2012-11-28T12:45:56.530 回答
0

这有点令人困惑,但来自 Sergey 的链接为后台发生的事情提供了很好的上下文(即将 java 扩展到脚本世界)。

尽管 Sergey 的解决方案有效,但它在可能是 javascript 的内联脚本中混合了 java 类方法(根据页面语言声明)。没有浏览器,所以没有“console.log()”,所以最好避免潜在的 java/js 混淆,只使用 print():

<fx:script>
    function reactToClick(event) {
        print("I was clicked");
    }
</fx:script>

下一个问题是 print() 方法从何而来……它不是 java 也不是 js。我认为答案在于用于支持 java/js 集成的 Nashorn javascript 引擎。Print() 是一个内置函数:Nashorn shell 命令。

于 2019-06-09T11:31:21.387 回答