2012-08-17 76 views
8

Tôi cần lấy giá trị nguyên của combobox trong Swing.Nhận giá trị combobox trong Java swing

Tôi đã đặt giá trị số nguyên làm id cho combobox.I đã thử combobox.getSelectedItem() và combobox.getSelectedIndex() nhưng không thể nhận giá trị int.

Dưới đây là mã của tôi:

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; 

    } 

Any help is appreciated.

+0

Vì vậy, bạn đã đặt nó như thế nào? – nullpotent

+1

Vui lòng đăng [SSCCE] (http://sscce.org/) để minh họa sự cố. – tenorsax

+1

Bản cập nhật của bạn chưa hoàn tất. Ví dụ, loại 'projectId' là gì? – trashgod

Trả lời

36

Phương thức Object JComboBox.getSelectedItem() trả về giá trị được bao bọc theo loại Object do đó bạn phải truyền theo đó.

Cú pháp:

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

Tôi chỉ nhận được giá trị chuỗi khi tôi sử dụng ở trên. (Ví dụ: tên người dùng nhìn thấy trong hộp tổ hợp). – vijay

+0

Tác phẩm này.Thanks AVD – vijay

+1

Dựa trên bản cập nhật, có vẻ như 'YourType' là' CommonBean', từ đó 'projectId' có thể được lấy. – trashgod

5

Nếu chuỗi rỗng, comboBox.getSelectedItem().toString() sẽ cung cấp cho một NullPointerException. Vì vậy, tốt hơn để typecast bởi (String).

Các vấn đề liên quan