JavaFX 能用來建立GUI,而這篇文章就是方便本人 copy and paste 而存在的。

注意這文章沒有訴說原理,只適合查語法之用。

JavaFX基本

使用JavaFX

import javafx.application.Application;

public class Main extends Application {

	@Override
	public void start(Stage primaryStage) throws Exception {
		//這裏用來描述interface
	}
    
	public static void main(String[] args) {
        Application.launch(args); //這段code建議新增,據說沒有加這段有部份
    }
}

這裏有一段很適合的comment解釋為何要加入Application.launch(args);

/**
* The main method is only needed for the IDE with limited
* JavaFX support. Not needed for running from the command line.
*/

例子:在Windows中顯示一個Button

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;

public class Main extends Application {

	@Override
	public void start(Stage primaryStage) throws Exception {
		Button test_btn = new Button("test button");
		Scene scene = new Scene(test_btn, 200, 200);
		primaryStage.setScene(scene);
		primaryStage.show();
	}
	public static void main(String[] args) {
        Application.launch(args);
    }
}

在Windows中顯示一個Button

觸發動作

onclick

onclick demo 1

Button demo = new Button("demo");
btn_change_color.setOnMouseClicked(new EventHandler<MouseEvent>() {
    @Override
    public void handle(MouseEvent event) {
        //這裏寫在按下Button之後要執行的東西
    }
});

onclick demo 2

//create 'OKHandlerClass' class
class OKHandlerClass implements EventHandler<ActionEvent> {
    @Override
    public void handle(ActionEvent e) {
      System.out.println("OK button clicked"); 
    }
}
Button btOK = new Button("OK");
OKHandlerClass handler1 = new OKHandlerClass(); //create object
btOK.setOnAction(handler1); //然後利用

onclick demo 3 (利用在 Java8 之後新增的 Lambda Expression 來寫)

import javafx.application.Application;
import javafx.scene.control.Button;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {
  @Override
  public void start(Stage primaryStage) {
	  Button demo = new Button("Demo");
	  demo.setOnMouseClicked(e -> {
		  System.out.println("Mouse click demo button");
	  }); //利用了lambda expression
	  Scene scene = new Scene(demo, 400, 200);
	  primaryStage.setScene(scene);
	  primaryStage.setTitle("Demo lambda expression");
	  primaryStage.show();
  }
  
  
  public static void main(String[] args) {
    launch(args);
  }
}

img

img

感想

JavaFX 是一個抄code的過程。