Computer >> Máy Tính >  >> Lập trình >> Java

Làm cách nào để triển khai JShell bằng JavaFX trong Java 9?

JShell là một công cụ tương tác được sử dụng để triển khai các biểu thức mẫu. Chúng tôi có thể triển khai JShell theo chương trình bằng cách sử dụng JavaFX ứng dụng thì chúng ta cần nhập một vài gói trong chương trình java được liệt kê bên dưới

import jdk.jshell.JShell;
import jdk.jshell.SnippetEvent;
import jdk.jshell.VarSnippet;

Trong ví dụ dưới đây, đã triển khai một ứng dụng Java FX mẫu. Chúng tôi sẽ nhập các giá trị khác nhau trong trường văn bản và nhấn " eval ". Nó sẽ hiển thị các giá trị với các kiểu dữ liệu tương ứng trong một danh sách.

Ví dụ

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<String> listView = new ListView<>();

      evalButton.setOnAction(e -> {
         List<SnippetEvent> 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();
   }
}

Đầu ra

Làm cách nào để triển khai JShell bằng JavaFX trong Java 9?