JComboBox hiển thị drop-down list cho user chọn một và chỉ một item tại một thời điểm, trong khi JList hiển thị nhiều item (hàng) và cho phép chọn nhiều item.
JComboBox
- Có thể editable hoặc read-only.
- Xử lý user action bằng ActionListener, ChangeListener hoặc ItemListener.
- Phương thức getSelectedItem() lấy item được chọn hoặc nhập.
- Phương thức setEditable() bật/tắt phần nhập text.
- Tạo instance từ array/vector, thường dùng ComboBoxModel thao tác element.
Ví dụ
import java.awt.*;
import javax.swing.*;
public class JComboBoxTest extends JFrame {
JComboBoxTest() {
setTitle("JComboBox Test");
String country[] = {"India", "Aus", "Singapore", "England", "Newzealand"};
JComboBox jcb = new JComboBox(country);
setLayout(new FlowLayout());
add(jcb);
setSize(300, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new JComboBoxTest();
}
}
Kết quả

JList
- JList cho phép chọn đơn lẻ hoặc nhiều lựa chọn.
- JList không hỗ trợ scrollbar. Để thêm scrollbar, dùng JScrollPane cùng JList. JScrollPane quản lý scrollbar tự động.
- getSelectedIndex() trả về index item chọn đầu tiên hoặc -1 nếu không chọn. getSelectedIndexes() trả về mảng index các item chọn. Mảng rỗng nếu không chọn.
- getSelectedValue() trả về item chọn đầu tiên hoặc null.
- DefaultListModel cung cấp implement đơn giản list model quản lý item hiển thị bởi JList.
Ví dụ
import java.awt.*;
import javax.swing.*;
public class JListTest extends JFrame {
JListTest() {
setTitle("JList Test");
DefaultListModel dlm = new DefaultListModel();
dlm.addElement("India");
dlm.addElement("Aus");
dlm.addElement("England");
dlm.addElement("Singapore");
JList list = new JList();
list.setModel(dlm);
setLayout(new FlowLayout());
add(list);
setSize(350, 275);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String args[]) {
new JListTest();
}
}
Kết quả
