有沒有辦法讓你禁用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);
會讓JComboBox
有list
項目。 final
使用因爲C1被稱爲其用於點擊事件內部類ActionListener
內部。 index=c1.getSelectedIndex();
將獲得所選項目的index location
在c1
。 c2.removeItemAt(index);
將刪除位於c2的index
位置的物品。由於c1
和c2
都包含相似的項目,因此index
項目的位置相同。 如果你想在某個時候重新插入C2中的項目,然後 保存要刪除的項的索引位置和項目的名稱,對於使用
index=c1.getSelectedIndex();
item=c2.getItemAtIndex(index);
c2.removeItemAt(index);
然後還原的項目被刪除使用
c2.insertItemAt(item,index);
注意 - index
和item
應外聲明ActionListener
如果有外面使用。
如果此答案解決了您的問題,請點擊勾號標記問題解決並標記答案有用。 – 2013-03-30 19:28:38
好吧,我會嘗試,謝謝 – 2013-04-30 15:19:11
@EduardoSoriano如果你喜歡答案,那麼它很有用,如果它解決了你的問題標記問題, – 2013-04-30 19:59:11