JShell是用于实现示例表达式的交互式工具。我们可以使用JavaFX应用程序以编程方式实现JShell,然后需要在下面列出的Java程序中导入一些软件包import jdk.jshell.JShell;
import jdk.jshell.SnippetEvent;
import jdk.jshell.VarSnippet;
在下面的示例中,实现了一个示例Java FX应用程序。我们将在文本字段中输入不同的值,然后按“ eval ”按钮。它将在列表中显示具有相应数据类型的值。
示例import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import java.util.List;
import jdk.jshell.JShell;
import jdk.jshell.SnippetEvent;
import jdk.jshell.VarSnippet;
public class JShellFXTest extends Application {
@Override public void start(Stage primaryStage) throws Exception {
JShell shell = JShell.builder().build();
TextField textField = new TextField();
Button evalButton = new Button("eval");
ListView listView = new ListView<>();
evalButton.setOnAction(e -> {
List events = shell.eval(textField.getText());
events.stream().map(event -> convert(event)).filter(s -> s != null).forEach(s -> listView.getItems().add(s));
});
BorderPane pane = new BorderPane();
pane.setTop(new HBox(textField, evalButton));
pane.setCenter(listView);
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
}
public static String convert(SnippetEvent e) {
if(e.snippet() instanceof VarSnippet) {
return ((VarSnippet) e.snippet()).typeName() + " " + ((VarSnippet) e.snippet()).name() + " " + e.value();
}
return null;
}
public static void main(String[] args) {
launch();
}
}