2013-10-24 227 views
1

我有5个复选框,分别是星期一,星期二,星期四,星期四,星期五。 我试图从这些复选框中选择任何一个时获取Value。 但是我意识到,当他们都没有被选中时,没有被选中的那些打印时就会有空值。我怎么才能打印只有选中一个没有null值之间的值。这是当我做System.out.print();假设我选择星期二和星期四独自我得到的响应像null tuesday null thursday null从复选框中获取值

以下是我所做的。

这是代码

private void jButton2MouseClicked(java.awt.event.MouseEvent evt) 
{ 
    System.out.print(mon+ " " +tue+" "+wed +" "+thus+" " +fri); 
    JOptionPane.showMessageDialog(null, mon+ " " +tue+" "+wed +" "+thus+" " +fri); 

}          

private void mondayBoxItemStateChanged(java.awt.event.ItemEvent evt) { 
    if(mondayBox.isSelected()) 
    { 
     mon = mondayBox.getText(); 

    } 
    else 
    { 
    mon = " "; 
    } 
}           

private void tuesdayBoxItemStateChanged(java.awt.event.ItemEvent evt) 
{ 
    if(tuesdayBox.isSelected()) 
    { 
     tue = tuesdayBox.getText(); 
    } 
    else 
    { 
     tue = ""; 
    }// TODO add your handling code here: 
}           

private void wedBoxItemStateChanged(java.awt.event.ItemEvent evt) { 
    if(wedBox.isSelected()) 
    { 
     wed = wedBox.getText(); 
    }else 
    { 
     wed = ""; 
    }  // TODO add your handling code here: 
}          

private void thurBoxItemStateChanged(java.awt.event.ItemEvent evt) { 
    if(thurBox.isSelected()) 
    { 
     thus = thurBox.getText(); 
    }else 
    { 
     thus = ""; 
    }   // TODO add your handling code here: 
}           

private void friBoxItemStateChanged(java.awt.event.ItemEvent evt) { 
if(friBox.isSelected()) 
    { 
     fri = friBox.getText(); 
    }else 
    { 
     fri = ""; 
    }   
}       
+0

为什么不将所有ItemListeners组合到一个ItemListener? – Vallentin

+1

检查值是否为空然后打印它们 –

回答

0

它返回null,因为所有这些变量“星期一”,“星期二”,“结婚”等。将被设置为仅空如果该复选框改变它的状态。

试试这个:

btnSelected.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
       JOptionPane.showMessageDialog(null, getSelected()); 
      } 
     }); 

public String getSelected() { 
    String days = ""; 
    for (Component c : getComponents()) { 
     if (c instanceof JCheckBox) 
      if (((JCheckBox) c).isSelected()) 
       days += ((JCheckBox) c).getText() + ","; 
    } 
    return days; 
} 

我们在这里所做的是验证当前面板的所有组件,该组件是一个复选框,并选择,然后我们加入它的文本字符串“天” 。

+0

非常感谢您的帮助Gabriel,我完全按照您的建议进行了操作,但似乎出现了错误。当我尝试打印出没有显示的值时。我不知道如果变量“天”没有得到的价值。 –

+0

@AgwuChile,也许你的复选框属于另一个JPanel。看到你添加复选框的面板,就像'myPanel.add(复选框)'。现在你可以编辑上面的代码,看看for(Component c:getComponents())'for change for(for Component c:myPanel.getComponents())',看它是否有效。 –

+0

非常感谢你Gabriel。它的作品现在很好。非常感激。 –

0

该解决方案实际上很简单。在您的类上下文中声明tue, wed, mon等初始化为空字符串""。所有的null都将消失。例如:

class MyPanel extends JPanel 
{ 
    String tue = ""; 
    String wed = ""; 
    ......... 
    JCheckBox tuesDayBox; 

}