JavaFX UI组件——Choice Box

本文提供了一个使用 JavaFX 的 ChoiceBox 控件的详细示例,展示了如何创建一个多语言问候界面,用户可以选择不同的语言来更改问候语。代码中包含了设置 ChoiceBox、监听选择变化并更新界面元素的方法。

详解:https://docs.oracle.com/javase/8/javafx/user-interface-tutorial/choice-box.htm

代码示例:

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class ChoiceBoxSample extends Application {

    Rectangle rect = new Rectangle(150, 30);
    final Label label = new Label("Hello");

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        scene.setFill(Color.ALICEBLUE);
        stage.setScene(scene);
        stage.show();

        stage.setTitle("ChoiceBox Sample");
        stage.setWidth(300);
        stage.setHeight(200);
      
        label.setFont(Font.font("Arial", 25));
        label.setLayoutX(40);

       final String[] greetings = new String[]{"Hello", "Hola", "Привет", "你好",
           "こんにちは"};
       final ChoiceBox cb = new ChoiceBox(FXCollections.observableArrayList(
           "English", "Español", "Русский", "简体中文", "日本語")
       );
                                     
       cb.getSelectionModel().selectedIndexProperty().addListener(
           (ObservableValue<? extends Number> ov,
                Number old_val, Number new_val) -> {
                    label.setText(greetings[new_val.intValue()]);            
        });
             
        cb.setTooltip(new Tooltip("Select the language"));
        cb.setValue("English");
        HBox hb = new HBox();
        hb.getChildren().addAll(cb, label);
        hb.setSpacing(30);
        hb.setAlignment(Pos.CENTER);
        hb.setPadding(new Insets(10, 0, 0, 10));

        ((Group) scene.getRoot()).getChildren().add(hb);
        
       
       
        
    }
}

 

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值