What are the differences between a JComboBox and a JList in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

A JComboBox is a component that displays a drop-down list and gives users options that we can select one and only one item at a time whereas a JList shows multiple items (rows) to the user and also gives an option to let the user select multiple items.

JComboBox

  • A JComboBox can be editable or read-only.
  • An ActionListener, ChangeListener or ItemListener interfaces can be used to handle the user actions on a JComboBox.
  • A getSelectedItem() method can be used to get the selected or entered item from a combo box.
  • A setEditable() method can be used to turn on or turn off the text input part of a combo box.
  • We can create a JComboBox instance from an array or vector. Most of the time, we will use ComboBoxModel to manipulate ComboBox’s elements.

Example

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();
   }
}

Output

JList

  • A JList is a component that allows the user to choose either a single selection or multiple selections.
  • A JList class itself does not support scrollbar. In order to add scrollbar, we have to use JScrollPane class together with the JList class. The JScrollPane then manages a scrollbar automatically.
  • A getSelectedIndex() method returns the index of the first selected item or –1 if no items are selected and getSelectedIndexes() method returns an array with the index of each selected item. The array is empty if no items are selected.
  • A getSelectedValue() returns the first selected item or null if no items are selected.
  • A DefaultListModel class provides a simple implementation of a list model, which can be used to manage items displayed by a JList control.

Example

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();
   }
}

Output

raja
Published on 08-Jul-2019 11:48:58
Advertisements