JShell的四個小例子,分別基於網絡,併發,JavaFX(OpenJFX)和Swing

第一個例子,基於網絡

Client.java

import java.io.IOException
import java.net.InetSocketAddress
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.nio.channels.ServerSocketChannel
import java.nio.channels.SocketChannel
import java.nio.file.Paths
import java.nio.file.StandardOpenOption

SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 1532))
FileChannel fileChannel = FileChannel.open(Paths.get("1.png"), StandardOpenOption.READ)
ByteBuffer buf = ByteBuffer.allocate(1024)
while (fileChannel.read(buf) != -1){
    buf.flip();
    socketChannel.write(buf);
    buf.clear();
}
fileChannel.close()
socketChannel.close()

Server.java

import java.io.IOException
import java.net.InetSocketAddress
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.nio.channels.ServerSocketChannel
import java.nio.channels.SocketChannel
import java.nio.file.Paths
import java.nio.file.StandardOpenOption

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()
FileChannel fileChannel = FileChannel.open(Paths.get("2.png"), StandardOpenOption.WRITE, StandardOpenOption.CREATE)
serverSocketChannel.bind(new InetSocketAddress(1532))
SocketChannel socketChannel = serverSocketChannel.accept()
ByteBuffer byteBuffer = ByteBuffer.allocate(1024)
while (socketChannel.read(byteBuffer) != -1){
    byteBuffer.flip();
    fileChannel.write(byteBuffer);
    byteBuffer.clear();
}
socketChannel.close()
fileChannel.close()
serverSocketChannel.close()

先運行Server.java,然後再運行Client.java,這兩個文件所在的目錄下需要一個名爲1.png的圖片,還可以把這兩段代碼分別封裝到一個方法中,然後執行方法,運行結果如下:

 

第二個例子,基於併發

ForkJoinSumCalculate.java

import java.util.concurrent.RecursiveTask

class ForkJoinSumCalculate extends RecursiveTask<Long>{

    private long start;
    private long end;

    private static final long THURSHOLD = 10000L;

    public ForkJoinSumCalculate(long start, long end){
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long length = end - start;
        if(length < THURSHOLD){
            long sum = 0L;
            for(long i = start; i <= end; i++){
                sum += i;
            }
            return sum;
        }else {
            long mid = (start + end) / 2;
            ForkJoinSumCalculate left = new ForkJoinSumCalculate(start, mid);
            left.fork(); //拆分並壓入線程隊列
            ForkJoinSumCalculate right = new ForkJoinSumCalculate(mid + 1, end);
            right.fork();

            return left.join() + right.join();
        }
    }
}

MainScript.java

import java.util.concurrent.ForkJoinPool
import java.util.concurrent.ForkJoinTask
import java.util.stream.LongStream

ForkJoinPool pool = new ForkJoinPool()
ForkJoinTask<Long> task = new ForkJoinSumCalculate(0L, 100000000L)
long sum = pool.invoke(task)
System.out.println(sum)

運行順序必須先是ForkJoinSumCalculate.java,然後是MainScript.java,JShell還沒有其他的解釋型語言這麼成熟,下面是運行結果:

 

第三個例子,基於JavaFX

MainController.java

public class MainController {}

這個java文件需要自己編譯後打成Jar包,因爲JavaFX fxml控制器的安全機制,需要JavaFX線程自己加載類,導致無法解釋執行。

main.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane xmlns="http://javafx.com/javafx"
            xmlns:fx="http://javafx.com/fxml"
            fx:controller="MainController"
            prefHeight="400.0" prefWidth="600.0" id="anchorPane">

</AnchorPane>

MainWindow.java

import javafx.fxml.FXMLLoader
import javafx.scene.Scene
import javafx.scene.layout.AnchorPane
import javafx.scene.paint.Color
import javafx.scene.shape.Line
import java.io.File

class MainWindow extends Scene {
    public MainWindow() throws Exception {
        super(FXMLLoader.load(new File("D:\\CAH\\Creat\\2019\\Learn\\Applicarion\\JShell\\test2\\main.fxml").toURL()));
        AnchorPane anchorPane = (AnchorPane) lookup("#anchorPane");
        for(int i = 0; i < 11; i++){
            Line lineH = new Line();
            lineH.setStartX(50);
            lineH.setStartY(i * 50 + 50);
            lineH.setEndX(600 - 50);
            lineH.setEndY(i * 50 + 50);
            lineH.setStroke(Color.RED);
            lineH.setStrokeWidth(5);
            Line lineV = new Line();
            lineV.setStartX(i * 50 + 50);
            lineV.setStartY(50);
            lineV.setEndX(i * 50 + 50);
            lineV.setEndY(600 - 50);
            lineV.setStroke(Color.RED);
            lineV.setStrokeWidth(5);
            anchorPane.getChildren().add(lineH);
            anchorPane.getChildren().add(lineV);
        }
    }
}

MainStage.java

import javafx.application.Application
import javafx.stage.Stage

class MainStage extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        // 50 per
        primaryStage.setMinWidth(600);
        primaryStage.setMinHeight(600);
        // 設置標題
        primaryStage.setTitle("畫格子");
        // 加載顯示面板到Stage容器內
        primaryStage.setScene(new MainWindow());
        // 設置窗口大小禁止改變
        primaryStage.setResizable(false);
        primaryStage.show();
    }
}

MainScript.java

import javafx.application.Application

Application.launch(MainStage.class)

和之前說的一樣,需要按照一定的順序進行執行,同時還需要openJFX的jar包(用--class-path指定路徑)和之前封裝的控制器的jar包,運行結果如下:

 

第四個例子,基於Swing顯示一張圖片

ShowPicture.java

import javax.swing.ImageIcon
import javax.swing.JFrame
import javax.swing.JPanel
import java.awt.Image
import java.awt.Color
import java.awt.Graphics

class ShowPicture extends JFrame{
    public ShowPicture(){
        // 讀取一個圖片
        ImageIcon icon = new ImageIcon("C:\\Users\\OVEA\\OneDrive\\圖片\\本機照片\\Picture\\1022971.jpg");
        Image img = icon.getImage();
        JPanel base = new JPanel() {
            // 顯示和麪板,同時將圖片顯示出來
			public void paint(Graphics g) {
				g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
				super.paint(g);
			}
		};
        // 設置背景透明
		base.setBackground(null);
		// 設置控件透明
		base.setOpaque(false);
		// 不使用任何佈局
		base.setLayout(null);
        // 創建並設置窗體
		this.setTitle("圖片顯示");
		// 設置內容顯示
		this.setContentPane(base);
		// 設置窗體大小
		this.setSize(500, 500);
		// 設置位置
		this.setLocation(800, 300);
		// 設置點擊關閉按鈕的默認動作
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// 鎖定窗體
		this.setResizable(false);
		// 設置背景色(雖然沒啥用)
		this.setBackground(Color.WHITE);
		// 設置是否可見
		this.setVisible(true);
		// 設置居中
		this.setLocationRelativeTo(null);
    }
}

MainScript.java

new ShowPicture()

需要按照ShowPicture->MainScript的順序運行,結果如下:

 

 

以上便是使用JShell的四個例子,僅供初步JShell使用參考,所以比較簡單。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章