[英]How to disable a Jcombobox item from a listener?
我的項目有問題,因為我的目標是讓用戶用數組中的項目手動填充6個字段; 我想到了6個JComboBox
es具有相同的項目,當您在一個框中選擇一個項目時,其余項目將被禁用。 我開始了,盡管我已經搜索過,但我只發現了在其構造函數中執行此操作的方法。
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);
}}});
如果有人知道一種更有效的方法,使用戶可以手動將數組項分配給許多字段,我將歡迎您。
您無法禁用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
項目。 因為在內部類ActionListener
內調用了c1,所以使用了final
事件,該類用於單擊事件。 index=c1.getSelectedIndex();
將獲得c1
所選項目的index location
。 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
則應在ActionListener
之外聲明。
嘗試啟用ComboItem。 函數setEnabled用於對象,具體情況為cb2。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.