JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

How To Use The JList Function In Java Beginner’s Tutorial

August 21, 2018 by Krishna Srinivasan Leave a Comment

Let's say you're creating an address form on a webpage which asks for the state a user lives in. Do you really want to list all 50 states on the form for someone to choose from? After all, that information will take up too much valuable space on the page and create unnecessary clutter.

What should you do?

The simplest solution is to use Java's JList function to create a pop-up menu with a list of states for a user to choose from. The selection is made, the options box disappears, and life moves on.

Then again, to do this, you'll need to understand the ins and outs of using JList. To give you a hand, we'll go over the basics of what you'll need to know below.

Quick Navigation
What is JList?
JList Constructors & Methods
JList Constructors
JList Methods
Using JList
1. Building a List Model
2. Initializing a List
3. Rendering List Cells
4. Selecting List Items
5. Adding & Removing List Items
Additional JList Features
Split Panes
Box Layout
List Data Listener
Custom Models
Sample JList
Additional JList Resources

What is JList?

JList is a tool in Java which allows you to build a graphical user interface (GUI) to display a list of items and allow a user to select one or more of these items. It's a Swing component, part of a larger toolkit to build application programming interfaces (APIs). A separate component, ListModel, contains the data for the list being displayed.

JList

The "J" at the beginning of JList indicates it's a descendant of the JComponent class as are all the tools which utilize Swing architecture. This includes the following features:

  • Tool tips: Text boxes which pop up when a cursor hovers over a page element.
  • Accessibility:  Accessibility interface methods are included.
  • Painting infrastructure: Support for borders and double buffering of visual elements.
  • Component-specific properties: Any JComponent descendant object can be associated with name-object pairs.
  • Pluggable look and feel (L&F): Interface design can be determined by the programmer or, if desired, chosen by the user when initiated.
  • Keystroke handling: Define keyboard events to initiate actions automatically.

JList Constructors & Methods

The API for using JList constructors and methods breaks out into four areas:

  • Initializing list data
  • Managing list data
  • Displaying the list
  • Managing list selection

JList Constructors

These are the most common JList constructors:

  • JList(): Creates a read-only, empty model.
  • JList(E[] listData): Displays the elements in a specified array.
  • JList(ListModel<E> dataModel): Displays the elements from a specified, non-null model.
  • JList(Vector<? extends E> listData): Displays the elements from a specified Vector.

JList Methods

Common methods used with JList constructors include:

  • getModel(): Returns the data model holding list items to be displayed.
  • getSelectedIndex(): Returns the smallest selected cell index.
  • setListData(E[] listData): Builds a read-only ListModel.
  • setListData(Vector<? extends E> listData): Builds a read-only ListModel from a Vector.
  • addListSelectionListener(ListSelectionListener listener): Each time a selection is changed, the specified listener is notified.

Using JList

Depending on the relative size, complexity, and visual properties of the list you want to display, JList's options are both varied and robust. There are, however, five basic steps you'll need to work through each time you use the JList function:

  • Building a list model
  • Initializing a list
  • Rendering list cells
  • Selecting list items
  • Adding and removing list items

1. Building a List Model

Before you can build the JList GUI, you need to create a model for your list's data. There are three options to do this:

  • 1
    ListModel: You manage all elements of the list.
  • 2
    AbstractListModel: You manage the list data.
  • 3
    DefaultListModel: Most list elements managed by default parameters.

2. Initializing a List

Once you've chosen your model, you'll need to use code from ListDialog.java to initialize the list and populate its array with items from a previously defined object. Or, as per the constructors listed above, you can create a list from an object or Vector as per the ListModel component.

This is also when you can determine display characteristics such as adding a scroll pane or how the text will be displayed: vertical, vertical with text wrapping, or horizontal with text wrapping.

3. Rendering List Cells

List items are displayed by using a cell renderer object to format icons and strings by via toString. If you want to customize this display, you'll need to utilize the ListCellRenderer interface. This will create a "stamp" to paint components within a JList cell such as the foreground or background colors.

4. Selecting List Items

