簡體   English   中英

在 Java swing 中獲取組合框值

[英]Get combobox value in Java swing

我需要在 Swing 中獲取組合框的整數值。

我已經設置了一個整數值作為組合框的 id。我嘗試了 combobox.getSelectedItem() 和 combobox.getSelectedIndex() 但它無法獲得 int 值。

下面是我的代碼:

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;

    }

任何幫助表示贊賞。

方法Object JComboBox.getSelectedItem()返回一個由Object類型包裝的值,因此您必須相應地對其進行轉換。

句法:

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

如果字符串為空,則comboBox.getSelectedItem().toString()將給出NullPointerException 所以最好通過(String)進行類型轉換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM