2013-03-27 61 views
1

我有我的項目的一個問題,因爲我的目標是讓用戶手工填寫在一個陣列項目6個領域;我想到的6個JComboBox ES具有相同的項目,當你在一個盒子裏選擇一個項目,就成了其餘殘疾。我開始了,儘管我已經搜索過,但我只找到了在其構造函數中完成它的方法。如何從偵聽器中禁用Jcombobox項目?

cb1.addActionListener(new ActionListener(){ 

@Override 
public void actionPerformed(ActionEvent e) { 
    if(cb1.getSelectedIndex()==1) { 
     // this is as far as I go, but disables the entire jcombobox 
     cb2.setEnabled(false); 

     // this is more like I want, but it doesn't work. 
     cb2.setSelectedIndex(1).setEnabled(false);        
}}}); 

如果有人知道一個更有效的方法,使可以將用戶手動分配陣列的項目到很多領域我會歡迎它。

回答

1

有沒有辦法讓你禁用JComboBox的項目。你可以只從位置刪除它這裏是如何: -

import java.awt.Container; 
import java.awt.FlowLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JComboBox; 
import javax.swing.JFrame; 
public class Combobox extends JFrame{ 
Combobox(){ 
    this.setVisible(true); 
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    String[] list={"car","bus","bike"}; 
    final JComboBox c1=new JComboBox(list); 
    final JComboBox c2=new JComboBox(list); 
    Container c=this.getContentPane(); 
    c.setLayout(new FlowLayout()); 
    c.add(c1); 
    c.add(c2); 
    c1.addActionListener(new ActionListener(){ 
     @Override 
     public void actionPerformed(ActionEvent e) { 
      int index=c1.getSelectedIndex(); 
      c2.removeItemAt(index); 
      } 
    }); 
    this.pack(); 
} 
    public static void main(String[] args) { 
     new Combobox(); 
    } 
} 

final JComboBox c1=new JComboBox(list);會讓JComboBoxlist項目。 final使用因爲C1被稱爲其用於點擊事件內部類ActionListener內部。 index=c1.getSelectedIndex();將獲得所選項目的index locationc1c2.removeItemAt(index);將刪除位於c2的index位置的物品。由於c1c2都包含相似的項目,因此index項目的位置相同。 如果你想在某個時候重新插入C2中的項目,然後 保存要刪除的項的索引位置和項目的名稱,對於使用

index=c1.getSelectedIndex(); 
item=c2.getItemAtIndex(index); 
c2.removeItemAt(index); 

然後還原的項目被刪除使用

c2.insertItemAt(item,index); 

注意 - indexitem應外聲明ActionListener如果有外面使用。

+0

如果此答案解決了您的問題,請點擊勾號標記問題解決並標記答案有用。 – 2013-03-30 19:28:38

+0

好吧,我會嘗試,謝謝 – 2013-04-30 15:19:11

+0

@EduardoSoriano如果你喜歡答案,那麼它很有用,如果它解決了你的問題標記問題, – 2013-04-30 19:59:11

0

嘗試啓用的ComboItem。函數setEnabled用於對象,在您的情況cb2。