Monday, November 10, 2014

JComboBox – Display and Value from Item

Do quá trình làm đồ án Java có nhiều bạn gặp khó khăn trong việc load dữ liệu vào JComboBox. Trong bài này tôi hướng dẫn một đoạn code nhỏ để các bạn tham khảo.

image

Bước 1: Định nghĩa nội dung cho một phần tử trong ds của JComboBox

1 class Item {
2 public Item(int id, String name, int price) {
3 this.id = id;
4 this.name = name;
5 this.price = price;
6 }
7
8 private int id;
9 private String name;
10 private int price;
11
12 public int getId() {
13 return id;
14 }
15
16 public void setId(int id) {
17 this.id = id;
18 }
19
20 public String getName() {
21 return name;
22 }
23
24 public void setName(String name) {
25 this.name = name;
26 }
27
28 @Override
29 public String toString() {
30 return getName() + "\t" + getPrice();
31 }
32
33 public int getPrice() {
34 return price;
35 }
36
37 public void setPrice(int price) {
38 this.price = price;
39 }
40 }
Bước 2: Gán dữ liệu vào danh sách và đưa lên JComboBox


1 private void load()
2 {
3 DefaultComboBoxModel model = new DefaultComboBoxModel();
4 model.addElement(new Item(1,"Mit",8000));
5 model.addElement(new Item(2,"Cam", 15000));
6 model.addElement(new Item(2,"Xoai", 20000));
7 jComboBox1.setModel(model);
8 }

Bước 3: Nhận giá trị (khóa, ID) của từ JComboBox khi chọn một phần từ từ giao diện


- Đăng ký sự kiện chọn phần tử từ ds





1 private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
2 this.setTitle( ((Item)jComboBox1.getSelectedItem()).getId()+"");
3 }


Tới đây chạy lại from để quan sát kết quả.


 


Mã nguồn tham khảo ở đây


http://1drv.ms/10JvXRm


Video tham khảo


http://youtu.be/wvJ155iuni0?list=UUQ8F8U5jZwjS4MZ5JYX5W2A

No comments:

Post a Comment

Translate