How To Add To A Jlist In Java
- Details
- Written by
- Terminal Updated on 06 July 2019 | Print Electronic mail
JList is a Swing component with which we can display a list of elements. This component too allows the user to select i or more elements visually. This article shows how to work with JList and gain to testify some examples.
We will write lawmaking to accomplish a JList output like:
Output
Table of Contents:
one. Developing A Simple JList
2. Adding a Scrollpane
3. Pick Way
4. Event Handlers
5. Developing a Selection Listener
1. Developing A Simple JList:
Let us at present build a GUI with a JList . Let us say we want to evidence a list of countries. As with other Swing components, the information for a JList is held in a model. This is represented by ListModel interface in the Swing API. The API provides a default implementation of this class named DefaultListModel . Generally, we would want to display a list of homogeneous elements.
Using the DefaultListModel:
Allow us at present see how to create and utilize the DefaultListModel .
Note that, since version 1.7, the API for JList allows the power to create a JList with a parameterized type. And then, we volition use that syntax to create a JList that will accept a List<String> :
DefaultListModel<String> listModel = new DefaultListModel<>(); listModel.addElement("The states"); listModel.addElement("India"); listModel.addElement("Vietnam"); listModel.addElement("Canada"); listModel.addElement("Denmark"); listModel.addElement("France"); listModel.addElement("Bully Great britain"); listModel.addElement("Japan");
The preceding piece of lawmaking is quite simple. Nosotros create an instance of the DefaultListModel grade by declaring it as accepting only String values using the parameterized syntax.
Then, nosotros tin use this model to create a JList:
JList<Cord> countryList = new JList<>(listModel);
Information technology is important to note that the JList annunciation and usage should also be parameterized.
Running the Sample:
Let us provide the full source code and run it:
package net.codejava.swing; import javax.swing.DefaultListModel; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.SwingUtilities; public class JListExample extends JFrame { private JList<String> countryList; public JListExample() { //create the model and add elements DefaultListModel<String> listModel = new DefaultListModel<>(); listModel.addElement("USA"); listModel.addElement("India"); listModel.addElement("Vietnam"); listModel.addElement("Canada"); listModel.addElement("Kingdom of denmark"); listModel.addElement("France"); listModel.addElement("Keen Britain"); listModel.addElement("Japan"); //create the listing countryList = new JList<>(listModel); add(countryList); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("JList Example"); this.setSize(200,200); this.setLocationRelativeTo(nothing); this.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new JListExample(); } }); } }
Initial Output
two. Calculation a Scrollpane:
Allow us now attempt and resize the frame. We will get the post-obit output:
Resized Frame without Scrollbar
But, where are the rest of the countries? They have disappeared from the display. But, ideally, we would want the scrollbar to appear in this instance. To make this happen, nosotros accept to add the list to a scrollpane instead of adding it directly:
add(new JScrollPane(countryList));
Permit us now run the program:
Output with Scrollbar
three. Set Selection Mode for JList
The option mode defines the manner elements can exist selected. There are totally 3 selection modes available to exist set for JList :
SINGLE_SELECTION:
This mode specifies that but a single particular can be selected at any betoken of fourth dimension.
SINGLE_INTERVAL_SELECTION:
This fashion specifies that multiple items can be selected, but they have to exist contiguous. Items tin can be selected contiguously past pressing downwards the shift key and selecting elements with the mouse.
MULTIPLE_INTERVAL_SELECTION:
This mode is the default style. This style specifies that multiple items can exist selected and they may or may non be contiguous.
Allow us now run the program and select multiple items. We volition concord downwardly the shift cardinal and click with mouse to select contiguous items. For non-face-to-face items, nosotros need to press down the ctrl cardinal and select with the mouse.
Nosotros get the following output:
Output with Multiple Items Selected
Changing the Selection Mode:
Let u.s. now attempt and change the option mode. This tin can be done as follows:
countryList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
We make a call to the setSelectionMode() method and brand use of the constants declared in the ListSelectionModel to set our selection mode. Allow u.s.a. now run the program with this selection fashion and try to select multiple items:
Single Selection Mode
When we run the program with this modify and endeavor to select multiple items (past pressing downward either the shift or ctrl central), we find out that we are unable to select multiple items.
4. Issue Handlers:
Let united states now try and develop event handlers for JList . Event treatment in JList is very similar to that of other Swing components. We annals an consequence listener and are notified when the event happens.
5. Developing A Selection Listener for JList
Permit u.s. write a option listener for JList . Knowing the currently selected particular(s) volition be i of the near useful events to know. Note that, the user might have selected one or more particular(s) in the listing. Also, the user may deselect a selected item. If the user had earlier selected only one item and now deselected the same, there would be no selection left in the listing.
The selection listener for the list fires the upshot even in the case of user deselecting an item. This might exist quite useful in certain scenarios.
Let united states of america now add together the following listener code:
countryList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if(!east.getValueIsAdjusting()) { terminal Listing<String> selectedValuesList = countryList.getSelectedValuesList(); System.out.println(selectedValuesList); } } });
The above code registers a ListSelectionListener using the addListSelectionListener() method. Nosotros employ an anonymous inner course to implement the event listener interface. We implement the valueChanged() method. Nosotros telephone call the handy method getSelectedValuesList() on the JList case which returns a List<String> , as in our instance, we had declared the JList to comprise merely Cord values. For illustration purposes, nosotros merely impress this listing on the console which prints the list of values selected.
Now, run the plan and select a few items (single, multiple, face-to-face, not-face-to-face) and cheque the output on the panel. Now, deselect all items in the list and cheque the output on the console. It will print an empty list.
We employ extra if condition in the code which checks if the list is nevertheless adjusting the status. If information technology is not, we think the selected items.
Hither is the full source code of our GUI:
bundle internet.codejava.swing; import java.util.List; import javax.swing.DefaultListModel; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; import javax.swing.consequence.ListSelectionEvent; import javax.swing.effect.ListSelectionListener; /** * JList bones tutorial and example * * @author wwww.codejava.internet */ public course JListExample extends JFrame { individual JList<Cord> countryList; public JListExample() { //create the model and add elements DefaultListModel<String> listModel = new DefaultListModel<>(); listModel.addElement("United states of america"); listModel.addElement("Republic of india"); listModel.addElement("Vietnam"); listModel.addElement("Canada"); listModel.addElement("Kingdom of denmark"); listModel.addElement("France"); listModel.addElement("U.k."); listModel.addElement("Nihon"); //create the list countryList = new JList<>(listModel); countryList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent due east) { if (!east.getValueIsAdjusting()) { final List<Cord> selectedValuesList = countryList.getSelectedValuesList(); Organisation.out.println(selectedValuesList); } } }); add together(new JScrollPane(countryList)); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("JList Instance"); this.setSize(200, 200); this.setLocationRelativeTo(zip); this.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new JListExample(); } }); } }
Other Java Swing Tutorials:
- Java Swing Hullo Globe Tutorial for Beginners Using Text Editor
- JFrame bones tutorial and examples
- JPanel basic tutorial and examples
- JLabel basic tutorial and examples
- JTextField bones tutorial and examples
- JButton basic tutorial and examples
- JComboBox basic tutorial and examples
- JCheckBox basic tutorial and examples
- JTree basic tutorial and examples
About the Author:
Nam Ha Minh is certified Coffee programmer (SCJP and SCWCD). He started programming with Java in the time of Coffee i.4 and has been falling in love with Java since then. Brand friend with him on Facebook and scout his Java videos you lot YouTube.
Add together annotate
How To Add To A Jlist In Java,
Source: https://www.codejava.net/java-se/swing/jlist-basic-tutorial-and-examples
Posted by: clearyhishowas.blogspot.com
0 Response to "How To Add To A Jlist In Java"
Post a Comment