简体   繁体   English

如何检查JComboBox是否为空?

[英]How to check if JComboBox is empty?

I am not able to check whether the JComboBox is empty. 我无法检查JComboBox是否为空。 The below code is not working. 以下代码无效。

if (t_m_priority.getSelectedItem() != null &&
t_m_priority.getSelectedItem().equals("SELECT")){
        msg = "Triage Time Is Not Entered";
        saveflag = false;
    }

JComboBox#getSelectedItem will return null when no items are selected 当没有选择任何项时, JComboBox#getSelectedItem将返回null

You could use something like... 你可以用...

if (t_m_priority.getSelectedItem() != null &&
    t_m_priority.getSelectedItem().equals("SELECT")) {

To first check to see if the anything is selected and then test to see what the selected item actually is... 首先检查是否选择了任何内容,然后测试以查看所选项目实际是什么...

JComboBox.getItemCount() JComboBox.getItemCount()

If this method returns 0, the component is empty. 如果此方法返回0,则组件为空。

if (t_m_priority.getItemCount() == 0) {
   msg = "Triage Time Is Not Entered";
   saveflag = false; 
}

UPDATE: Try this to check if no item is selected in the combo box. 更新:尝试此操作以检查组合框中是否未选择任何项目。

if(t_m_priority.getSelectedItem() == null ) {
     msg = "Triage Time Is Not Entered";
     saveflag = false;  
}

Instead of adding the dummy item "Select" to the combo box, use a custom renderer to display "Select" when no item is actually selected. 而不是将虚拟项“选择”添加到组合框,而是在没有实际选择项目时使用自定义渲染器显示“选择”。 Then you can just check if the selected index of the combo box is not -1. 然后你可以检查组合框的选定索引是否不是-1。

Check out Combo Box Prompt for a renderer that implements this functionality for you. 查看为您实现此功能的渲染器的组合框提示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM