javafX初探(选择框)

52 篇文章 0 订阅
47 篇文章 4 订阅

本章我们介绍下拉框的使用。

 

创建下拉框

ChoiceBox cb = new ChoiceBox(FXCollections.observableArrayList(
    "First", "Second", "Third")
);


 

使用ChoiceBox的构造方法来创建一个下拉框,这个构造函数接受一个obervableList。我们也可以是用setItems方法来达到这一目的,如下:

ChoiceBox cb = new ChoiceBox();
cb.setItems(FXCollections.observableArrayList(
    "New Document", "Open ", 
    new Separator(), "Save", "Save as")
);


 

需要指出的是,下拉框不仅仅只能包含文本,也可以包含Separator控件,用来分割选项。如下图所示:

为下拉框设置行为

package com.chu.button;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.Separator;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

public class ChoiceBoxTest extends Application {

	@Override
	public void start(Stage primaryStage) throws Exception {

		FlowPane fp = new FlowPane();
		
		ChoiceBox<Object> cb = new ChoiceBox<>();
		cb.setItems(FXCollections.observableArrayList(
		    "English", "Open ", 
		    new Separator(), "Save", "Save as")
		);
		
		final String [] greeting = {"aaa","bbb","ccc","ddd","eee",};
		
		final Label label = new Label();
		cb.getSelectionModel().selectedIndexProperty().addListener((ov,oldv,newv)->{
			
			label.setText(greeting[newv.intValue()]);
		});
		
		cb.setTooltip(new Tooltip("Select the language"));

		
		fp.getChildren().add(cb);
		fp.getChildren().add(label);
		
		
		
		Scene scene = new Scene(fp,500,300);
		primaryStage.setScene(scene);

		primaryStage.show();
	}

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


设置提示

cb.setTooltip(new Tooltip("Select the language"));


  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值