第一种:一个事件建一个类(比较容易理解,但是每次一个事件都要创建一个类,繁琐,只绑定一次)
第二种内部类(直接在表示类中再新建一个类,较为简洁)
第三种匿名类(不用起名字,更加简约)
第四种lambda 表达式(最简约,格式较以往不同需要多敲几遍才能记住)
(event)->{count ++; …}
事件类
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package panessetlocation;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
/**
*
* @author liulufei
*/
public class myClickHandler implements EventHandler<ActionEvent>{
@Override
public void handle(ActionEvent arg0) {
System.out.println("点击按钮");
}
}
在显示类中新建事件类对象
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package panessetlocation;
import javafx.scene.shape.Rectangle;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class PanesSetLocation extends Application {
int count = 0;
@Override
public void start(Stage primaryStage) {
Label num = new Label();
//生成一个矩形对象
Rectangle shape1 = new Rectangle(50, 100);
//设置矩形的位置,x,y坐标,左上角为0,0从左到右,从上到下
//shape1.setX(20);
//shape1.setY(20);
//设置边界颜色。使用了Color颜色类美式英语
shape1.setStroke(Color.BLACK);
//设置填充颜色
shape1.setFill(Color.YELLOW);
HBox pane = new HBox();
pane.getChildren().add(shape1);
Scene scene = new Scene(pane, 200, 200);
Button button = new Button("???");
Button button2 = new Button("按钮2");
pane.getChildren().add(button);
pane.getChildren().add(button2);
pane.getChildren().add(num);
//-----------------------------------------------
//第一种方式:新建一个事件类的对象
myClickHandler click = new myClickHandler();
System.out.println("?");
//绑定事件到按钮上
button.setOnAction(click);
//第二种方式:内部类-------------------------------------------
// class myClick implements EventHandler<ActionEvent>{
//
// @Override
// public void handle(ActionEvent arg0) {
// count += 1;
// num.setText(count + "");
// System.out.println(count);
// }
//
// }
//
// button2.setOnAction(new myClick());
// 第三种方式:使用匿名类-------------------------------------
// button2.setOnAction(new EventHandler<ActionEvent>(){
// @Override
// public void handle(ActionEvent arg0) {
// count ++;
// num.setText(count + "");
// System.out.println(count);
// }
//
// }
// );
//----------------------------------------
//第四种方式,使用lambda 表达式,最简约,但是格式不同以前,稍微有些难记(event) -> {count ++;...}
button.setOnAction((event)->{
count ++;
num.setText(count+"");
}
);
primaryStage.setTitle("pane Example");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}