Java Graphical User Interface(GUI): JList Functions and ListSelectionListener Using Eclipse IDE

in #utopian-io7 years ago (edited)

What Will I Learn?

  • The user will learn the concept of JList.
  • The user will learn how to create a List of Items.
  • The user will learn functions of JList by using it to change background color of a panel.
  • The user will also learn about ListSelectionListeners.

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

So far, we have learnt a lot of Swing Components starting with J. Today we look at yet another component.

JLIST

JList is a Swing component with which we can display a list of elements. This component also allows the user to select one or more elements visually.
The object of JList class represents a list of text items. The list of text items can be set up so that the user can choose either one item or multiple items. It inherits JComponent class.

ListSelectionListener

This is the listener that is notified when a lists selection value changes.

JList is very similar to JComboBox. ComboBox is a drop down list while JList is simply a list of elements. For the sake of simplicity and ease of understanding, In this tutorial, we shall use JList to perform the same task as JCombo Box from the previous tutorial, that is changing the background color of a panel. This will show us a clearer picture of the similarity and help us grasp the concept quicker.

1.png

2.png

CODE BLOCK

LIST CLASS
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class list extends JFrame {
    private JList list;
    private String[] colornames = {"CYAN", "DARK GRAY", "MAGENTA", "PINK"};
    private Color[] color = {Color.CYAN, Color.DARK_GRAY, Color.MAGENTA, Color.PINK};
    public list() {
    super("JList Demo");
    setLayout(new FlowLayout());
    list = new JList(colornames);
    list.setVisibleRowCount(2);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    add(new JScrollPane(list));
    list.addListSelectionListener(
            new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent event) {
                    getContentPane().setBackground(color[list.getSelectedIndex()]);
                }
            }
            );  
    }
}
MAIN CLASS
import javax.swing.JFrame;
public class listMain {
    public static void main (String args []) {
        list l = new list();
        l.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        l.setSize(400,200);
        l.setVisible(true);
    }
}

LIST 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 list 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 list;
private String[] colornames = {"CYAN", "DARK GRAY", "MAGENTA", "PINK"};
private Color[] color = {Color.CYAN, Color.DARK_GRAY, Color.MAGENTA, Color.PINK};   

The JList variable is declared.

A String Array named “colornames” is created to hold the texts that will be visible in the list.
Another Array of Color type named “color” to hold the actual colors recognizable by the program.

NOTE

The first string “colornames” holds color names recognizable by human while the second string “colors” hold the actual colors that will change the background.

public list() {

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 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 Demo”

setLayout(new FlowLayout());

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

list = new JList(colornames);
list.setVisibleRowCount(2);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
add(new JScrollPane(list));

The JList object is created and the String array “colornames” is passed to it as an argument.
The list will now contain elements of the string array and an action occurs when any of them is clicked.

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

The setSelectionMode method will be used to determine if the user can click multiple items at once. SINGLE SELECTION means the user can only select one item 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.

list.addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
getContentPane().setBackground(color[list.getSelectedIndex()]);

The .addListSelectionListener method is used to add the listener instructions to the list.
A new anonymous ListSelectionListener class is created and is passed as an argument in the .addListSelectionListener method.

The Listener is notified when a value changes in the list and the ListSelectionListener class has a single valueChanged method which must be overridden.

The background color of the panel is then changed. The

getContentPane()

method is used to gain access to the background and it is then changed using the

 .setBackground method

Using the line of code below

colors[list.getSelectedIndex()

The program automatically links the text from String “colornames” in the list and the actual color in “color” string to display the color.

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 Main {

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.

list l = new list()

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.

l.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.

l.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.

l.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.

3.png

When the program is run, only two items in the list is displayed by default. A scroll pane is by the right of the list, enabling the user to scroll down to view other items in the list.

When each color in the list is selected, the background of the panel changes.

4.png

5.png

6.png

7.png

Source Codes from GitHub Account.

8.png

9.png

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]

This post has received a 0.35 % upvote from @drotto thanks to: @banjo.

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!
  • 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.21
TRX 0.20
JST 0.033
BTC 94476.03
ETH 3112.49
USDT 1.00
SBD 3.03