2012-08-17 7 views
8

Ho bisogno di ottenere il valore intero della casella combinata in Swing.Ottieni valore combobox in swing Java

Ho impostato un valore intero come id per la casella combinata.Ho provato combobox.getSelectedItem() e combobox.getSelectedIndex() ma non è possibile ottenere il valore int.

Qui di seguito è il mio codice:

CommonBean commonBean[]=new CommonBean[commonResponse.getCommonBean().length+1];   
     for(int i=0;i<commonResponse.getCommonBean().length;i++) 
     { 
      commonBean[i] = new CommonBean("--Please select a project--", 0); 
      commonBean[i+1] = new CommonBean(commonResponse.getCommonBean()[i].getProjectName(), commonResponse.getCommonBean()[i].getProjectId()); 
     } 

JComboBox combobox= new JComboBox(commonBean); 


public CommonBean(String projectName,int projectId) {  
     this.projectName = projectName; 
     this.projectId = projectId; 

    } 

Ogni aiuto è apprezzato.

+0

Quindi, come l'hai impostato? – nullpotent

+1

Si prega di inviare [SSCCE] (http://sscce.org/) che dimostra il problema. – tenorsax

+1

L'aggiornamento è incompleto. Qual è il tipo di 'projectId', ad esempio? – trashgod

risposta

36

Il metodo Object JComboBox.getSelectedItem() restituisce un valore che è stato compresso dal tipo Object quindi è necessario eseguirlo di conseguenza.

Sintassi:

YourType varName = (YourType)comboBox.getSelectedItem();` 
String value = comboBox.getSelectedItem().toString(); 
+0

Ricevo solo un valore di stringa quando utilizzo quanto sopra (ovvero il nome che l'utente vede nella casella combinata). – vijay

+0

Funziona.Grazie AVD – vijay

+1

In base all'aggiornamento, sembra che 'YourType' sia' CommonBean', da cui 'projectId' può essere ottenuto. – trashgod

5

Se la stringa è vuota, comboBox.getSelectedItem().toString() darà un NullPointerException. Quindi, meglio digitare typecast da (String).