2011-02-01 53 views
0

我試圖尋找用戶名和返回值到JComboBox中,這裏是代碼我的JComboBox沒有反應到我的KeyListener和actionPerform執行weired東西

public void actionPerformed(java.awt.event.ActionEvent e) { 
    sr = new Search(((String) jComboBoxReceiver.getSelectedItem()));  
    usrList = sr.searchUser(); 
    String[] userList = new String[usrList.size()] ; 
    for(int i=0;i<usrList.size();i++){ 
     userList[i]= usrList.get(i).getUserName(); 
    } 
    model = new DefaultComboBoxModel(userList); 
    jComboBoxReceiver.setModel(model); 
} 

你點擊到別的地方或點擊進入後,它會進行搜索,但是,它會再次搜索的第一個項目,這是非常混亂...然後我試着用壓

if(e.getKeyCode()==13){ 
    sr = new Search(((String) jComboBoxReceiver.getSelectedItem()));  
    usrList = sr.searchUser(); 
    String[] userList = new String[usrList.size()] ; 
    for(int i=0;i<usrList.size();i++){ 
     userList[i]= usrList.get(i).getUserName(); 
    } 
    model = new DefaultComboBoxModel(userList); 
    jComboBoxReceiver.setModel(model); 
} 

鍵,這個完全不反應。

回答

1

無論如何,如果你真的想這樣做,那麼你應該後刪除動作偵聽器(或停用)改變其內容之前,並重新添加它(或重新激活)哇,你每次都重建一個ComboBoxModel?這不是有點貴嗎?你知道有一個MutableComboBoxModel,也實現了DefaultComboBoxModel,這將允許你添加/刪除組合元素,而無需每次重建其模型?

關於你的問題,我不明白的聲明

但是,如果我這樣做,它不正確地執行,但是,它將再次去搜索的第一個項目

你的意思是你的JComboBox開始閃爍,每次修改內容?

如果是這樣,也許是因爲你的ActionListener鏈接到JComboBox,其內容不斷變化。

無論如何,我建議你添加一些日誌,像

sr = new Search(((String) jComboBoxReceiver.getSelectedItem()));  
DefaultComboBoxModel model = (DefaultComboBoxModel) jComboBoxReceiver.getModel(); 
model.remvoeAllElements(); 
usrList = sr.searchUser(); 
String[] userList = new String[usrList.size()] ; 
for(int i=0;i<usrList.size();i++){ 
    String username = usrList.get(i).getUserName(); 
    System.out.println(username); // feel free to instead use one loger 
    model.addElement(username); 
} 

此外,我往往會建議你的另一種方法,在組合框模型不包含簡單的字符串,而是用戶對象, ListCellRenderer只顯示用戶名。

+0

非常感謝......問題是,我們的教師只教我們基本概念,ListcellRenderer和MutableModelEvent是有點太複雜了...哈哈 – 2011-02-01 16:18:13

1

IMO會讓你的用戶感到困惑的是,只要他們選擇了其中一個選項,就會改變組合框的內容和選擇。

public void actionPerformed(java.awt.event.ActionEvent e) { 
    sr = new Search(((String) jComboBoxReceiver.getSelectedItem()));  
    usrList = sr.searchUser(); 
    String[] userList = new String[usrList.size()] ; 
    for(int i=0;i<usrList.size();i++){ 
     userList[i]= usrList.get(i).getUserName(); 
    } 
    model = new DefaultComboBoxModel(userList); 
    jComboBoxReceiver.removeActionListener(this); 
    jComboBoxReceiver.setModel(model); 
    jComboBoxReceiver.addActionListener(this); 
} 
相關問題