How do I create a JSpinner component?

JSpinner is a single line input field with two buttons (arrow up and arrow down) that allow us to select a value like number or object from a sequence value. It looks like a combobox without a drop-down.

In the following example we create the default JSpinner that will give us a spinner to select an integer value from it.

package org.kodejava.swing;

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

public class JSpinnerCreate extends JFrame {
    public JSpinnerCreate() {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new JSpinnerCreate().setVisible(true));
    }

    private void initialize() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // Create an instance of JSpinner and put it at the top of the frame.
        final JSpinner spinner = new JSpinner();
        getContentPane().add(spinner, BorderLayout.NORTH);

        // Create a JButton and print out the value of the JSpinner when
        // the button is clicked.
        JButton okButton = new JButton("OK");
        okButton.addActionListener(e -> {
            Integer value = (Integer) spinner.getValue();
            System.out.println("value = " + value);
        });
        getContentPane().add(okButton, BorderLayout.SOUTH);
    }
}

How do I get the items of a JList components?

In this example you can see how we can read the items of a JList component. We also obtain the size or the number of items in the JList components.

This can be done by calling JList‘s getModel() method which return a ListModel object. From the ListModel we can get the items size, and we can iterate the entire items of the JList component.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.text.DateFormatSymbols;

public class JListGetItems extends JFrame {
    public JListGetItems() {
        initialize();
    }

    public static void main(String[] args) {
        // Run the program, create a new instance of JListGetItems and
        // set its visibility to true.
        SwingUtilities.invokeLater(
                () -> new JListGetItems().setVisible(true));
    }

    private void initialize() {
        // Configure the frame default close operation, its size and the
        // layout.
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setSize(500, 500);
        this.setLayout(new BorderLayout(5, 5));

        // Create a JList and set the items to the available weekdays
        // names.
        Object[] listItems = DateFormatSymbols.getInstance().getWeekdays();
        JList<Object> list = new JList<>(listItems);
        getContentPane().add(list, BorderLayout.CENTER);

        // Below we start to print the size of the list items and iterates
        // the entire list items or elements.
        System.out.println("JList item size: " + list.getModel().getSize());

        System.out.println("Reading all JList items:");
        System.out.println("-----------------------");
        for (int i = 0; i < list.getModel().getSize(); i++) {
            Object item = list.getModel().getElementAt(i);
            System.out.println("Item = " + item);
        }
    }
}

And here is the result:

JList item size: 8
Reading all JList items:
-----------------------
Item = 
Item = Sunday
Item = Monday
Item = Tuesday
Item = Wednesday
Item = Thursday
Item = Friday
Item = Saturday

How do I set the cell width and height of a JList component?

The cell width and height of a JList can be defined by setting the fixedCellWidth and fixedCellHeight properties. These properties have a corresponding methods called setFixedCellWidth(int width) and setFixedCellHeight(int height).

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.util.Vector;

public class JListCellWidthAndHeight extends JFrame {
    public JListCellWidthAndHeight() {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new JListCellWidthAndHeight().setVisible(true));
    }

    private void initialize() {
        // Initialize windows default close operation, size and the layout
        // for laying the components.
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(500, 175);
        setLayout(new BorderLayout(5, 5));

        // Create a list of vector data to be used by the JList component.
        Vector<String> v = new Vector<>();
        v.add("A");
        v.add("B");
        v.add("C");
        v.add("D");

        JList<String> list = new JList<>(v);
        list.setFixedCellWidth(50);
        list.setFixedCellHeight(50);

        JScrollPane pane = new JScrollPane(list);

        // Add an action listener to the button to exit the application.
        JButton button = new JButton("CLOSE");
        button.addActionListener(e -> System.exit(0));

        // Add the scroll pane where the JList component is wrapped and
        // the button to the center and south of the panel
        getContentPane().add(pane, BorderLayout.CENTER);
        getContentPane().add(button, BorderLayout.SOUTH);
    }
}
JList Cell Width and Height Demo

JList Cell Width and Height Demo

How do I create a JList component?

JList is a component that displays a list of objects and allow user to select one or more items. To create an instance of JList we can pass a vector, an array of objects or a ListModel. In this example we will pass an array of objects that contains a date, string and numbers as the parameters.

By default, the list does not display a scrollbar. To give our JList component a scrollbar we must wrap it with a JScrollPane.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.util.Date;

public class CreateJListDemo extends JFrame {

    public CreateJListDemo() {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new CreateJListDemo().setVisible(true));
    }

    // Initialize the components and configuration of our CreateJListDemo.
    private void initialize() {
        // Define the window title, size and the default close operation.
        this.setTitle("Create JList Demo");
        this.setSize(500, 175);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        // Create an array of arbitrary objects for the JList to display.
        Object[] data = new Object[]{
                new Date(), "One", 1, Long.valueOf("12345"), "Four", "Five"
        };

        // Create an instance of JList and pass data variable as the
        // initial content of it. By default, the JList does not have a
        // scrolling behaviour, so we create a JScrollPane as the container
        // for the JList.
        JList<Object> list = new JList<>(data);
        JScrollPane scrollPane = new JScrollPane(list);

        // Add a button to close the program.
        JButton button = new JButton("Close");
        button.addActionListener(e -> System.exit(0));

        // Set the panel layout to BorderLayout and place the list in the
        // center and the button on the south.
        this.setLayout(new BorderLayout(5, 5));
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        getContentPane().add(button, BorderLayout.SOUTH);
    }
}
Swing JList Demo

Swing JList Demo

How do I create a compound border?

In this example we create a compound border, a border around border. Here, instead of creating a new instance of Border class directly we create the border using the BorderFactory factory class.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import java.awt.*;

public class CompoundBorderExample extends JFrame {
    public CompoundBorderExample() {
        initializeUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new CompoundBorderExample().setVisible(true));
    }

    private void initializeUI() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        BevelBorder raisedBevel =
                (BevelBorder) BorderFactory.createBevelBorder(BevelBorder.RAISED);
        BevelBorder loweredBevel =
                (BevelBorder) BorderFactory.createBevelBorder(BevelBorder.LOWERED);
        Border border = BorderFactory.createCompoundBorder(raisedBevel, loweredBevel);
        JPanel panel = new JPanel();
        panel.setBorder(border);

        setContentPane(panel);
    }
}