激活和停用组合框

2022-07-23 00:00:00 checkbox combobox java swing

取消选中复选框时如何使comboBox可用(反之亦然)

为什么在取消选中复选框后组合框仍处于禁用状态?

choice [] = {"A","B","C"};
JComboBox a = new JComboBox(choice);

JCheckBox chk = new JCheckBox("choice");

...
a.addActionListener(this);
chk.addActionListener(this);
...

public void actionPerformed(ActionEvent e) {

   //disable the a comboBox when the checkBox chk was checked
  if(e.getSource()==chk)
    a.setEnabled(false);

  //enable the a comboBox when the checkBox chk was unchecked
  else if(e.getSource()!=chk)
    a.setEnabled(true);
}

解决方案

如果我理解正确的话,我认为您需要做的就是根据复选框的当前值更改组合框的启用状态:

public void actionPerformed(ActionEvent e) {
    if (e.getSource()==chk) {
        a.setEnabled(chk.isSelected());
    } 
}

相关文章