Java GUI: JSpinner and functions Using Eclipse IDE

in #utopian-io7 years ago (edited)

What Will I Learn?

  • The user will learn the concept behind the Swing Construct called JSpinner
  • The user will learn the various JSpinner Models.
  • The user will learn how to pass a list as a Spinner argument.

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

Intermediate.

Tutorial Contents

This tutorial follows from previous tutorials, on the topic of Swing constructs in GUI beginning with ‘J’. The tutorial introduce another interesting construct;

JSpinner

A single line input field that lets the user select a number or an object value from an ordered sequence. Spinners typically provide a pair of tiny arrow buttons for stepping through the elements of the sequence. The keyboard up/down arrow keys also cycle through the elements. The user may also be allowed to type a (legal) value directly into the spinner. Although combo boxes provide similar functionality, spinners are sometimes preferred because they don't require a drop down list that can obscure important data.
A JSpinner's sequence value is defined by its SpinnerModel. The model can be specified as a constructor argument and changed with the model property. SpinnerModel classes for some common types are provided: SpinnerListModel,SpinnerNumberModel, and SpinnerDateModel.
A JSpinner has a single child component that's responsible for displaying and potentially changing the current element or value of the model, which is called the editor. The editor is created by the JSpinner's constructor and can be changed with the editor property. The JSpinner's editor stays in sync with the model by listening for ChangeEvents.

Constructors in JSpinner

JSpinner()

Constructs a spinner with an Integer SpinnerNumberModel with initial value 0 and no minimum or maximum limits.

JSpinner(SpinnerModel model)

Constructs a complete spinner with pair of next/previous buttons and an editor for the SpinnerModel.

In this tutorial, we will create two classes;

  • Class 1: We will create three JSpinner objects to simulate the user entering Date of Birth details; First object, the user enters day, second object; user enters month and third object; user enters year.

  • Class 2: Contains main method for run instructions.

This tutorial is done in assumption that the user follows through previous tutorials and is familiar with the coding terms used therein, also, have basic Java programming knowledge.

IMPORTANT NOTE

If you follow previous tutorials, you will notice these Swing Constructs are created the same way, however, their functionalities differ.
You may use the same line of code to create objects of these constructs, but making them function requires different methods of coding.
This is where this tutorial comes in handy. The tutorial uses an example to illustrate its functions and actions that can be associated with it.

1.png

2.png

3.png

CODE BLOCK

spinner Class
import java.awt.*;
import java.util.Arrays;
import javax.swing.*;
public class spinner extends JFrame {
private JSpinner dateSpinner;
private JLabel dateLabel;
private JSpinner monthSpinner;
private JLabel monthLabel;
private JSpinner yearSpinner;
private JLabel yearLabel;
private JLabel label;
private JPanel panel;
String[] month = {"January ", "February ", "March ", "April ", "May ",
"June ", "July ", "August ", "September ", "October ", "November ", "December "};
    public spinner() {
        super("JSpinner Demo");
        setLayout(null);
        panel = new JPanel();
        getContentPane().setBackground(Color.YELLOW);
        add(panel);
        label = new JLabel("SELECT DATE OF BIRTH");
        label.setFont(new Font("Times New Roman", Font.BOLD, 28));
        label.setBounds(70, 21, 400, 20);
        add(label);
        dateLabel = new JLabel("Select Date");
        dateLabel.setFont(new Font("Times New Roman", Font.BOLD, 20));
        dateLabel.setBounds(130, 71, 100, 14);
        SpinnerModel dateModel = new SpinnerNumberModel(1, 0, 31, 1);
        dateSpinner = new JSpinner(dateModel);
        dateSpinner.setBounds(290, 71, 36, 19);
        add(dateLabel);
        add(dateSpinner);
        monthLabel = new JLabel("Select Month");
        monthLabel.setFont(new Font("Times New Roman", Font.BOLD, 20));
        monthLabel.setBounds(130, 101, 400, 20);
        SpinnerModel monthModel = new SpinnerListModel(Arrays.asList(month));
        monthSpinner = new JSpinner(monthModel);
        monthSpinner.setBounds(290, 101, 90, 19);
        add(monthLabel);
        add(monthSpinner);
        yearLabel = new JLabel("Select Year");
        yearLabel.setFont(new Font("Times New Roman", Font.BOLD, 20));
        yearLabel.setBounds(130, 141, 100, 14);
        SpinnerModel yearModel = new SpinnerNumberModel(1985, 1980, 1999, 1);
        yearSpinner = new JSpinner(yearModel);
        yearSpinner.setEditor(new JSpinner.NumberEditor(yearSpinner, "#"));
        yearSpinner.setBounds(290, 141, 56, 19);
        add(yearLabel);
        add(yearSpinner);
    }
}
spinnerMain Class
import javax.swing.JFrame;
public class spinnerMain {
    public static void main (String args []) {
        spinner spin = new spinner();
        spin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        spin.setSize(500, 300);
        spin.setVisible(true);
    }
}

Output

ezgif.com-optimize.gif

spinner Class

String[] month = {"January ", "February ", "March ", "April ", "May ", "June ", "July", "August ", "September ", "October ", "November ", "December "};

A String “month” is declared and initiated; to be passed to a Spinner object as argument.

panel = new JPanel();
getContentPane().setBackground(Color.YELLOW);
add(panel);

As in previous tutorials, the creation of a JPanel object. Background color is set to yellow using the getContentPane().setBackground() method.

add(panel) to add to the frame.

label = new JLabel("SELECT DATE OF BIRTH");
label.setFont(new Font("Times New Roman", Font.BOLD, 28));
label.setBounds(70, 21, 400, 20);
add(label);

