JavaFX UI组件——Combo Box

本文展示了一个使用JavaFX创建的组合框示例,包括电子邮件地址和优先级选择。通过代码实现了不同优先级颜色提示,以及发送消息的功能。

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

代码示例:

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Callback;

public class ComboBoxSample extends Application {
        public static void main(String[] args) {
        launch(args);
    }
    
    final Button button = new Button ("Send");
    final Label notification = new Label ();
    final TextField subject = new TextField("");
    final TextArea text = new TextArea ("");
    
    
    String address = " ";
    
    @Override public void start(Stage stage) {
        stage.setTitle("ComboBoxSample");
        Scene scene = new Scene(new Group(), 500, 270);
        
        final ComboBox emailComboBox = new ComboBox();
        emailComboBox.getItems().addAll(
            "jacob.smith@example.com",
            "isabella.johnson@example.com",
            "ethan.williams@example.com",
            "emma.jones@example.com",
            "michael.brown@example.com"  
        );
        
        emailComboBox.setPromptText("Email address");
        emailComboBox.setEditable(true);        
        emailComboBox.setOnAction((Event ev) -> {
            address = 
                emailComboBox.getSelectionModel().getSelectedItem().toString();    
        });
        
         
        final ComboBox priorityComboBox = new ComboBox();
        priorityComboBox.getItems().addAll(
            "Highest",
            "High",
            "Normal",
            "Low",
            "Lowest" 
        );   
        priorityComboBox.setValue("Normal");
        priorityComboBox.setCellFactory(
            new Callback<ListView<String>, ListCell<String>>() {
                @Override public ListCell<String> call(ListView<String> param) {
                    final ListCell<String> cell = new ListCell<String>() {
                        {
                            super.setPrefWidth(100);
                        }    
                        @Override public void updateItem(String item, 
                            boolean empty) {
                                super.updateItem(item, empty);
                                if (item != null) {
                                    setText(item);    
                                    if (item.contains("High")) {                                    
                                        setTextFill(Color.RED);
                                    }
                                    else if (item.contains("Low")){
                                        setTextFill(Color.GREEN);
                                    }
                                    else {
                                        setTextFill(Color.BLACK);
                                    }
                                }
                                else {
                                    setText(null);
                                }
                            }
                };
                return cell;
            }
                        
        });
     
        
        button.setOnAction((ActionEvent e) -> {
            if (emailComboBox.getValue() != null && 
                    !emailComboBox.getValue().toString().isEmpty()){
                notification.setText("Your message was successfully sent"
                        + " to " + address);
                emailComboBox.setValue(null);
                if (priorityComboBox.getValue() != null &&
                        !priorityComboBox.getValue().toString().isEmpty()){
                    priorityComboBox.setValue(null);
                }
                subject.clear();
                text.clear();
            }
            else {
                notification.setText("You have not selected a recipient!");
            }
        });
              
        GridPane grid = new GridPane();
        grid.setVgap(4);
        grid.setHgap(10);
        grid.setPadding(new Insets(5, 5, 5, 5));
        grid.add(new Label("To: "), 0, 0);
        grid.add(emailComboBox, 1, 0);
        grid.add(new Label("Priority: "), 2, 0);
        grid.add(priorityComboBox, 3, 0);
        grid.add(new Label("Subject: "), 0, 1);
        grid.add(subject, 1, 1, 3, 1);            
        grid.add(text, 0, 2, 4, 1);
        grid.add(button, 0, 3);
        grid.add (notification, 1, 3, 3, 1);
        
        Group root = (Group)scene.getRoot();
        root.getChildren().add(grid);
        stage.setScene(scene);
        stage.show();

    }    
}

 

