上一篇我们讲解了Hello World演示,主要用到Label标签的功能,
这里我们要介绍的是最常用的控件之一:按钮
在现在的软件开发过程中还没发现没有用到按钮的应用,
基本上用户的操作输入都赋予给它,让他去触发后面的事件,
做出对应的反应或操作。
1. 代码
这里的主要操作是有两个按钮:加1、减1
然后按对应的按钮,就会有对应的操作。
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
import java.util.concurrent.atomic.AtomicInteger;
public class ButtonDemo extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
stage.setTitle("设置标题");
// 流式布局:按照控件的添加次序按个摆放,按照从上到下、从左到右的次序摆放。
FlowPane pane = new FlowPane(10, 10);
// 居中显示
pane.setAlignment(Pos.CENTER);
// 场景
Scene scene = new Scene(pane, 800, 600);
stage.setScene(scene);
AtomicInteger num = new AtomicInteger();
// 标签
Label label = new Label("初始值:" + num);
// 按钮
Button addButton = new Button("加1");
Button subButton = new Button("减1");
// 处理按钮事件
addButton.setOnAction((event) -> label.setText("当前值:" + num.incrementAndGet()));
subButton.setOnAction((event) -> label.setText("当前值:" + num.decrementAndGet()));
// 将标签、按钮添加到场景
pane.getChildren().addAll(addButton, subButton, label);
stage.show();
}
}
2. 讲解
这里的逻辑很简单,初始的时候显示了两个按钮和一个Label对应如下所示。
然后我们点击一下加1的按钮试一下,可以看到Label的值变了。
接着就是另一个按钮,也会有相应的操作。
可以看到,上面的逻辑基本上都能接受,
那我们处理的地方也可以看到就是短短的一行,
这就是Lambda的强大,后期我们再好好聊聊它。
3. 代码仓库
有喜欢的小伙伴可以学习起来啦,期待你的加入~
https://gitee.com/jack0240/yiyi-fx.git