【问题标题】:Is It Possible To Import Classes into FXML <fx:script> block (JavaFX-2)是否可以将类导入 FXML <fx:script> 块(JavaFX-2)
【发布时间】:2012-11-28 09:32:45
【问题描述】:

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

示例代码:(注意&lt;?language javascript?&gt; 指令)

<?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>

所以我的问题是:有没有办法将类导入

【问题讨论】:

    标签: javafx-2 fxml


    【解决方案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

    【讨论】:

    • 它有效,谢谢@Sergey。我不知道/认为有 Java 脚本语言的文档。
    【解决方案2】:

    这有点令人困惑,但来自 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 commands.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-01
      • 2016-08-08
      • 2019-06-11
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多