### ControlsFX JavaFX UI库 使用指南与示例代码 ControlsFX 是一个专门为 JavaFX 提供高质量 UI 控件的开源库,旨在扩展 JavaFX 的核心功能[^3]。它提供了一系列增强型控件和工具类,帮助开发者构建更加复杂、交互性强的应用程序。 #### 1. **主要功能模块** ControlsFX 主要分为以下几个部分: - **Dialogs**: 实现自定义对话框。 - **Action APIs**: 简化事件处理机制。 - **Effects and Animations**: 增加视觉效果和动画支持。 - **Custom Nodes**: 提供额外的节点组件,如 `CheckComboBox`, `ToggleNode` 等。 --- #### 2. **引入依赖项** 如果使用 Maven 构建项目,则可以在 `pom.xml` 文件中添加以下依赖配置来导入 ControlsFX[^3]: ```xml <dependency> <groupId>org.controlsfx</groupId> <artifactId>controlsfx</artifactId> <version>11.1.0</version> <!-- 替换为最新版本 --> </dependency> ``` 对于 Gradle 用户,可将此行加入 build.gradle 文件: ```gradle implementation 'org.controlsfx:controlsfx:11.1.0' // 替换为最新版本号 ``` --- #### 3. **常用控件详解** ##### a. CheckComboBox 这是一个改进版的下拉列表,允许操作。以下是具体用法: ```java import org.controlsfx.control.CheckComboBox; ObservableList<String> items = FXCollections.observableArrayList( "Item 1", "Item 2", "Item 3" ); CheckComboBox<String> checkComboBox = new CheckComboBox<>(items); checkComboBox.getCheckModel().checkAll(); // 默认全所有项 ``` ##### b. ToggleSwitch 类似于 iOS 上的开关按钮,用于开启/关闭状态切换。 ```java import org.controlsfx.control.ToggleSwitch; ToggleSwitch toggleSwitch = new ToggleSwitch("Enable Feature"); toggleSwitch.selectedProperty().addListener((obs, oldValue, newValue) -> { System.out.println(newValue ? "Feature Enabled" : "Feature Disabled"); }); ``` ##### c. Notifications 弹出通知提示信息给用户查看。 ```java Notifications.create() .title("Important Message") .text("This is an example notification.") .graphic(new ImageView("/icons/info.png")) .hideAfter(Duration.seconds(5)) .showInformation(); ``` --- #### 4. **对话框管理** ControlsFX 对话框 API 提供了一种简单的方式来请求用户的输入或者确认某些动作的结果[^3]: ```java ButtonType result = Dialogs.create() .owner(primaryStage) .title("Confirmation Required") .masthead(null) .message("Are you sure to proceed?") .buttons(ButtonType.YES, ButtonType.NO) .defaultButton(ButtonType.YES) .cancelButton(ButtonType.NO) .showConfirm(); if (result == ButtonType.YES){ System.out.println("User confirmed."); } else{ System.out.println("Operation canceled by user."); } ``` --- #### 5. **样式定制** 如同其他 JavaFX 节点一样,ControlsFX 组件也支持通过 CSS 修改外观。例如改变 `CheckComboBox` 的背景颜色: ```css .check-combo-box-button { -fx-background-color: lightblue; } .check-menu-item:checked .check { -fx-fill: red; /* 当前勾标记的颜色 */ } ``` 随后只需确保该样式表被加载至场景即可生效。 --- #### 6. **综合示例** 下面是一段完整的例子,展示如何利用 ControlsFX 创建带有组合框及通知系统的窗口界面: ```java import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.VBox; import javafx.stage.Stage; import org.controlsfx.control.CheckComboBox; import org.controlsfx.dialog.Dialogs; public class ControlsFxExample extends Application { @Override public void start(Stage primaryStage) throws Exception { VBox vbox = new VBox(10); ObservableList<String> options = FXCollections.observableArrayList("Option A","Option B","Option C"); CheckComboBox<String> combo = new CheckComboBox<>(options); Button notifyBtn = new Button("Show Notification"); notifyBtn.setOnAction(e->{ String selectedItems = String.join(", ",combo.getCheckModel().getCheckedItems()); Dialogs.create() .title("Selected Items") .message("You have chosen:" +selectedItems ) .showInformation(); }); vbox.getChildren().addAll(combo,notifyBtn ); Scene scene = new Scene(vbox ,300 ,200 ); primaryStage.setTitle ("ControlsFX Example "); primaryStage.setScene(scene ); primaryStage.show (); } public static void main(String[] args ){ launch(args ); } } ``` --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值