The ListSelectionModel component manages the list selection options. By default, this includes the ability to choose any number of items as per the three following modes:

  • SINGLE_SELECTION: Only one item can be selected. If a second item is selected, the previous item is deselected.
  • SINGLE_INTERVAL_SELECTION: Multiple items in a contiguous range can be selected. If a new range is selected, the previous items are deselected.
  • MULTIPLE_INTERVAL_SELECTION: This is the default mode which allows any combination or number of items to be chosen.
JList Methods

5. Adding & Removing List Items

Lists can be either mutable (changeable) or immutable (unchanging). In the case of listing all 50 US states, you'd likely want that list to be immutable. On the other hand, you'll need to set up a mutable list if you're going to be adding or removing items from it such as, for example, different products or payment options over time.

There are two basic ways to do this:

  • insertElementAt: Insert the new item after the current selection or at the beginning of the list if there is no existing selection.
  • DefaultListModel addElement: Insert the new item at the end of the list.

Additional JList Features

Of course, depending on the complexity of the list you want users to access, there are a variety of additional features which can be incorporated once you master the basics:

  • Split panes
  • Box layout
  • List data listener
  • Custom models

Split Panes

JSplitPane allows you to display two separate components either one on top of the other or side by side. For example, in a side-by-side display, you could list product names in the left pane, and when a selection is made by the user, a picture of the product appears in the right-hand pane.

To try this out, open Java Web Start (JDK 7 or later), and select the Launch button for the SplitPaneDemo. Or, you can use this example provided by Oracle to compile and run your own split-pane list.

Box Layout

JList's BoxLayout allows you to put all selections in a single box either in rows or stacked on top of each other. This is similar to FlowLayout but offers more powerful options such as moving and rearranging elements within the box in relationship to each other.

Be aware: Even Oracle admits coding box layouts by hand can be tricky and suggests you consider using the GroupLayout manager with a builder tool such as NetBeans IDE.

List Data Listener

When the contents of a list change, that's a data event. By default, list models are immutable, so to use a data listener – or even have a need for one – you'll need to make sure you've created a mutable list. An example of an action requiring a list data listener would be offering users the ability to add items to an online wish list.

Custom Models

By default, almost all Swing components work from models. For example, an onscreen button uses a model file to store its image, what keyboard action it's associated with, and other properties. Plus, components can use multiple models. For example, a list uses one model to track the existing selection a user has made while another one is used for list data.

So, if you wanted to allow users to enter data which is then further manipulated for them, you'd need to create a custom model. For example, perhaps you have a temperature converter. Users could enter degrees in Fahrenheit and the model you've created would convert that into a Celsius measurement. Or, you could allow users to convert pounds to kilograms, miles to kilometers, and so on.

codes

Sample JList

Now that we've covered some of the theory, here's the code for a basic JList GUI which displays a list of four car manufacturers:

import javax.swing.*;

public class ListDemo

{

     ListDemo(){

          JFrame f= new JFrame();

          DefaultListModel<String> l1 = new DefaultListModel<>();

          l1.addElement("Audi");

          l1.addElement("Chevrolet");

          l1.addElement("Ford");

          l1.addElement("Mercedes");

          JList<String> list = new JList<>(l1);

          list.setBounds(150,150, 100,100);

          f.add(list);

          f.setSize(500,500);

          f.setLayout(null);

          f.setVisible(true);

     }

     public static void main(String args[])

     {

          new ListDemo();

     }

}

Remember, as you add more bells and whistles to your list's GUI, the code will be longer and more complex.

Additional JList Resources

Thanks to Java being open source, there are many resources available for programmers beginning with Oracle's complete Java Platform, Standard Edition 8 API Specification documentation. All that information makes for some dense reading, however, so for JList tips, in particular, you might also take a look at the tutorials at these websites:

  • C​​​​​odeJava
  • GeeksforGeeks
  • Tutorials Point

When you're programming with Java, you want to make sure you're using all its features to maximum effect. Once you're familiar with JList's constructors and methods, you will be well on your way to creating dynamic lists with a variety of functions for users.

Filed Under: Java

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved