English Subtitles for Java Swing Tutorial A - Z : Part 7 : JComboBox and JList (English Subtitle)



Subtitles / Closed Captions - English

Create a new empty java application project

Create a new JFrame named ProductList Design GUI with JComboBox, JList, edit text and change variable name for all objects Modify model property of JComboxBox to clear all default items Modify model property of JList to clear all default items Create action event for Add button Use addItem(Object item) method of JComboBox to add item

Run the project and add some item to JComboBox But no method for JList to add directly an item into it So we must create an object of DefaultListModel class to contain its data And use addElement(Object element) method of model object to add an item for JList Use setModel(Model model) method of JList object to import all data into JList Run the project and add some item to both JComboBox and JList simultaneously

Now create action event for Delete button Use removeItemAt(int index) method of JComboBox object to remove an item at some index Use getSelectedIndex method of JComboBox object to get the index when end-user choose any item But JList doesn't have remove method to remove an item like JComboBox So we must use removeElementAt(int index) method of model object instead to remove an item at some index of JList And use getSelectedIndex method of JList object the same as JComboBox to get the index when end-user choose any item

Run the project, add some items, and then remove some But when no choice in JList, and click Delete button, it throws an exception And when the JComboBox is empty, we can't remove any more item remaining and it throws more exception So now we must modify, use if to check condition when JComboBox and JList model are empty or not If not empty, perform deleting selected item in both JComboBox and JList model Otherwise, a message appears that "product list should not be empty"

Run the project and now, when the list or combobox is empty, a message appear But when no choice in JList, it still throws an exception So use try-catch block to catch exception and handle it When exception occurs, the message "You must choose an item to delete!" will appear instead Run the project and add some items, delete any, and everything is OK now!



Video Description

Click CC to view Caption (Subtitle) for this video clip!
This clip tutors how to:
- use JComboBox and JList
- add and remove items to and from them