JavaFX、使用ComboBox和ListView

 


package fx;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import java.util.ArrayList;

public class Exercise16_16 extends Application {

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

    @Override
    public void start(Stage primaryStage) {
        ComboBox<String> selectMode = new ComboBox<>(FXCollections.observableArrayList("SINGLE", "MULTIPLE"));  //选择模式复选框
        selectMode.setValue("SINGLE");  //选择模式设置初值
        HBox topHBox = new HBox(10, new Label("Choose Selection Mode:"), selectMode);
        topHBox.setAlignment(Pos.CENTER);

        ListView<String> listView = new ListView<>();   //列表视图
        listView.getItems().addAll("China", "Japan", "Korea", "India", "Malaysia", "Vietnam");  //列表视图添加值
        listView.setPrefHeight(120);    //列表视图设置高度
        Text text = new Text(); //文本

        selectMode.setOnAction(event -> {   //选择模式注册动作事件
            ObservableList<String> list = selectMode.getItems();    //获取列表
            //设置选择模式
            listView.getSelectionModel().setSelectionMode(list.get(list.indexOf(selectMode.getValue()
                    )).equals("MULTIPLE") ? SelectionMode.MULTIPLE : SelectionMode.SINGLE);
        });
        listView.getSelectionModel().selectedItemProperty().addListener(observable -> { //列表视图添加监听器
            ObservableList<String> list = listView.getSelectionModel().getSelectedItems();
            String string;

            if (list.size() > 1) string = "Selected items are"; //列表大小大于1时,设置为复数
            else string = "Selected item is";

            for (String s : list)   //添加字符串
                string += (" " + s);
            text.setText(string);   //设置字符串
        });

        BorderPane pane = new BorderPane(new ScrollPane(listView));
        pane.setBottom(text);
        pane.setTop(topHBox);

        Scene scene = new Scene(pane);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Exercise16_16");
        primaryStage.show();
    }
}

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值