JavaFX组合框应何时触发其onAction?

时间:2019-06-04 05:20:20

标签: java javafx combobox

我有一个JavaFX组合框,在其中选择了一个项目后,将在另一个组合框中填充相关项目的列表。因此,我将组合框的onAction设置为handleSelect(),这是负责填充第二个组合框的函数。

何时handleSelect()应该被触发?当我从组合框中选择一个项目时,将按预期触发handleSelect()。但是,即使第二个组合框未设置onAction,当我单击第二个组合框时也会触发handleSelect()。此外,当我单击另一个窗口时,将触发handleSelect()

这是JavaFX组合框的onAction的预期行为吗?

顺便说一句,这曾经有用,现在却不起作用,我也不知道为什么。这是代码...

我有两个comboBox,一个叫做comboVariable,另一个叫做comboOperator。从comboVariable中选择变量后,comboOperator框将填充对所选变量类型有意义的关系运算符。为此,我创建了一个名为UserVariable的类和一个枚举类型RelationOperator。

@FXML ComboBox<ComboBoxItem<String>> comboVariable;
@FXML ComboBox<SimpleConditional.RelationalOperator> comboOperator;

public void initWindow()
{
    setContents();
}

public void setContents()
{
    System.out.println("setContents called");
    comboVariable.getItems().clear();
    if (getVars().size() > 0) {
        for(Map.Entry<String, UserVariable<? extends Comparable<?>>> varEntry : getVars().entrySet()) {
            comboVariable.getItems().add(new ComboBoxItem<String>(varEntry.getKey(), true));
        }
    }

    // make comboVariable autocomplete
    FxUtil.autoCompleteComboBox(comboVariable, 
            (typedText, itemToCompare) -> itemToCompare.getName().toLowerCase().contains(typedText.toLowerCase()) 
    );
}

@FXML public void handleSelect()
// This method is called whenever a variable name is selected in the comboVariable combobox
{
    System.out.println("handleSelectVar called");

    ComboBoxItem<String> selectedItem = FxUtil.getComboBoxValue(comboVariable);

    if (selectedItem == null) return;

    String varName = selectedItem.getName();

    UserVariable<?> selectedVar = getVar(varName);
    if (selectedVar == null) return;

    myVarType = selectedVar.getType();

    setComboAndLabelBasedOnType();
}

private void setComboAndLabelBasedOnType()
// This helper function is called by handleSelect()
// It sets the available operators to be == and != for Strings and Bool and makes all operators available for
// Doubles and Integers.
{
    System.out.println("setComboAndLabelBasedOnType called");

    comboOperator.getItems().clear();

    switch (myVarType) {
    case STRING:
    case BOOL:
        comboOperator.getItems().addAll(RelationalOperator.EQ, RelationalOperator.NE);
        break;
    case DOUBLE:
    case INT:
        comboOperator.getItems().addAll(RelationalOperator.EQ, RelationalOperator.NE, 
                RelationalOperator.GT, RelationalOperator.GE, RelationalOperator.LT, 
                RelationalOperator.LE);
        break;
    }
}

0 个答案:

没有答案