不是一个完整的答案,但希望足以让您完成您的应用。
您需要创建一个ChangeListener 来监听ChoiceBox 所选值的变化,并根据ChoiceBox 中所选值启用或禁用相关的TextFields。
以下代码创建了一个类似于屏幕截图中的 GUI,但仅根据所选数据库启用(或禁用)dbName 和 path 文本字段。
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class ChooseDb extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
GridPane root = new GridPane();
root.setHgap(10.0);
root.setVgap(10.0);
root.setPadding(new Insets(20, 20, 20, 20));
Label hostLabel = new Label("Host");
root.add(hostLabel, 0, 0);
TextField hostTextField = new TextField();
root.add(hostTextField, 1, 0);
Label portLabel = new Label("Port");
root.add(portLabel, 2, 0);
TextField portTextField = new TextField();
root.add(portTextField, 3, 0);
Label usernameLabel = new Label("Username");
root.add(usernameLabel, 0, 1);
TextField usernameTextField = new TextField();
root.add(usernameTextField, 1, 1);
Label passwordLabel = new Label("Password");
root.add(passwordLabel, 2, 1);
TextField passwordTextField = new TextField();
root.add(passwordTextField, 3, 1);
Label dbNameLabel = new Label("Database name");
root.add(dbNameLabel, 0, 2);
TextField dbNameTextField = new TextField();
dbNameTextField.setDisable(true);
root.add(dbNameTextField, 1, 2);
Label dbPathLabel = new Label("Path to database file");
root.add(dbPathLabel, 2, 2);
TextField dbPathTextField = new TextField();
dbPathTextField.setDisable(true);
root.add(dbPathTextField, 3, 2);
ChoiceBox<String> dbNames = new ChoiceBox<>(FXCollections.observableArrayList("MySQL", "SQLite"));
dbNames.setValue("MySQL");
dbNames.valueProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable,
String oldValue,
String newValue) {
switch (newValue) {
case "MySQL":
dbNameTextField.setDisable(true);
dbPathTextField.setDisable(true);
break;
case "SQLite":
dbNameTextField.setDisable(false);
dbPathTextField.setDisable(false);
break;
}
}
});
root.add(dbNames, 0, 3);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}