JLabel and JComboBox in Java Using NetBeans IDE

Introduction

This article describes how JLabel and JCombobox can be created in Java. The Netbeans IDE is used for the development of the example.

What is JLabel

Label is basically used to display text and Jlabel is also used like a label for displaying text, but Jlabel also supports more features like the displaying of images.

What is JComboBox

Combobox is basically used for the user to select one choice from several given choices. Combobox is also known as a drop down list. The following image is used to display a combobox.

fig1.jpg

Packages Imported

java.awt.*;

AWT stands for Abstract Window Toolkit and the AWT package is imported to use AWT components like label, list, checkbox and so on.

javax.swing.*;

Swing is an extended version of AWT and it is used to provide a graphical user interface to programs. Swing has components such as JComboBox, JScroll Pane, JTabbed Pane and so on.

Features of JLabel

  • JLabel supports images.
  • JLabel supports Borders.
  • JLabel supports HTML content.

Example

In this example; we show how to create a JLabel and JCombobox in Java using the Netbeans IDE. There are certain steps in the Netbeans IDE that we need to follow as explained below.

Step 1

Open the Netbeans IDE and click on "File" -> "New project" then choose "Java project" then provide a name (for example JlbCmbBx ) then click on "Ok" then right-click on our project and choose "New" -> "Java class" and then provide your class name (as JlbCmbBx.java) and click "Ok" then write the following code over there.

Step 2

In this class write the following code (the class name is "JlbCmbBx"):

import javax.swing.*;

import java.awt.*;

public class JlbCmbBx extends JFrame

{

public void launchFrame()

{

setLayout(new FlowLayout());

JLabel lb=new JLabel("Colors");

JComboBox jcb=new JComboBox();

jcb.addItem("red");

jcb.addItem("black");

add(lb);

add(jcb);

setSize(300,300);

setVisible(true);

}

public static void main(String[] args)

{

JlbCmbBx obj=new JlbCmbBx();

obj.launchFrame();

}

}


fig2.jpg

 

Step 3

 

Now go to JlbCmbBx and right-click on that, click on "Run" from the menu bar as in the following:

 

fig 3.jpg

 

Output

 

This output shows the combobox with the two options red and black; the user can select one of them.

 

fig4.jpg

 


Up Next
    Ebook Download
    View all
    Learn
    View all