javafx adds a graphical interface to the java terminal program without a graphical interface

This approach may be a general method for adding a graphical interface to headless programs.

First of all, two threads must be opened, one to run the ui, and the other to run the java program to be transformed. The static class variables of the main program are used to exchange data between the ui and the java program.

It is mainly to modify the keyboard input and display. The keyboard input uses javafx keyboard event input, and the display uses the javafx animation principle to refresh regularly.

On this basis, it can be modified to become an Android program.

The following code has chat and nas functions. You can upload files to the other party, you can query the files in the directory specified by the other party, and you can download them back.

It is found that the Thread.sleep() delay method cannot be used in the ui part and event method of javafx. After using it, the program does not report an error, but nothing is displayed.

The code is modified as follows;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.*;
import java.net.Socket;
import java.util.*;

public class Test extends Application {
    public static String[] dir(String in){
        File file=new File(in);
        String[] out=file. list();
        return out;
    }
    static String jpin="hello";
    static boolean isjp;
    static boolean isrun=true;
    static boolean iszx;
    static String pathfile="";
    static boolean iscp;
    static String jspath="/home/wjs/nas/";
    static String s="start";
    static ArrayList<String> sw=new ArrayList<>();
    @Override
    public void start(Stage stage){

        Label label=new Label();
        label.setFont(Font.font("Verdana", FontWeight.BLACK,15));
        label.setText("Query: dir, upload: & amp; + file name, download: send, chat: input directly");

        Button button = new Button();
        button.setPrefSize(120,50);
        button.setFont(Font.font("Verdana", FontWeight.BLACK,15));
        button.setText("Send");

        TextArea textArea=new TextArea();
        textArea.setPrefRowCount(24);
        textArea. setMaxHeight(410);
        textArea.setFont(Font.font("Verdana", FontWeight.BLACK,15));


        TextField textArea1 = new TextField();
        textArea1.setPrefSize(600,50);
        textArea1.setFont(Font.font("Verdana", FontWeight.BLACK,15));

        EventHandler<ActionEvent> eventHandler1=event -> { //keyboard input
            jpin=textArea1.getText();
            isjp=true;
            textArea1.setText("");
        };

        textArea1.setOnAction(eventHandler1);
        button.setOnAction(eventHandler1);


        HBox hBox = new HBox();
        hBox.getChildren().addAll(textArea1,button);

        BorderPane root = new BorderPane();
        root.setTop(textArea);
        root.setCenter(label);
        root.setBottom(hBox);

      EventHandler<ActionEvent> eventHandler = e -> {
                                  //The purpose of the following 11 sentences is to make the screen always display the last 18 sentences of information entered
            int t = sw. size();
            String so="";
            if(t<=18){
                for(int n=0;n<t;n + + ){
                    so = so + sw. get(n);
                }
            }else{
                for(int n=t-18;n<t;n + + ){
                    so = so + sw. get(n);
                }
            }
            textArea. setText(so);
        };
        KeyFrame keyFrame=new KeyFrame(Duration.millis(100),eventHandler); //Corresponding to eventHandler event every 1ms
        Timeline timeline = new Timeline(keyFrame); //ui displays the content of static s regularly.
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline. play();

 /* It has been verified that this simplest loop timing can also be used here
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                  int t = sw. size();
            String so="";
            if(t<=18){
                for(int n=0;n<t;n + + ){
                    so = so + sw. get(n);
                }
            }else{
                for(int n=t-18;n<t;n + + ){
                    so = so + sw. get(n);
                }
            }
            textArea. setText(so);
            }
        }, 100, 100);*/

        Scene scene=new Scene(root,720,480);
        stage. setScene(scene);
        stage.setTitle("Client");
        stage. show();
    }
    public static void main(String[] args){
        Client t=new Client();
        t. start();
        launch(args);
    }
}
class Client extends Thread {
    public void run() {

        try {
            Socket sc = new Socket("114.132.48.228", 6001);
            InputStream is1 = sc. getInputStream();
            //------------Receive the login information prompted by the server---------------------------- -------------------
            ObjectInputStream objectInputStream1 = new ObjectInputStream(is1);
            // System.out.println(objectInputStream1.readUTF());
            Test.sw.add(objectInputStream1.readUTF() + "\
");
//----------Determine whether the other party's server is online------------------------------ ------------------
            boolean isrun = true;
            boolean iszx = objectInputStream1. readBoolean();
            if (iszx == true) {
                // System.out.println("The client is online");
                Test.sw.add("The client is online\
");
            } else {
                Test.sw.add("The client is not online\
");
                // System.out.println("The client is not online");
                while (iszx == false) {
                    Thread. sleep(1000);
                    iszx = objectInputStream1. readBoolean();
                }
            }
            //-------Enter id to verify id------------------------------------- --------------------------
            // System.out.println(objectInputStream1.readUTF());
            Test.sw.add(objectInputStream1.readUTF() + "\
");
            // si=objectInputStream1.readUTF() + "\
";
            OutputStream outputStreamid = sc. getOutputStream();
            ObjectOutputStream objectOutputStreamid = new ObjectOutputStream(outputStreamid);

            // Scanner scanner = new Scanner((System.in));
            while(Test.isjp==false){
                Thread. sleep(100);
            }

            // objectOutputStreamid.writeUTF(scanner.nextLine());
            objectOutputStreamid.writeUTF(Test.jpin);
            objectOutputStreamid.flush();

            Test.sw.add(objectInputStream1.readUTF() + "\
");
            Jp jp = new Jp();
            jp.start();
//------------------------------------------------ --------------------------------------
            while (iszx == true) {

                InputStream is = sc. getInputStream();
                ObjectInputStream objectInputStream = new ObjectInputStream(is);
                boolean isdf = objectInputStream. readBoolean();
                if (isdf == false) {
                    // System.out.println("The other party's client is offline, waiting for the other party to connect");
                    Test.sw.add("The other party's client is offline, waiting for the other party to connect\
");
                    Thread. sleep(3000);

                }
                char c = objectInputStream. readChar();
//-----------Receive chat information------------------------------- -----------------------------------

                if (c == '^') {
                    String s = objectInputStream. readUTF();
                    if (s. equals(" & amp;")) {
                        // System.out.println("File transfer started");
                        Test.sw.add("File transfer started\
");
                    } else {
                        // System.out.println("The client received: " + s);
                        Test.sw.add("The client received:" + s + "\
");
                        if (s. equals("dir")) {
                            // String dirpath="/Users/wangzhong/nas/";
                            String[] dirfile = Test.dir(Test.jspath);
                            String stringout = "";
                            for (String x : dirfile) {
                                stringout = stringout + x + " ";
                            }
                            Test.jpin = "\
" + stringout + "\
" + Test.jspath;
                            Test.isjp = true;
                            isdf = true;
                        }
                        if (s. length() > 4) {
                            String zxml = s. substring(0, 4);

                            if (zxml. equals(("send"))) {
                                Test.pathfile = s.substring(5);
                                // pathfile=jspath + pathfile;
                                Test.iscp = true;
                            }
                        }
                    }
                    c = '*';
                }

//------------Receive the file uploaded by the other party's client------------------------- ----------------------------

                if (c == ' & amp;') { // upload file identifier
                    String jsfilename = objectInputStream. readUTF();
                    int jsfilelength = objectInputStream. readInt();
                    byte[] jsfile = new byte[jsfilelength];
                    objectInputStream. readFully(jsfile);

                    FileOutputStream fileOutputStream = new FileOutputStream(Client3000.jspath + jsfilename);
                    fileOutputStream.write(jsfile);
                    fileOutputStream. close();
                    // System.out.println(jsfilename + "receive complete");
                    Test.sw.add(jsfilename + "receiving completed\
");
                    c = '*';
                }

                OutputStream os = sc. getOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(os);
//-----------turn off an app----------------------------------- ----------------------------------
                if ((Test.isjp == true) & amp; & amp; (isdf == true)) {
                    if (Test. jpin. equals("~")) {
                        sc. close();
                        break;
                    }
                    // if(!jpin.equals(" & amp;")) {
//---------Send chat message--------------------------------- ---------------------------------
                    objectOutputStream.writeChar('^');
                    objectOutputStream.flush();
                    objectOutputStream.writeUTF(Test.jpin);
                    objectOutputStream.flush();
                    // System.out.println("Client send:" + Test.jpin);
                    Test.sw.add("Client send:" + Test.jpin + "\
");
                    Test.isjp = false;
                    Test.iscp = false;
                    // }
//------------Send upload file---------------------------------- --------------------------------
                } else if (Test.iscp == true) {
                    objectOutputStream.writeChar(' & amp;'); //Send upload file identifier
                    objectOutputStream.flush();
                    try {
                        File file = new File(Test.jspath + Client3000.pathfile);
                        String filename = file. getName();
                        int filelength = (int) file. length();
                        objectOutputStream.writeUTF(filename);
                        objectOutputStream.writeInt(filelength);
                        objectOutputStream.flush();

                        byte[] fsfile = new byte[filelength];
                        FileInputStream fileInputStream = new FileInputStream(file);
                        fileInputStream. read(fsfile);

                        objectOutputStream.write(fsfile);
                        objectOutputStream.flush();
                        // System.out.println(filename + "send complete");
                        Test.sw.add(filename + "send completed\
");
                        Test.iscp = false;
                        Test.isjp = false;
                    } catch (FileNotFoundException e) {
                        Test.s="copy file path error";
                        break;
                    }

                } else {
//----------Send anti-blocking character------------------------------- --------------------------------
                    objectOutputStream.writeChar('*');
                    objectOutputStream.flush();

                }
                Thread. sleep(200);
            }
            sc. close();
            Test.s="The connection between the client and the server is interrupted, reconnect";

        } catch (IOException | InterruptedException e) {
            Test.s="The connection is interrupted. Restart the program";
            // throw new RuntimeException(e);
        }
    }
}
/* Change to gui graphical interface, scanner input does not work
//============ Keyboard input class ===================================== ==========================
class Jp1 extends Thread{
    public synchronized void run(){
        while(true) {
            Scanner scanner = new Scanner(System.in);
            Test.jpin = scanner.nextLine();
            isjp=true;

            if(Test.jpin.equals(" & amp;")){ //upload file
                Test.pathfile=scanner.nextLine();
                Test.iscp=true;

            }
        }
    }
}*/