Java
Swing - GUIs LESSON NOTE - JCOMBOBOX JCOMBOBOX CONSTRUCTOR We
create a JComboBox by specifying a String array
that contains the data that will be inside the JComboBox. String[] data = {"apple",
"orange", "banana", "pear"}; JComboBox cb = new JComboBox(data); After
adding the JComboBox to the content pane, we get
this: SELECTED? To know which text is
selected, we use the getSelectedText() method. String
s = cb.getSelectedItem(); To know the index of the
text that is selected, we use the getSelectedIndex() method. int index = cb.getSelectedIndex(); ACTION LISTENER We can add an action
listener to the JComboBox. After we do
so, an event is triggered whenever the down arrow is clicked on and then one
of the choices are picked. ACTIONPERFORMED METHOD To
respond to an event, we check the source of the event. If the event comes from the JComboBox, then we get the selected text or index. public
void actionPerformed(ActionEvent
e) { if (e.getSource()
== cb) { System.out.println(cb.getSelectedItem()); } } FULL CODE EXAMPLE Here
is a complete example that shows the concepts from above in action.
|
|
|