JavaFX使用RadioButton、CheckBox实现单选按钮、多选框
程序员文章站
2024-02-03 20:49:58
...
目录
一、环境
jdk8
二、模拟
三、代码
package xyz.hashdog.class31;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.List;
/**
* @author th
* @description: TODO
* @projectName hashdog
* @date 2020/2/1620:48
*/
public class Launch extends Application {
public static void main(String[] args) {
Application.launch(Launch.class, args);
}
@Override
public void start(Stage primaryStage) throws Exception {
AnchorPane an = new AnchorPane();
//指定间距10
HBox box = new HBox(10);
//单选按钮组
ToggleGroup tg = new ToggleGroup();
//单选按钮
RadioButton r1 = new RadioButton("r1");
r1.setToggleGroup(tg);
RadioButton r2 = new RadioButton("r2");
r2.setToggleGroup(tg);
RadioButton r3 = new RadioButton("r3");
r3.setToggleGroup(tg);
RadioButton r4 = new RadioButton("r4");
r4.setToggleGroup(tg);
box.getChildren().addAll(r1, r2, r3, r4);
VBox vbox = new VBox(10);
//多选按钮
CheckBox c1 = new CheckBox("c1");
CheckBox c2 = new CheckBox("c2");
CheckBox c3 = new CheckBox("c3");
CheckBox c4 = new CheckBox("c4");
vbox.getChildren().addAll(c1, c2, c3, c4);
AnchorPane.setTopAnchor(vbox, 20.0);
an.getChildren().addAll(box, vbox);
an.setStyle("-fx-background-color: deepskyblue");
Scene s = new Scene(an);
primaryStage.setScene(s);
primaryStage.setTitle("hashdog");
primaryStage.setWidth(500);
primaryStage.setHeight(300);
//设置窗口不可拉伸
primaryStage.setResizable(false);
primaryStage.show();
//单选组添加选择事件
tg.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
@Override
public void changed(ObservableValue<? extends Toggle> observable, Toggle oldValue, Toggle newValue) {
RadioButton r = (RadioButton) newValue;
System.out.println("已选择:" + r.getText());
}
});
c1.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
System.out.println("已经选择:" + newValue);
}
});
//当点击面板的时候,打印已选择的多选按钮
an.setOnMouseClicked(e -> {
List<CheckBox> list = (List<CheckBox>) (Object) vbox.getChildren();
final StringBuilder str = new StringBuilder("已选择:");
list.forEach(item -> {
if (item.isSelected()) {
str.append(item.getText() + ",");
}
});
System.out.println(str);
});
}
}
上一篇: 理解 maven 多模块项目依赖关系
下一篇: sklearn学习——决策树分类