2012-11-28 110 views
0

可能重複:
Dynamic JComboBoxes多個鏈接的下拉框

我在java程序一個新手。 我有關於組合框程序的問題。 我有3個組合框(cbxType,cbxItem和cbxColor)。我希望第二個組合框(cbxItem)中的項目列表根據第一個(類型)進行更改,然後根據第二個(cbxItem)中的選定項目更改第三個組合框(cbxColor)項目列表。 我一直試圖通過我自己的代碼解決這個問題,第二個組合框在第一個組合框更改時工作正常,但第三個組合框在我更改後不會顯示任何項目。 這是我的代碼。 感謝您的幫助球員,併爲我的英語不好對不起..

private void viewCbxType(){ 
    String sql; 


try { 
    sql ="Select distinct productItem from Product "; 
    if(cbxType.getSelectedItem() != "<<Product Type>>"){ 

     String prType = cbxType.getSelectedItem().toString(); 

     sql ="Select distinct productItem from Product WHERE productType='" +prType+"'"; 



      cbxItem.removeAllItem(); 
      cbxItem.setSelectedIndex(0); 
     } 
    } 


    PreparedStatement st = conn.prepareStatement(sql); 
    ResultSet rs =st.executeQuery(); 



    while (rs.next()) { 
     String prItem = rs.getString("productItem"); 

     cbxItem.addItem(prItem); 

    } 
}catch (SQLException se) {} 
} 

我致電的actionPerformed該方法對我的第一個組合框,使類同第二

+2

這已被要求,並回答了很多次這個網站,包括這個線程:[動態JComboBoxes](http://stackoverflow.com/questions/3191837/dynamic-jcomboboxes),和這個線程:[改變jcombobox的元素...](http://stackoverflow.com/問題/ 5336711 /改變元素-的-根據對所述選擇從 - 另一個-jcombob一個-的JComboBox-)。投票結束這個問題的重複。 –

回答

0

您可以組合實現了一個動作監聽器箱:

public class ComboBoxDemo ... implements ActionListener { 
    . . . 
     petList.addActionListener(this) { 
    . . . 
    public void actionPerformed(ActionEvent e) { 
     JComboBox cb = (JComboBox)e.getSource(); 
     String petName = (String)cb.getSelectedItem(); 
     updateLabel(petName); 
    } 
    . . . 
} 

這個動作監聽器從組合框中獲取新選擇的項目,用它來計算圖像文件的名稱,並更新標籤來顯示圖像。當用戶從組合框的菜單中選擇一個項目時,組合框會觸發一個動作事件。看到如何編寫一個動作偵聽器,適用於一般的信息有關實施行動聽衆:

http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

這可以幫助你太

http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html