2010-03-31 49 views
2

我怎樣才能讓組合框時可用的複選框取消選中了(反之亦然)激活和關閉組合框

爲什麼下拉框中仍然禁用後,我未選中的複選框?

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); 
} 

回答

4

如果我理解正確,我認爲,所有你需要做的是改變基礎上的複選框的當前值的組合框的啓用狀態:

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

謝謝,這是我需要的:-) – Jessy 2010-03-31 12:14:21

0

我TREID這一點,工作..

public class JF extends JFrame implements ActionListener { 
String choice [] = {"A","B","C"}; 
JComboBox a = new JComboBox(choice); 

JCheckBox chk = new JCheckBox("choice"); 

JF() 
{ 
    this.add(a, BorderLayout.NORTH); 
    this.add(chk, BorderLayout.CENTER); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    a.addActionListener(this); 
    chk.addActionListener(this); 
} 

public void actionPerformed(ActionEvent e) { 

    //NOTE THE FOLLOWING LINE!!!! 
    if(e.getSource()==chk) 
    a.setEnabled(chk.isSelected()); 
} 
public static void main(String[] args) { 
    new JF().setVisible(true); 
} 
} 

您的舊代碼無法正常工作,因爲即使取消選中複選框觸發事件。觸發源是複選框..所以雙方同時檢查並取消選中事件源爲chk

+0

謝謝拉吉:-) .. – Jessy 2010-03-31 12:14:39

2

我有一個類似的設置,和我使用的項偵聽器,像這樣:

CheckBox.addItemListener(new ItemListener() { 
    public void itemStateChanged(ItemEvent e) { 
     if(e.getStateChange()==ItemEvent.SELECTED){ 
      ComboBox.setEnabled(true); 
     }else if(e.getStateChange()==ItemEvent.DESELECTED){ 
      ComboBox.setSelectedIndex(-1); 
      ComboBox.setEnabled(false); 
     } 
    } 
}); 

這在選擇和取消選擇時,行爲是不同的。

0
if (e.getSource() == chckbxModificar) { 
     if (chckbxModificar.isSelected()) { 
      cbxImpuesto.setEnabled(true); 
      cbxMoneda.setEnabled(true); 
      txtPorcentaje.setEditable(true); 
      txtSimbolo.setEditable(true); 

     } else { 
      cbxImpuesto.setEnabled(false); 
      cbxMoneda.setEnabled(false); 
      txtPorcentaje.setEditable(false); 
      txtSimbolo.setEditable(false); 
     } 
    }