How to implement JShell using JavaFX in Java 9?

JShell is an interactive tool used to implement sample expressions. We can implement JShell programmatically using JavaFX application then we need to import a few packages in the java program listed below

<strong>import jdk.jshell.JShell;
import jdk.jshell.SnippetEvent;
import jdk.jshell.VarSnippet;</strong>

In the below example, implemented a sample Java FX application. We will enter different values in the text field and press the "eval" button. It will display values with corresponding data types in a list.

Example

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 {
   <strong>@Override</strong>
   public void start(Stage primaryStage) throws Exception {
      <strong>JShell</strong> shell = <strong>JShell.builder().build()</strong>;
      TextField textField = new TextField();
      Button evalButton = new Button("eval");
      <strong>ListView<String></strong> listView = new <strong>ListView</strong><>();

      evalButton.setOnAction(e -> {
         <strong>List<SnippetEvent></strong> events = shell.<strong>eval</strong>(textField.getText());
         events.stream().<strong>map</strong>(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);
      <strong>Scene </strong>scene = new <strong>Scene</strong>(pane);
      primaryStage.<strong>setScene</strong>(scene);
      primaryStage.<strong>show()</strong>;
   }
   public static String convert(<strong>SnippetEvent </strong>e) {
      if(e.snippet() instanceof VarSnippet) {
         return ((VarSnippet) e.snippet()).<strong>typeName()</strong> + " " + ((VarSnippet) e.snippet()).<strong>name() </strong>+ " " + <strong>e.value()</strong>;
      }
      return null;
   }
   public static void main(String[] args) {
      launch();
   }
}

Output

Updated on: 2020-05-02T09:45:07+05:30

341 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements