从 JavaFX 中的选择框中获取所选项目
ChoiceBox
是 JavaFX
库的一部分,我们可以从中获得选定的选项。本教程演示了如何从 JavaFX 中的 ChoiceBox
中获取选定项目。
从 JavaFX 中的 ChoiceBox
中获取所选项目
ChoiceBox
包含一组项目,用户可以从中选择将成为当前选定项目的选项。选择框中的默认选择是空
条目。
以下方法用于使用 ChoiceBox
。
方法 | 说明 |
---|---|
hide() |
此方法将关闭选项列表。 |
setItems(ObservableList value) |
这将设置属性项的值。 |
setValue(T value) |
这将设置属性值的值。 |
getItems() |
这将获得属性项的值。 |
getValue() |
这将获取属性值的值。 |
show() |
这将打开选项列表。 |
我们使用以下方法从选择框中获取选定的项目。
ChoiceBox.getSelectionModel().selectedIndexProperty()
让我们使用 JavaFX 从 ChoiceBox
中获取选定项目。
package delftstack;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.collections.*;
import javafx.beans.value.*;
import javafx.stage.Stage;
public class Choice_Box extends Application {
public void start(Stage Choice_Box_Stage) {
//title for the stage
Choice_Box_Stage.setTitle("ChoiceBox");
//button to show
Button Show_Button = new Button("Show Choice");
// tile pane
TilePane Title_Pane = new TilePane();
// labels
Label Label1 = new Label("This is a choice box, Please select your choice");
Label Label2 = new Label("No Choice selected");
// Choices array
String Choice_Array[] = { "Delftstack 1", "Delftstack 2", "Delftstack 3", "Delftstack 4", "Delftstack 5" };
// choiceBox
ChoiceBox DemoChoiceBox = new ChoiceBox(FXCollections.observableArrayList(Choice_Array));
// adding a listener
DemoChoiceBox.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
// if items of the list are changed
public void changed(ObservableValue ov, Number value, Number new_value) {
// text for the label to the selected item
Label2.setText(Choice_Array[new_value.intValue()] + " is Selected");
}
});
// ChoiceBox
Title_Pane.getChildren().add(Label1);
Title_Pane.getChildren().add(DemoChoiceBox);
Title_Pane.getChildren().add(Label2);
Scene sc = new Scene(Title_Pane, 400, 200);
// Setting the scene
Choice_Box_Stage.setScene(sc);
Choice_Box_Stage.show();
}
public static void main(String args[]) {
// launching the application
launch(args);
}
}
上面的代码演示了使用 JavaFX 从 ChoiceBox
中获取选择项。见输出:
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。