所以在Java上,"AND"语句是&&,"OR"语句是|| ...
那么XOR呢......那就是我有两个选择.我必须选一个,但我不能同时选择.
然而,
private class CheckBoxListener implements ItemListener{
public void itemStateChanged(ItemEvent e)
{
if(one.isSelected()^two.isSelected()){
thehandler handler = new thehandler();
button.addActionListener(handler);
}
}}
Run Code Online (Sandbox Code Playgroud)
即使我同时选中了两个复选框,该按钮也会"启用".这是按钮fyi的处理程序:
private class thehandler implements ActionListener{
public void actionPerformed(ActionEvent event){
dispose();
}
Run Code Online (Sandbox Code Playgroud)
因此,如果两者都被选中,并且如果我单击按钮.框架不应该丢弃.它应该只在选择其中任何一个时处理.
^ 是Java中的XOR运算符.
关于你的Swing问题,问题是你没有在单击按钮时检查复选框的状态,而是在选中复选框时.你应该改为:
private class ButtonActionListener implements ActionListener {
/*
* You will probably define a constructor that accepts the two checkboxes
* as arguments.
*/
@Override
public void actionPerformed(ActionEvent event) {
if (one.isSelected() ^ two.isSelected()) {
dispose();
}
}
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是创建一个实例ActionListener.addActionListener当选中其中一个复选框时,您可以添加它,并使用removeActionListener其他方式将其删除:
private class CheckBoxListener implements ItemListener {
private ActionListener buttonActionListener = new thehandler();
@Override
public void itemStateChanged(ItemEvent event) {
if(one.isSelected() ^ two.isSelected()) {
button.addActionListener(buttonActionListener);
} else {
button.removeActionListener(buttonActionListener);
}
}
}
Run Code Online (Sandbox Code Playgroud)