Java Graphical User Interface(GUI): JList Multiple Item Selection Using Eclipse IDE

in #utopian-io7 years ago (edited)

What Will I Learn?

  • The user will learn how to create a JList with multiple selection option multiple.
  • The user will learn how to move multiple items from one list to another at once.

Requirements

  • A computer System is required for this tutorial.
  • Java Software Development Kit(JDK) must be installed on your computer.
  • An Integrated Development Environment(IDE) such as Eclipse or NetBeans is required to be installed on your computer.

Get JDK here

Get Eclipse here

Get NetBeans here

Difficulty

The codes in this tutorial are around the same level as other tutorials so difficulty level will be same as others - Intermediate.

Tutorial Contents

Following the previous tutorial on JList, it only showed us how to create a list and select one item at a time.

In JList, it is possible to select multiple items for different purposes, this tutorial shows us how, using the ListSelectionModel method.

This tutorial is done assuming the user followed through on the previous tutorial here

We will create two lists; “countryList” and “africanList”. The first contains a list of countries; the aim of the program is for the user to select all the African countries in the countries list at once and move them to the second list.

8.jpg

9.jpg

CODE BLOCK

MULTIPLELIST CLASS
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class multipleList extends JFrame {
    private JList countryList;
    private JList africanList;
    private JButton move;
    private String[] list = {"Austria", "Cape Verde", "Denmark", "Nigeria", "Ghana", "Brazil"};
    public multipleList() {
        super("JList Multiple Selection Demo");
        setLayout(new FlowLayout());
        countryList = new JList(list);
        countryList.setVisibleRowCount(3);
        countryList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        add(new JScrollPane(countryList));
        move = new JButton("Move");
        move.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        africanList.setListData(countryList.getSelectedValues());
                    }
                }           
                );
        add(move);
        africanList = new JList();
        africanList.setVisibleRowCount(3);
        africanList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        africanList.setFixedCellHeight(20);
        africanList.setFixedCellWidth(90);
        add(new JScrollPane(africanList));
    }
}
LISTMAIN CLASS
import javax.swing.JFrame;
public class listMain {
    public static void main (String args []) {
        multipleList selection = new multipleList();
        selection.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        selection.setSize(400, 200);
        selection.setVisible(true);
    }
}

MULTIPLELIST CLASS

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

These are Import Statements. Import Statements are used to reference methods that are in other packages. Java comes with a bunch of in built methods and these methods are in different packages. When the user imports a class, the user has access to all methods in the class because they are automatically imported.

public class multipleList extends JFrame {

This is the name of the current class. When you start a new class, it must be saved with a name. This class extends JFrame. In Java, it is possible for classes to inherit properties of another class. Here, this class inherits basic Frame properties like a window with close, maximize and minimize buttons from the JFrame class. The extends keyword is used to achieve this.

private JList countryList;
private JList africanList;
private JButton move;
private String[] list = {"Austria", "Cape Verde", "Denmark", "Nigeria", "Ghana", "Brazil"};

Two JList variables “countryList” and “africanList” are declared.

A String Array named “list” is created containing a list of countries.

public multipleList() {

A Constructor is a block of code that lets you initialize variables immediately an object is created. Methods can be created and called later but with constructors, initialization is done immediately. Constructors have the same name as the class name and is called when an object of the class in created.
The above constructor does not carry any arguments and is created to hold the JList components.

super("JList Multiple Selection Demo");

The super keyword is used here to refer to properties of a superclass; in this case the JFrame class.
In this context, it is used to set the title of the newly created window. The title of the window is “JList Multiple Selection Demo”

setLayout(new FlowLayout());

The FlowLayout class. This provides a simple layout that is used by JFrame components.

countryList = new JList(list);
countryList.setVisibleRowCount(3);
countryList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
add(new JScrollPane(countryList));

A JList “countryList” object is created and the String array “list” is passed to it as an argument.
The list will now contain elements of the string array.

The setVisibleRowCount method is used to set how many items will be seen in the list by default. The number 3 means the first two items will be seen by default.

countryList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

This is the major subject of this tutorial.

ListSelectionModel interface represents the current state of the selection for any of the components that display a list of values with stable indices. The selection is modeled as a set of intervals, each interval represents a contiguous range of selected list elements. The methods for modifying the set of selected intervals all take a pair of indices, index0 and index1, that represent a closed interval, i.e. the interval includes both index0 and index1.

.MULTIPLE_INTERVAL_SELECTION

A value for the selectionMode property to select one or more contiguous ranges of indices at a time.

The List is the added to the screen with a scrollpane using the JScrollPane method.

IMPORTANT

Instead of creating a whole newClass and creating an eventHandler object like we have been doing in previous tutorial, here is a much simpler, shorter way to implement the ItemListener action and associate with the list.

move = new JButton("Move");
move.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
africanList.setListData(countryList.getSelectedValues());
}
}
);
add(move);

A JButton object “move” is created.
The .addActionListener method is used to add the listener instructions to the button.
A new anonymous ActionListener class is created and is passed as an argument in the .addActionListener method.

The Listener is notified when a the button is clicked and the class has a single actionPerformed method which must be overridden.

africanList.setListData(countryList.getSelectedValues());

The setListData method is used to set value of the second list. Using the getSelectedValues method, the program populates the second list with the selected values from the first list.

LISTMAIN CLASS

import javax.swing.JFrame;

This is an import statement. This statement is used specifically to import the JFrame class from Application Program Interface (API). This allows the user to use all methods contained in it.

public class LISTMAIN {

This is just like creating a new file or document and saving it with a name. This is the name of the new class created.

public static void main (String args []) {

The Java main method. Every program must contain this method in order to execute. It is the point from which the program begins execution.
A program without this method will not execute.

multipleList selection = new multipleList();

An Object of the list class is created. This enables the user to call in built GUI methods that will help to properly display the JList component to the screen.

selection.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

This inbuilt method needs to be called before the program is run . This method states the default behavior of the windows when the “close”(x) button is clicked.
Here, it tells the window to close.

selection.setSize(400,200);

This is to set the size of the object to the specified width and height. In this case, the specified dimensions are (400,200).

Values of width and height are non-negative integers. The constructors that allow you to create a dimension do not prevent you from setting a negative value for these properties. If the value of width or height is negative, the behavior of some methods defined by other objects is undefined.

selection.setVisible(true);

This simply determines whether a component is displayed on the screen. It has two states. True and false.

With setVisible( false ), if the Component is not already marked invisible, setVisible calls invalidate() which invalidates the Container’s layout and the chain of parents since there is now more screen real estate in the Container and the positions of the siblings must be adjusted to flow into the freed space.

With setVisible( true ), if the Component is not already marked visible,setVisible calls invalidate() which invalidates the Container’s layout and the chain of parents since there is now less screen real estate in the Container and the positions of the siblings must be adjusted to squeeze in this new Component.

1.jpg

Program is run showing two lists; one is populated with names of countries while the other is empty.
The goal is to select the African countries using Ctrl button and move them to the other empty list by clicking the move button.

2.jpg

3.jpg

Multiple items being selected at once

4.jpg

The selected items have been moved to the list by the right by clicking the move button.

5.jpg

6.jpg

7.jpg

Source Codes from GitHub Account.

You can get the codes here if you want to try it on your own.

REFERENCES

Curriculum

Similar posts already posted on Utopian are:



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @will-ugo I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • You are generating more rewards than average for this category. Super!;)
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Coin Marketplace

STEEM 0.20
TRX 0.25
JST 0.038
BTC 97445.74
ETH 3477.06
USDT 1.00
SBD 3.16