在JavaFX应用程序中设置和获取参数

在JavaFX应用程序中设置和获取参数,java,javafx,Java,Javafx,我的应用程序中有这样一种方法,它使用一个helper类来构造RadioButtons:Mode。我想为用户选择的单选按钮调用createModesRadios方法.getText()。我还想保存用户的选择,以便在以后的使用中记住它们。是否有一种简单的方法可以调用它们并将选项设置到复选框、单选按钮和前缀选择组合框中? 我使用一个模型类Configuration.java来存储信息,因为我需要处理一些用户输入的计算。我想把上面提到的控制器的选择也存储在里面 我班的一部分 public class C

我的应用程序中有这样一种方法,它使用一个helper类来构造
RadioButton
s:
Mode
。我想为用户选择的
单选按钮调用
createModesRadios
方法
.getText()
。我还想保存用户的选择,以便在以后的使用中记住它们。是否有一种简单的方法可以调用它们并将选项设置到
复选框、
单选按钮和
前缀选择组合框中?
我使用一个模型类
Configuration.java
来存储信息,因为我需要处理一些用户输入的计算。我想把上面提到的控制器的选择也存储在里面

我班的一部分

public class ConfigurationEditDialogController {

// General Tab
@FXML
private TextField configurationNameField;
@FXML
private TextField commentField;
@FXML
private TextField creationTimeField;
@FXML
private TextField startAddress;

@FXML
private ToggleSwitch triggerEnable;
@FXML
private ToggleSwitch softwareTrigger;
@FXML
private ToggleSwitch ctsEnable;


// Data Acquisition Tab
@FXML
private Pane dataAcquisitionTab;

@FXML
private Button okButton;

private Mode[] modes = new Mode[]{
        new Mode("Vertical", 4),
        new Mode("Hybrid", 2),
        new Mode("Horizontal", 1)
};
private int count = Stream.of(modes).mapToInt(Mode::getCount).max().orElse(0);
private ToggleGroup group = new ToggleGroup();
private IntegerProperty elementCount = new SimpleIntegerProperty();
private ObservableMap<Integer, String> elements = FXCollections.observableHashMap();
CheckBox[] checkBoxes = new CheckBox[count];

private ObservableList<String> options = FXCollections.observableArrayList(
        "ciao",
        "hello",
        "halo");





private Stage dialogStage;
private Configuration configuration;
private boolean okClicked = false;


/**
 * Initializes the controller class. This method is automatically called
 * after the fxml file has been loaded.
 */
@FXML
private void initialize() {





    HBox radioBox = createModesRadios(elementCount, modes);
    GridPane grid = new GridPane();
    VBox root = new VBox(20, radioBox);
    root.setPrefSize(680, 377);
    grid.setHgap(40);
    grid.setVgap(30);
    grid.setAlignment(Pos.CENTER);



    elementCount.addListener((o, oldValue, newValue) -> {
        // uncheck checkboxes, if too many are checked
        updateCheckBoxes(checkBoxes, newValue.intValue(), -1);
    });

    for (int i = 0; i < count; i++) {
        final Integer index = i;
        CheckBox checkBox = new CheckBox();
        checkBoxes[i] = checkBox;

        PrefixSelectionComboBox<String> comboBox = new PrefixSelectionComboBox<>();
        comboBox.setItems(options);
        comboBox.setPromptText("Select Test Bus " + i);
        comboBox.setPrefWidth(400);
        comboBox.setVisibleRowCount(options.size() -1);
        comboBox.valueProperty().addListener((o, oldValue, newValue) -> {
            // modify value in map on value change
            elements.put(index, newValue);
        });
        comboBox.setDisable(true);

        checkBox.selectedProperty().addListener((o, oldValue, newValue) -> {
            comboBox.setDisable(!newValue);
            if (newValue) {
                // put the current element in the map
                elements.put(index, comboBox.getValue());

                // uncheck checkboxes that exceed the required count keeping the current one unmodified
                updateCheckBoxes(checkBoxes, elementCount.get(), index);
            } else {
                elements.remove(index);
            }

        });
        grid.addRow(i, comboBox, checkBox);


    }


    // enable Ok button iff the number of elements is correct
    okButton.disableProperty().bind(elementCount.isNotEqualTo(Bindings.size(elements)));

    root.getChildren().add(grid);
    dataAcquisitionTab.getChildren().add(root);



}

/**
 * Create Radio Buttons with Mode class helper
 *
 * @param count
 * @param modes
 * @return
 */
private HBox createModesRadios(IntegerProperty count, Mode... modes) {
    ToggleGroup group = new ToggleGroup();
    HBox result = new HBox(50);
    result.setPadding(new Insets(20, 0, 0, 0));
    result.setAlignment(Pos.CENTER);
    for (Mode mode : modes) {
        RadioButton radio = new RadioButton(mode.getText());
        radio.setToggleGroup(group);
        radio.setUserData(mode);
        result.getChildren().add(radio);
        radio =

    }
    if (modes.length > 0) {
        group.selectToggle((Toggle) result.getChildren().get(0));
        count.bind(Bindings.createIntegerBinding(() -> ((Mode) group.getSelectedToggle().getUserData()).getCount(), group.selectedToggleProperty()));

        } else {
        count.set(0);
    }
    return result;
}


/**
 * Method for updating CheckBoxes depending on the selected modek
 *
 * @param checkBoxes
 * @param requiredCount
 * @param unmodifiedIndex
 */
private static void updateCheckBoxes(CheckBox[] checkBoxes, int requiredCount, int unmodifiedIndex) {
    if (unmodifiedIndex >= 0 && checkBoxes[unmodifiedIndex].isSelected()) {
        requiredCount--;
    }
    int i;
    for (i = 0; i < checkBoxes.length && requiredCount > 0; i++) {
        if (i != unmodifiedIndex && checkBoxes[i].isSelected()) {
            requiredCount--;
        }
    }

    for (; i < checkBoxes.length; i++) {
        if (i != unmodifiedIndex) {
            checkBoxes[i].setSelected(false);
        }
    }
}

/**
 * Sets the stage of this dialog.
 *
 * @param dialogStage
 */
public void setDialogStage(Stage dialogStage) {
    this.dialogStage = dialogStage;
}


/**
 * Sets the configuration to be edited in the dialog.
 *
 * @param configuration
 */
public void setConfiguration(Configuration configuration) {
    this.configuration = configuration;

    configurationNameField.setText(configuration.getConfigurationName());
    commentField.setText(configuration.getComment());

    //Set the comboboxes and the checkboxes and the radiobutton

    creationTimeField.setText(LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm")));
}

/**
 * Returns true if the user clicked OK, false otherwise.
 *
 * @return
 */
public boolean isOkClicked() {
    return okClicked;
}

/**
 * Called when the user clicks ok.
 */
@FXML
private void handleOk() {
    if (isInputValid()) {
        configuration.setConfigurationName(configurationNameField.getText());
        configuration.setComment(commentField.getText());
        configuration.setTestBus1(elements.get(0));
        configuration.setTestBus2(elements.get(1));
        configuration.setTestBus3(elements.get(2));
        configuration.setTestBus4(elements.get(3));
        configuration.setCreationTime(DateTimeUtil.parse(creationTimeField.getText()));

        // Store the information of the sample mode (vertical, hybrid or horizontal).


        okClicked = true;
        dialogStage.close();
    }
}
public class Mode {

private final String text;
private final int count;

public Mode(String text, int count) {
    this.text = text;
    this.count = count;
}

public String getText() {
    return text;
}

public int getCount() {
    return count;
}
}
    Properties props = new Properties();

    // Set the properties to be saved
    props.setProperty("triggerMode", triggerMode.get());
    props.setProperty("acquisitionTime", String.valueOf(acquisitionTime.get()));

    // Write the file
    try {
        File configFile = new File("config.xml");
        FileOutputStream out = new FileOutputStream(configFile);
        props.storeToXML(out,"Configuration");
    } catch (IOException e) {
        e.printStackTrace();
    }
Configuration.java

public class Configuration {

private final StringProperty configurationName;
private final StringProperty comment;
private final StringProperty testBus1;
private final StringProperty testBus2;
private final StringProperty testBus3;
private final StringProperty testBus4;
private final StringProperty triggerSource;
private final StringProperty sampleMode;
private final StringProperty icDesign;
private final StringProperty triggerMode;
private final DoubleProperty acquisitionTime;
private final ObjectProperty<LocalDateTime> creationTime;

/**
 * Default constructor.
 */
public Configuration() {
    this(null, null);
}

/**
 * Constructor with some initial data.
 *
 * @param configurationName
 * @param comment
 */
public Configuration(String configurationName, String comment) {      //todo initialize null values
    this.configurationName = new SimpleStringProperty(configurationName);
    this.comment = new SimpleStringProperty(comment);

    // Some initial sample data, just for testing.
    this.testBus1 = new SimpleStringProperty("");
    this.testBus2 = new SimpleStringProperty("");
    this.testBus3 = new SimpleStringProperty("");
    this.testBus4 = new SimpleStringProperty("");
    this.triggerSource = new SimpleStringProperty("");
    this.sampleMode = new SimpleStringProperty("");
    this.icDesign = new SimpleStringProperty("Ceres");
    this.triggerMode = new SimpleStringProperty("Internal");
    this.acquisitionTime = new SimpleDoubleProperty(2346.45);
    this.creationTime = new SimpleObjectProperty<>(LocalDateTime.of(2010, 10, 20,
            15, 12));
}


/**
 *  Getters and Setters for the variables of the model class. '-Property' methods for the lambdas
 *  expressions to populate the table's columns (just a few used at the moment, but everything
 *  was created with scalability in mind, so more table columns can be added easily)
 */

// If more details in the table are needed just add a column in
// the ConfigurationOverview.fxml and use these methods.

// Configuration Name
public String getConfigurationName() {
    return configurationName.get();
}
public void setConfigurationName(String configurationName) {
    this.configurationName.set(configurationName);
}
public StringProperty configurationNameProperty() {
    return configurationName;
}

// Comment
public String getComment() {
    return comment.get();
}
public void setComment (String comment) {
    this.comment.set(comment);
}
public StringProperty commentProperty() {
    return comment;
}

// Test Bus 1
public String getTestBus1() {
    return testBus1.get();
}
public void setTestBus1(String testBus1) {
    this.testBus1.set(testBus1);
}
public StringProperty testBus1Property() {
    return testBus1;
}

// Test Bus 2
public String getTestBus2() {
    return testBus2.get();
}
public void setTestBus2(String testBus2) {
    this.testBus2.set(testBus2);
}
public StringProperty testBus2Property() {
    return testBus2;
}

// Test Bus 3
public String getTestBus3() {
    return testBus3.get();
}
public void setTestBus3(String testBus3) {
    this.testBus3.set(testBus3);
}
public StringProperty testBus3Property() {
    return testBus3;
}

// Test Bus 4
public String getTestBus4() {
    return testBus4.get();
}
public void setTestBus4(String testBus4) {
    this.testBus4.set(testBus4);
}
public StringProperty testBus4Property() {
    return testBus4;
}

// Trigger Source
public String getTriggerSource(){
    return triggerSource.get();
}
public void setTriggerSource (String triggerSource){
    this.triggerSource.set(triggerSource);
}
public StringProperty triggerSourceProperty() {
    return triggerSource;
}

// Sample Mode
public String getSampleMode() {
    return sampleMode.get();
}
public void setSampleMode (String sampleMode){
    this.sampleMode.set(sampleMode);
}
public StringProperty sampleModeProperty() {return sampleMode;}

// IC Design
public String getIcDesign() {
    return icDesign.get();
}
public void setIcDesign (String icDesign){
    this.icDesign.set(icDesign);
}
public StringProperty icDesignProperty() {
    return icDesign;
}

// Trigger Mode
public String getTriggerMode() {
    return triggerMode.get();
}
public void setTriggerMode (String triggerMode){
    this.triggerMode.set(triggerMode);
}
public StringProperty triggerModeProperty() {return triggerMode;}

// Acquisition Time
public double getAcquisitionTime() {
    return acquisitionTime.get();
}
public void setAcquisitionTime(double acquisitionTime){
    this.acquisitionTime.set(acquisitionTime);
}
public DoubleProperty acquisitionTimeProperty() {
    return acquisitionTime;
}

// Last modified - Creation Time
@XmlJavaTypeAdapter(LocalDateTimeAdapter.class)
public LocalDateTime getCreationTime() {
    return creationTime.get();
}
public void setCreationTime(LocalDateTime creationTime){
        this.creationTime.set(creationTime);
    }
public ObjectProperty<LocalDateTime> creationTimeProperty() {
    return creationTime;
}
}
公共类配置{
私有最终StringProperty配置名称;
私人财产评论;
私有财产测试总线1;
私有财产测试总线2;
私有财产测试总线3;
私有财产测试总线4;
私人最终财产触发源;
私有最终StringProperty采样模式;
私人最终设计;
私有最终StringProperty triggerMode;
私有财产最终取得时间;
私有最终对象属性creationTime;
/**
*默认构造函数。
*/
公共配置(){
这个(空,空);
}
/**
*具有一些初始数据的构造函数。
*
*@param configurationName
*@param评论
*/
公共配置(字符串配置名称,字符串注释){//todo初始化空值
this.configurationName=新的SimpleStringProperty(configurationName);
this.comment=新的SimpleStringProperty(comment);
//一些初始样本数据,仅用于测试。
this.testBus1=新的SimpleStringProperty(“”);
this.testBus2=新的SimpleStringProperty(“”);
this.testBus3=新的SimpleStringProperty(“”);
this.testBus4=新的SimpleStringProperty(“”);
this.triggerSource=新的SimpleStringProperty(“”);
this.sampleMode=新的SimpleStringProperty(“”);
this.icDesign=新的SimpleStringProperty(“Ceres”);
this.triggerMode=新的SimpleStringProperty(“内部”);
this.acquisitionTime=新的SimpleDoubleProperty(2346.45);
this.creationTime=新的SimpleObject属性(LocalDateTime.of(2010,10,20,
15, 12));
}
/**
*模型类变量的getter和setter。lambdas的'-Property'方法
*用于填充表列的表达式(目前只使用了一些,但所有
*创建时考虑了可伸缩性,因此可以轻松添加更多表列)
*/
//如果需要表中的更多详细信息,只需在中添加一列即可
//使用ConfigurationOverview.fxml并使用这些方法。
//配置名称
公共字符串getConfigurationName(){
返回configurationName.get();
}
public void setConfigurationName(字符串configurationName){
this.configurationName.set(configurationName);
}
public StringProperty configurationNameProperty(){
返回configurationName;
}
//评论
公共字符串getComment(){
返回comment.get();
}
公共void setComment(字符串注释){
this.comment.set(comment);
}
公共字符串属性commentProperty(){
回复评论;
}
//测试总线1
公共字符串getTestBus1(){
返回testBus1.get();
}
公共void setTestBus1(字符串testBus1){
this.testBus1.set(testBus1);
}
公共StringProperty testBus1Property(){
返回testBus1;
}
//测试总线2
公共字符串getTestBus2(){
返回testBus2.get();
}
公共void setTestBus2(字符串testBus2){
this.testBus2.set(testBus2);
}
公共StringProperty testBus2Property(){
返回testBus2;
}
//测试总线3
公共字符串getTestBus3(){
返回testBus3.get();
}
公共void setTestBus3(字符串testBus3){
this.testBus3.set(testBus3);
}
公共StringProperty testBus3Property(){
返回testBus3;
}
//测试总线4
公共字符串getTestBus4(){
返回testBus4.get();
}
公共void setTestBus4(字符串testBus4){
this.testBus4.set(testBus4);
}
公共StringProperty testBus4Property(){
返回testBus4;
}
//触发源
公共字符串getTriggerSource(){
返回triggerSource.get();
}
public void setTriggerSource(字符串triggerSource){
this.triggerSource.set(triggerSource);
}
public StringProperty triggerSourceProperty(){
返回触发源;
}
//采样模式
公共字符串getSampleMode(){
返回sampleMode.get();
}
public void setSampleMode(字符串采样模式){
this.sampleMode.set(sampleMode);
}
public StringProperty sampleModeProperty(){return sampleMode;}
//集成电路设计
公共字符串getIcDesign(){
返回icDesign.get();
}
公共无效设置icDesign(字符串icDesign){
this.icDesign.set(icDesign);
}
公共字符串属性icDesignProperty(){
返回设计;
}
//触发模式
公共字符串getTriggerMode(){
返回triggerMode.get();
}
公共void setTriggerMode(字符串triggerMode){
this.triggerMode.set(triggerMode);
}
public StringProperty triggerModeProperty(){return triggerMode;}
//采集时间
公共双getAcquisitionTime(){
返回acquisitionTime.get();
}
public void setAcquisitionTime(双重acquisitionTime){
this.acquisitionTime.set(acquisitionTime);
}
public DoubleProperty acquisitionTimeProperty(){
返回获取时间;
}
//上次修改-创建时间
@XmlJavaTypeAdapter(LocalDateTimeAdapter.class)
公共LocalDateTime getCreationTime(){
返回creationTime.get();
}
public void setCreationTime(LocalDateTime creationTime){
this.creationTime.set(creationTime);
}
公共对象属性creationTimeProperty(){
返回creationTime;
}
}
您可以使用该类轻松地在XML文件中读取/写入这样的设置

保存到属性

public class ConfigurationEditDialogController {

// General Tab
@FXML
private TextField configurationNameField;
@FXML
private TextField commentField;
@FXML
private TextField creationTimeField;
@FXML
private TextField startAddress;

@FXML
private ToggleSwitch triggerEnable;
@FXML
private ToggleSwitch softwareTrigger;
@FXML
private ToggleSwitch ctsEnable;


// Data Acquisition Tab
@FXML
private Pane dataAcquisitionTab;

@FXML
private Button okButton;

private Mode[] modes = new Mode[]{
        new Mode("Vertical", 4),
        new Mode("Hybrid", 2),
        new Mode("Horizontal", 1)
};
private int count = Stream.of(modes).mapToInt(Mode::getCount).max().orElse(0);
private ToggleGroup group = new ToggleGroup();
private IntegerProperty elementCount = new SimpleIntegerProperty();
private ObservableMap<Integer, String> elements = FXCollections.observableHashMap();
CheckBox[] checkBoxes = new CheckBox[count];

private ObservableList<String> options = FXCollections.observableArrayList(
        "ciao",
        "hello",
        "halo");





private Stage dialogStage;
private Configuration configuration;
private boolean okClicked = false;


/**
 * Initializes the controller class. This method is automatically called
 * after the fxml file has been loaded.
 */
@FXML
private void initialize() {





    HBox radioBox = createModesRadios(elementCount, modes);
    GridPane grid = new GridPane();
    VBox root = new VBox(20, radioBox);
    root.setPrefSize(680, 377);
    grid.setHgap(40);
    grid.setVgap(30);
    grid.setAlignment(Pos.CENTER);



    elementCount.addListener((o, oldValue, newValue) -> {
        // uncheck checkboxes, if too many are checked
        updateCheckBoxes(checkBoxes, newValue.intValue(), -1);
    });

    for (int i = 0; i < count; i++) {
        final Integer index = i;
        CheckBox checkBox = new CheckBox();
        checkBoxes[i] = checkBox;

        PrefixSelectionComboBox<String> comboBox = new PrefixSelectionComboBox<>();
        comboBox.setItems(options);
        comboBox.setPromptText("Select Test Bus " + i);
        comboBox.setPrefWidth(400);
        comboBox.setVisibleRowCount(options.size() -1);
        comboBox.valueProperty().addListener((o, oldValue, newValue) -> {
            // modify value in map on value change
            elements.put(index, newValue);
        });
        comboBox.setDisable(true);

        checkBox.selectedProperty().addListener((o, oldValue, newValue) -> {
            comboBox.setDisable(!newValue);
            if (newValue) {
                // put the current element in the map
                elements.put(index, comboBox.getValue());

                // uncheck checkboxes that exceed the required count keeping the current one unmodified
                updateCheckBoxes(checkBoxes, elementCount.get(), index);
            } else {
                elements.remove(index);
            }

        });
        grid.addRow(i, comboBox, checkBox);


    }


    // enable Ok button iff the number of elements is correct
    okButton.disableProperty().bind(elementCount.isNotEqualTo(Bindings.size(elements)));

    root.getChildren().add(grid);
    dataAcquisitionTab.getChildren().add(root);



}

/**
 * Create Radio Buttons with Mode class helper
 *
 * @param count
 * @param modes
 * @return
 */
private HBox createModesRadios(IntegerProperty count, Mode... modes) {
    ToggleGroup group = new ToggleGroup();
    HBox result = new HBox(50);
    result.setPadding(new Insets(20, 0, 0, 0));
    result.setAlignment(Pos.CENTER);
    for (Mode mode : modes) {
        RadioButton radio = new RadioButton(mode.getText());
        radio.setToggleGroup(group);
        radio.setUserData(mode);
        result.getChildren().add(radio);
        radio =

    }
    if (modes.length > 0) {
        group.selectToggle((Toggle) result.getChildren().get(0));
        count.bind(Bindings.createIntegerBinding(() -> ((Mode) group.getSelectedToggle().getUserData()).getCount(), group.selectedToggleProperty()));

        } else {
        count.set(0);
    }
    return result;
}


/**
 * Method for updating CheckBoxes depending on the selected modek
 *
 * @param checkBoxes
 * @param requiredCount
 * @param unmodifiedIndex
 */
private static void updateCheckBoxes(CheckBox[] checkBoxes, int requiredCount, int unmodifiedIndex) {
    if (unmodifiedIndex >= 0 && checkBoxes[unmodifiedIndex].isSelected()) {
        requiredCount--;
    }
    int i;
    for (i = 0; i < checkBoxes.length && requiredCount > 0; i++) {
        if (i != unmodifiedIndex && checkBoxes[i].isSelected()) {
            requiredCount--;
        }
    }

    for (; i < checkBoxes.length; i++) {
        if (i != unmodifiedIndex) {
            checkBoxes[i].setSelected(false);
        }
    }
}

/**
 * Sets the stage of this dialog.
 *
 * @param dialogStage
 */
public void setDialogStage(Stage dialogStage) {
    this.dialogStage = dialogStage;
}


/**
 * Sets the configuration to be edited in the dialog.
 *
 * @param configuration
 */
public void setConfiguration(Configuration configuration) {
    this.configuration = configuration;

    configurationNameField.setText(configuration.getConfigurationName());
    commentField.setText(configuration.getComment());

    //Set the comboboxes and the checkboxes and the radiobutton

    creationTimeField.setText(LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm")));
}

/**
 * Returns true if the user clicked OK, false otherwise.
 *
 * @return
 */
public boolean isOkClicked() {
    return okClicked;
}

/**
 * Called when the user clicks ok.
 */
@FXML
private void handleOk() {
    if (isInputValid()) {
        configuration.setConfigurationName(configurationNameField.getText());
        configuration.setComment(commentField.getText());
        configuration.setTestBus1(elements.get(0));
        configuration.setTestBus2(elements.get(1));
        configuration.setTestBus3(elements.get(2));
        configuration.setTestBus4(elements.get(3));
        configuration.setCreationTime(DateTimeUtil.parse(creationTimeField.getText()));

        // Store the information of the sample mode (vertical, hybrid or horizontal).


        okClicked = true;
        dialogStage.close();
    }
}
public class Mode {

private final String text;
private final int count;

public Mode(String text, int count) {
    this.text = text;
    this.count = count;
}

public String getText() {
    return text;
}

public int getCount() {
    return count;
}
}
    Properties props = new Properties();

    // Set the properties to be saved
    props.setProperty("triggerMode", triggerMode.get());
    props.setProperty("acquisitionTime", String.valueOf(acquisitionTime.get()));

    // Write the file
    try {
        File configFile = new File("config.xml");
        FileOutputStream out = new FileOutputStream(configFile);
        props.storeToXML(out,"Configuration");
    } catch (IOException e) {
        e.printStackTrace();
    }
这个cre
List<PrefixSelectionComboBox<String>> comboBoxes = new ArrayList<PrefixSelectionComboBox<String>>();
List<CheckBox> checkBoxes = new ArrayList<>();
comboBoxes.add(comboBox);
checkBoxes.add(checkBox);
grid.addRow(i, comboBox, checkBox);
for (PrefixSelectionComboBox cb : comboBoxes) {
    cb.getValue(); // Do with this what you must
}
for (CheckBox cb : checkBoxes) {
    cb.isSelected();
}