New JLabel object creation called “label” holding “SELECT DATE OF BIRTH” as text.

Font style and size is set using .setFont() method.

.setBounds()

The setBounds() method not only specifies the size of the frame, but the location of the upper left corner:
public void setBounds(int x, int y, int width, int height)
This puts the upper left corner at location (x, y), where x the the number of pixels from the left of the screen and y is is the number from the top of the screen.height and width are as before.

The position of the JLabel object; the x and y coordinates, height and width is set.
Label object is then added to the frame.

dateLabel = new JLabel("Select Date");
dateLabel.setFont(new Font("Times New Roman", Font.BOLD, 20));
dateLabel.setBounds(130, 71, 100, 14);
SpinnerModel dateModel = new SpinnerNumberModel(1, 0, 31, 1);
dateSpinner = new JSpinner(dateModel);
dateSpinner.setBounds(290, 71, 36, 19);
add(dateLabel);
add(dateSpinner);

A JLabel object “dateLabel” is created holding the text “Select Date”. The size and font is also set using in built methods.

.setBounds() is used to set x and y coordinates in the frame with regards to height and width.

SpinnerNumberModel()

A SpinnerModel for sequences of numbers. The upper and lower bounds of the sequence are defined by properties called minimum and maximum. The size of the increase or decrease computed by the nextValue and previousValue methods is defined by a property called stepSize. The minimum and maximum properties can be null to indicate that the sequence has no lower or upper limit. All of the properties in this class are defined in terms of two generic types: Number andComparable, so that all Java numeric types may be accommodated. Internally, there's only support for values whose type is one of the primitive Number types: Double, Float, Long, Integer, Short, or Byte.

An object of the SpinnerNumberModel class “Model” is created to be passed as argument when a spinner is created. Minimum number allowed for the spinner is 1 while maximum number is 31.

JSpinner object “dateSpinner” is created and the dateModel object created earlier which holds the SpinnerNumberModel is passed as argument.

.setBounds() sets location as described earlier.

The Label and Spinner objects are then added to the screen.

Soft Note

This program creates three JSpinner objects and adds functionalities to them. One JLabel and JSpinner object has been created above requiring the user to enter a date ranging from 1 to 31. This is to simulate days of the month.

Similar sequence is used to create the second and third spinners.

monthLabel = new JLabel("Select Month");
monthLabel.setFont(new Font("Times New Roman", Font.BOLD, 20));
monthLabel.setBounds(130, 101, 400, 20);
SpinnerModel monthModel = new SpinnerListModel(Arrays.asList(month));
monthSpinner = new JSpinner(monthModel);
monthSpinner.setBounds(290, 101, 90, 19);
add(monthLabel);
add(monthSpinner);

As the first Label and Spinner object, another label and spinner object is created here to simulate choosing a month.

.setBounds() is again used to set location and width and height of objects.

SpinnerListModel()

This is a simple implementation of SpinnerModel whose values are defined by an array or a List.
For example to create a model defined by an array of the names of months.
Arrays.asList() method is used to convert an array to a list. The array “month” is passed to the method as an argument.

A new Spinner “monthSpinner” is created and the “monthModel” passed as argument to simulate selection of month.

Label and Spinner objects are added to the frame.

yearLabel = new JLabel("Select Year");
yearLabel.setFont(new Font("Times New Roman", Font.BOLD, 20));
yearLabel.setBounds(130, 141, 100, 14);
SpinnerModel yearModel = new SpinnerNumberModel(1985, 1980, 1999, 1);
yearSpinner = new JSpinner(yearModel);
yearSpinner.setEditor(new JSpinner.NumberEditor(yearSpinner, "#"));
yearSpinner.setBounds(290, 141, 56, 19);
add(yearLabel);
add(yearSpinner);

Following the sequence above, the same is used to create the label and spinner object to simulate selecting a year. The minimum value for year is set to 1985, while the maximum value is set to 1999.

.setBounds() is used to set location, width and height and then the label and spinner objects are added to the screen using .add() method.

spinnerMain class

import javax.swing.JFrame;

public class spinnerMain {
public static void main (String args []) {
spinner spin = new spinner();
spin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
spin.setSize(500, 300);
spin.setVisible(true);
    }
}

Main class containing main method with instructions on how the program runs.

An object of the Slider class is created. The slider class holds instructions for running the program.

The program Exit Mode is set. This will close the program when user clicks the “X” button on the frame.

Size of the window is set using inbuilt methods .setSize

Visibility setting is set, making the frame visible, the code .setVisible(true) is used.

ezgif.com-optimize.gif

When the program is run, it simulates a form requiring the user to enter date of birth details.

The user clicks the little arrows by the side of the JSlider object to change dates and month upwards or downwards.

This is a basic example to illustrate the functions of JSpinner.

4.png

5.png

6.png

Source Codes from Github Account.

You can get the codes at my GitHub Account 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]

Congratulations! This post has been upvoted from the communal account, @minnowsupport, by will-ugo from the Minnow Support Project. It's a witness project run by aggroed, ausbitbank, teamsteem, theprophet0, someguy123, neoxian, followbtcnews, and netuoso. The goal is to help Steemit grow by supporting Minnows. Please find us at the Peace, Abundance, and Liberty Network (PALnet) Discord Channel. It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.

If you would like to delegate to the Minnow Support Project you can do so by clicking on the following links: 50SP, 100SP, 250SP, 500SP, 1000SP, 5000SP.
Be sure to leave at least 50SP undelegated on your account.

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.20
TRX 0.25
JST 0.038
BTC 97445.74
ETH 3477.06
USDT 1.00
SBD 3.16