JavaFX:事件
package sample;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
// 实现事件处理方法
public class ButtonHandle implements EventHandler<ActionEvent> {
Label label=new Label();
Button ok=new Button("ok");
Button cancel=new Button("cancel");
@Override
public void handle(ActionEvent actionEvent) {
if (actionEvent.getSource()==ok){
label.setText(" you get ok item");
}else if (actionEvent.getSource()==cancel){
label.setText(" you get cancel item");
}
}
}
package sample;
import javafx.application.Application;
import javafx.event.Event;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
// Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
// FlowPane root = new FlowPane();
Pane root=new Pane();
primaryStage.setTitle("Hello World");
ButtonHandle handle=new ButtonHandle();
// 方法01
//为ok 按钮注册事件处理起
// handle.ok.setOnAction(handle);
//为cancel按钮注册事件处理起
// handle.cancel.setOnAction(handle);
// 方法02
// handle.ok.addEventHandler(ActionEvent.ACTION,handle);
// handle.cancel.addEventHandler(ActionEvent.ACTION,handle);
//方法03
/*handle.ok.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
handle.label.setText("你单击的是ok按钮");
}
});
handle.cancel.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
handle.label.setText("你单击的是cancel按钮");
}
});
*/
// 方法4
handle.ok.setOnAction(actionEvent -> {
handle.label.setText("你单击的是ok按钮");
});
handle.cancel.setOnAction(actionEvent -> {
handle.label.setText("你单击的是cancel按钮");
});
// 圆
final Circle circle=new Circle(140,50,40, Color.YELLOWGREEN);
// 为圆对象设置鼠标事件处理
//鼠标进入事件
circle.setOnMouseEntered(e->{
handle.label.setText("鼠标进入圆");
});
// 鼠标离开事件
circle.setOnMouseExited(
e->handle.label.setText("鼠标离开圆")
);
// 鼠标按压事件
circle.setOnMousePressed(e->{
handle.label.setText("鼠标被按下");
});
circle.setOnMouseDragged(e->{
circle.setCenterX(e.getX());
circle.setCenterY(e.getY());
});
Text text=new Text(300,220,"M");
root.setLayoutX(100);
root.setLayoutY(300);
// root.setAlignment(Pos.CENTER);
root.getChildren().addAll(handle.ok,handle.cancel,handle.label,circle,text);
primaryStage.setScene(new Scene(root, 640, 480));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
posted on 2019-06-03 11:24 Indian_Mysore 阅读(1065) 评论(0) 编辑 收藏 举报