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

in #utopian-io7 years ago (edited)

What Will I Learn?

  • The user will learn the concept of JComboBox.
  • The user will learn how to create a Combo Box(Drop Down List).
  • The user will also learn functions of a combo box by using it to change background color of a panel.

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.

JCOMBOBOX

JComboBox is a Swing component which allows the user to select a list of options from a drop down list.

A component that combines a button or editable field and a drop-down list. The user can select a value from the drop-down list, which appears at the user's request. If you make the combo box editable, then the combo box includes an editable field into which the user can type a value.

Items is a Combo Box are stored as array lists. A different array has to be created and passed to the JComboBox in order to hold it.

In this tutorial, we will create a Combo Box (drop-down list) with four color names and an array with four colors. When the user selects a color, the background of the panel changes to the selected color.

1.png

2.png

CODE BLOCK

COMBOBOX CLASS
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class comboBox extends JFrame {
    private JComboBox list;
    private static String[] colornames = {"Yellow", "Red", "Orange", "Green"};
    private static Color[] colors = {Color.YELLOW, Color.RED, Color.ORANGE, Color.GREEN};
    public comboBox() {
        super("Demo");
        setLayout(new FlowLayout());
        list = new JComboBox(colornames);
        add(new JScrollPane(list)); 
        list.addItemListener(
                new ItemListener() {
                    public void itemStateChanged(ItemEvent event) {
                        getContentPane().setBackground(colors[list.getSelectedIndex()]);
                    }
                }
                );  
    }
}
MAIN CLASS
import javax.swing.JFrame;
public class Main {
    public static void main (String args []) {
        comboBox box = new comboBox();
        box.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        box.setSize(400,200);
        box.setVisible(true);
    }
}

COMBOBOX 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 comboBox 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 JComboBox list;
private static String[] colornames = {"Yellow", "Red", "Orange", "Green"};
private static Color[] colors = {Color.YELLOW, Color.RED, Color.ORANGE, Color.GREEN};

The JComboBox variable is declared.

A String Array named “colornames” is created to hold the texts that will be visible in the drop down menu.
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 comboBox() {

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 JComboBox components.

super("JComboBox 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 “JComboBox Demo”

setLayout(new FlowLayout());

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

list = new JComboBox(colornames);

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

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.addItemListener(
new ItemListener() {
public void itemStateChanged(ItemEvent event) {
getContentPane().setBackground(colors[list.getSelectedIndex()]);
}
}
);

The .addItemListener method is used to add the listener instructions to the list.

A new anonymous itemListener class is created and is passed as an argument in the .addItemListener method.

The ItemListener class has a single itemStateChanged 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.

add(list)

Adds the list to the screen.

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

comboBox box = new comboBox()

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

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

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

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

The program is run and the Combo Box is displayed

4.png

When “Yellow” is selected, the background of the panel changes to Yellow

5.png

When “Red” is selected, the background of the panel changes to Red

6.png

When “Orange” is selected, the background of the panel changes to Orange

7.png

When “Green” is selected, the background of the panel changes to Green

8.png

9.png

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 @manishmike10, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!

Nice projects

this is wow nice job

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.