Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีสร้าง JShell ด้วย JavaFX ใน Java 9

JShell เป็นเครื่องมือโต้ตอบสำหรับทดสอบ expression ต่างๆ สามารถนำ JShell มาใช้ในโปรแกรมได้โดยใช้ JavaFX application ต้อง import package ต่อไปนี้:

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

ตัวอย่างโค้ด JavaFX Application

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();
    }
}

วิธีทำงาน

  1. สร้าง JShell instance ด้วย JShell.builder().build()
  2. สร้าง UI ด้วย TextField สำหรับใส่โค้ด, Button "eval" สำหรับรัน, และ ListView สำหรับแสดงผล
  3. เมื่อกดปุ่ม eval จะเรียก shell.eval() กับข้อความจาก TextField
  4. แปลง SnippetEvent ให้เป็น String แสดง type name, variable name, และ value
  5. เพิ่มผลลัพธ์ลงใน ListView

ผลลัพธ์

วิธีสร้าง JShell ด้วย JavaFX ใน Java 9

ข้อดีของการทำแบบนี้

  • สร้าง REPL tool ส่วนตัวได้
  • สามารถปรับแต่ง UI ตามต้องการ
  • นำไปฝังในแอปพลิเคชัน JavaFX อื่นๆ ได้
  • เหมาะสำหรับการสอนหรือทดสอบโค้ดแบบโต้ตอบ