JList in Java | Methods and Constructors of JList In Java

JList in JavaJList in Java

Introduction to JList in Java

JList in java is a swing component that displays a list of objects and allows the user to select one or more items. JList is like ListViews in other programming languages where it allows us to represent a list of items.

Definition of Application Program Interface (API)

JList is defined in the java. swing package.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

JList is generic. Moreover, it inherits from java.swing.JComponent, which is an abstract class that is the base class for all Swing components except top-level containers.

  • public class JList<E>
  • extends JComponent
  • implements Scrollable, Accessible

Moreover, as you can see JList implements javax.swing.Scrollable, an interface that provides a scrolling container like JScrollPane, and java.swing.Accessible, which is the main interface for the accessibility package.

Constructors of JList

Given below are the constructors explained.

  1.  JList( ): This Constructor in the JList class will create a List with a read-only, empty, model.
  2. JList( Array[ ] list data ): This Constructor in the JList class will create a list that will display the elements from the array specified within the parameter.
  3. JList( ListModel<Array> data model ): This Constructor in the JList class will create a list that will display the elements from the specified, no-null, model.
  4. JList( Vector <?> list data ): This Constructor in the JList class will create a list that will display the elements from the vector specified within the parameter.

Commonly Used Methods of JList

Following are commonly used methods.

  1. Void addListSelectionListener( ListSelectionListener listener ): This Method is used to add a listener to the list, which can be used to be notified whenever there is any change to the selection in the list being made.
  2. Int gets selectedIndex( ): This method is used to return the index of the selected item of the list.
  3. Int get selected value( ): This method is used to return the value of the element selected in the list.
  4. ListModel getModel( ): This method is used to return the data model that holds the items of the list in the JList Component.
  5. Void setListData( Object [ ] list data ): This method is used to create a read-only model from the given array of objects in the parameter.

Example of Simple JList in Action

In the below example we will use a JList to control the color of the panel. Firstly we will make JList and fill in the with the different colors, set the list a JScrollPane in order to see all the colors of the list and add an action event listener on the list based on which we set the color of the background panel.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JListExample extends JFrame{
private JList list;
private static String[] colorNames = {"blue","green","yellow","orange","red","black","grey","white"};
private static Color[] colors = {Color.BLUE,Color.GREEN,Color.YELLOW,Color.ORANGE,Color.RED,Color.BLACK,Color.GRAY,Color.WHITE};
public JListExample() {
super("JList Demo Example");
setLayout(new FlowLayout());
list = new JList(colorNames);
list.setVisibleRowCount(5);//number of elements to visible as row in list
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//choose the selection mode in list
add(new JScrollPane(list));
//adding event listener on JList
list.addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
getContentPane().setBackground(colors[list.getSelectedIndex()]);}
});
}public static void main(String[] args)
 {JListExample jl = new JListExample();
jl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jl.setSize(300, 300);
jl.setVisible(true);
}}

Output:

JList in Java-1JList in Java-1

Adding data to JList

 We don’t append data directly to JLists. Instead, we use a separate model. That model will maintain the contents of the list. However, if you want to render items from an array or vector, then we will just pass the array in our JList constructor then the JList will automatically build ListModel for us. However, the majority of the time you want to use ListModel if you have data coming from collections. Moreover, ListModel defines several methods that we can also use to manipulate our data.

We can initiate the ListModel in the following way:

DefaultListModel df = new DefaultListModel();
  • DefaultListModel is defined in javax.swing package.

Example to use DefaultListModel

Here in the below example, we will create a JFrame being split into two halves horizontally. The left will contain the list of some items and the right half will show the respective price of the items in the adjacent list. For doing so firstly we will create a JFrame, a JList and a DefaultListModel then we will fill the model  with the list of items and their respective prices, set the list to left component and prices to right component, set the size of the frame and at last frame the logic to list out the correct price for an Item.

import javax.swing.*;
import java.math.BigDecimal;
public class JListExample {
JFrame frame = new JFrame("Storage");
JList<Product> list = new JList<>();
DefaultListModel<Product> model = new DefaultListModel<>();
JLabel label = new JLabel();
JPanel panel = new JPanel();
JSplitPane splitPane = new JSplitPane();
public JListExample() {
list.setModel(model);
model.addElement(new Product("Item1", new BigDecimal("49.00")));
model.addElement(new Product("Item2", new BigDecimal("150")));
model.addElement(new Product("Item3", new BigDecimal("54.5")));
model.addElement(new Product("Item4", new BigDecimal("120.00")));
list.getSelectionModel().addListSelectionListener(e -> {
Product p = list.getSelectedValue();
label.setText(p.getName() + " price is = " + p.getPrice().toPlainString());
});
splitPane.setLeftComponent(new JScrollPane(list));
panel.add(label);
splitPane.setRightComponent(panel);
splitPane.setResizeWeight(0.5); //used to set the way it splits the left and right component
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(splitPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setSize(500,300);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(JListExample::new);
}
private class Product {
String name;
BigDecimal price;
public Product(String name, BigDecimal price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
@Override
public String toString() {
return name;
}
}
}

Output:

JList in Java-2JList in Java-2

Conclusion

Jlist Class in Java is suitable for displaying object data in a list and can be used to activate events on the basis of the selection of particular value in the list. Jlist can be used to represent data in a very orderly manner in Java Applications.

Recommended Articles

This is a guide to the JList in Java. Here we discuss the Introduction,  Constructors of JList, Commonly Used Methods of JList along with examples. You can also go through our other suggested articles to learn more–

0

Shares

Share

Primary Sidebar