Java NativeSelect等待我选择一个选项

Java NativeSelect等待我选择一个选项,java,if-statement,select,vaadin,Java,If Statement,Select,Vaadin,我使用了一个名为Vaadin的框架,其中我使用了一个NativeSelect,它的工作原理类似于HTML选择。当选择一个选项时,我想设置visible(true) 这是我的密码: List<String> behaviourData = new ArrayList<>(); behaviourData.add(new String("end")); behaviourData.add(new String("end-dx6")); NativeSelect behavio

我使用了一个名为Vaadin的框架,其中我使用了一个NativeSelect,它的工作原理类似于HTML选择。当选择一个选项时,我想设置visible(true)

这是我的密码:

List<String> behaviourData = new ArrayList<>();
behaviourData.add(new String("end"));
behaviourData.add(new String("end-dx6"));
NativeSelect behaviour1 = new NativeSelect("Select", behaviourData);
behaviour1.addValueChangeListener(event -> Notification.show("Value changed:",    String.valueOf(behaviour1.getValue()), Notification.Type.TRAY_NOTIFICATION));
if (behaviour1.getValue().equals("end-dx6")) {
    System.out.print("else if");
    hop1.setVisible(true);
    out1.setVisible(true);
    nextHop.setVisible(true);
    outGoing.setVisible(true);
 }
List behavior data=new ArrayList();
行为数据。添加(新字符串(“结束”);
行为数据。添加(新字符串(“end-dx6”);
NativeSelect行为1=新的NativeSelect(“选择”,行为数据);
行为1.addValueChangeListener(事件->通知.show(“值更改:”,字符串.valueOf(行为1.getValue()),通知.Type.TRAY_通知));
如果(行为1.getValue().equals(“end-dx6”)){
系统输出打印(“其他如果”);
hop1.setVisible(true);
out1.setVisible(true);
nextHop.setVisible(真);
outGoing.setVisible(true);
}

但当我启动我的页面时,我出现了一个错误,因为行为1为空,我知道我试图通过try/catch放弃,但在之后,当我更改select的值时,它不会进入我的if条件。你知道吗?

初始化期间测试
behavior 1.getValue()
是没有意义的,因为此时它是空的(除非你显式调用
setValue

如果要在选择值时运行代码,应将此代码添加到ValueChangeListener中

像这样的方法应该会奏效:

behaviour1.addValueChangeListener(
    new ValueChangeListener() {
        @Override
        public void valueChange(Property.ValueChangeEvent event){
            Notification.show("Value changed:",    String.valueOf(behaviour1.getValue()), Notification.Type.TRAY_NOTIFICATION);
            if (behaviour1.getValue().equals("end-dx6")) {
                System.out.print("else if");
                hop1.setVisible(true);
                out1.setVisible(true);
                nextHop.setVisible(true);
                outGoing.setVisible(true);
            }
        }
    }
);
您可能应该做的其他事情:

  • 避免对文本使用字符串构造函数:
    behaviorData.add(“end-dx6”)
  • 检查空值检查值时,用户可能只删除所选文本:

    //before checking the value
    if(behaviour1.getValue()==null) {
        //nothing is selected, just return
        return;
    }
    

似乎
if
语句应该位于ValueChangeListener中。否则,if将永远不会执行,并且可能会失败。当我将if语句放入ValueChangeListenerIt时,它不起作用。很抱歉,我的错误,我忘记了一个{