2016-03-25 24 views
0

我試過這個,但失敗了。如果我從屬性手動設置組合框,我可以將所選項目設置爲該項目。Java如何從數據庫SetSelectedItem ComboBox?

cbSetNoInvoice.setSelectedItem(txtSearchAll.getText()); 

而這一次是負載listComboBox

for (Transaction tr : listTransaction) { 
cbSetNoInvoice.addItem(tr.getNo_invoice()); 

Here is the screenshot. I want to set the selected item on the "Invoice" combobox if user input on the textfield and click the button

+0

是否要將comboBox中的值綁定到數據庫中的值?我不清楚你想在這裏實現什麼 –

+0

它就像列表中的臨時表,所以如果jTextField上的值與我保存後列表中的值相同,則可以removeItem。 所以它不會出現兩次,如果我已經選擇了... 這就是我想要的 –

回答

0

像這樣的事情? (我還沒有測試過)

btnSearch.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     String text = txtSearch.getText(); 
     int index = cbInvoice.getModel().getIndexOf(text); 
     if (index == -1) { 
      // the text is not already in the combobox 
      cbInvoice.insertItemAt(text, 0); 
      cbInvoice.setSelectedIndex(0); 
     } else { 
      // the text is already there 
      cbInvoice.setSelectedIndex(0); 
     } 
    } 
}; 
+0

是的,有點,但是雖然搜索它不會插入哪些不是已經在組合框...,但我可以' t執行cbInvoice.setSelected可能導致項目在第一次添加時不是字符串? –