Java FX组合框重置问题

当我尝试使用以下代码清除组合框时:

代码:

public class ComboController implements Initializable
{

@FXML
ComboBox firstcombobox=new ComboBox();
@FXML
ComboBox secondcombobox=new ComboBox();
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
    // TODO Auto-generated method stub
    firstcombobox.getItems().add("firabc");
    firstcombobox.getItems().add("firbcd");

    secondcombobox.getItems().add("seccde");
    secondcombobox.getItems().add("secdef");
}
@FXML
public void firstcomboboxAction()
{
    secondcombobox.getSelectionModel().clearSelection();
    secondcombobox.getItems().clear();
    System.out.println(firstcombobox.getSelectionModel().getSelectedItem());
}

public void secondcomboboxAction()
{
    System.out.println(secondcombobox.getSelectionModel().getSelectedItem());
    System.out.println("my name is vinay");
}

}

它会自动调用动作事件

首先,我从第二个组合框中选择了“ seccde”
然后我从第一个组合框中选择了“ firabc”

我收到的输出是:

seccde
my name is vinay
null
my name is vinay
firabc

但是应该是:

seccde
my name is vinay

firabc  [with an empty firstcombobox]

Fxml:

<AnchorPane xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="application.ComboController">
<ComboBox fx:id="firstcombobox" onAction="#firstcomboboxAction"  >
<ComboBox fx:id="secondcombobox" onAction="#secondcomboboxAction" >

解决方法:

输出正是您所期望的.

首先,在第二个组合框中选择一些内容.这将调用第二个组合框的处理程序,并提供输出

seccde
my name is vinay

然后,您在第一个组合框中选择一个项目.这将调用第一个组合框的处理程序.该组合框的处理程序首先清除第二个组合框的所有项目,这是副作用,将第二个组合框的value属性设置为null.这将导致第二个组合框的动作处理程序被调用,生成输出

null
my name is vinay

然后,第二个组合框的处理程序生成输出

firabc

当然,此时第二个组合框将没有任何物品.

这完全符合ComboBox的Javadocs.特别是,docs for the onAction handler将处理程序描述如下:

The ComboBox action, which is invoked whenever the ComboBox value
property is changed. This may be due to the value property being
programmatically changed, when the user selects an item in a popup
list or dialog, or, in the case of editable ComboBoxes, it may be when
the user provides their own input (be that via a TextField or some
other input mechanism.

上一篇:java-如何使用SmartGWT手动/以编程方式打开ComboboxItem / SelectItem的pickList?


下一篇:linux驱动工程面试必问知识点