Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to develop applications with Swing components

In this article, we will learn about javax.swing package and how to use them in our code. This article covers a lot, about Swing components from the basic level to an intermediate level.

The package ‘javax.swing’ contains classes and interfaces for creating components like dialogs, frames, buttons, tables etc. This package is mainly used for developing standalone applications. An example for standalone application is Netbeans. In addition, javax.swing package contains classes to build layouts, classes to create applets etc. Let us look at some of the features in more detail through examples.

Step 1

In this step we will learn to create a simple frame with buttons, text fields and labels.

Listing 1: Code to execute Step 1

import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class ExampleSwing {
//declaration 
JTextField textfield1=new JTextField(13);
JTextField textfield2=new JTextField(13);
JTextField textfield3=new JTextField(13);
JLabel label1=new JLabel("Result");
JButton button1=new JButton("Add 2 no.");
JButton button2=new JButton("Subtract  2 no.");
//code to generate a frame with components
public void generate(){
JFrame f=new JFrame("Swing");
Container c=f.getContentPane();
f.setLayout(new FlowLayout(2));
f.setTitle("Calculate");
f.add(textfield1);
f.add(textfield2);
f.add(button1);
f.add(button2);
f.add(label1);
f.add(textfield3);
f.setSize(233,343);
f.setVisible(true);
}
// main method
public static void main(String args[]){
ExampleSwing obj=new ExampleSwing();
    obj. generate ();
}
}

When we run the above program, the program will display a frame with a title ‘Calculate’. Inside the frame you can see two buttons with titles ‘Add 2 no.’ and ‘Subtract 2 no.’, three text fields, and a label captioned as ‘Result’. Textfields are enterable. But when you click the buttons nothing will happen. Because we have not written any code to manage events. This code just builds only the front end user interface. In the above program, FlowLayout class and Container class is used from the ‘java.awt’ package to build the user interface. Container is a component which can hold other components.

Step 2

In this step we will learn to create a frame with menus and a table.

Listing 2: Code to execute Step 2

import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TableMenu {
//declaration 
JMenu menu1;
JMenu menu2;
JMenu menu3;
JMenuBar menubar;
JMenuItem menuitem1;
JMenuItem menuitem2;
JMenuItem menuitem3;
JMenuItem menuitem4;
JMenuItem menuitem5;
JMenuItem menuitem6;
//code to generate a table with menus
public void generate(){
menu1=new JMenu("Home");
menu2=new JMenu("Edit");
menu3=new JMenu("Add");
menubar=new JMenuBar();
menuitem1=new JMenuItem("New");
menuitem2=new JMenuItem("Browse");
menuitem3=new JMenuItem("Cut");
menuitem4=new JMenuItem("Delete");
menuitem5=new JMenuItem("Columns");
menuitem6=new JMenuItem("Rows");
JFrame f=new JFrame("Table");
DefaultTableModel tablemodel=new DefaultTableModel(4,4);
JTable table=new JTable(tablemodel);
Container c=f.getContentPane();
f.setLayout(new FlowLayout());
menubar.add(menu1);
menubar.add(menu2);
menubar.add(menu3);
menu1.add(menuitem1);
menu1.add(menuitem2);
menu2.add(menuitem3);
menu2.add(menuitem4);
menu3.add(menuitem5);
menu3.add(menuitem6);
f.add(menubar);
f.add(table);
f.setLayout(new FlowLayout());
f.setSize(322,232);
f.setVisible(true);
}
// main method
public static void main(String args[]){
    TableMenu tableobject=new TableMenu();
    tableobject.generate();
}
}

When we run the above program, the program will display 3 menus with some menu items and a table with rows and columns as specified in the program. In the above program, we have used ‘DefaultTableModel’ class from the ‘javax.swing.table’ package. This class is responsible for defining the number of rows and columns in a table.

Step 3

In this step we will learn to create an Applet with some colourfulcolorful shapes.

An applet is a java program that can be embedded in a webpage. We can create graphics, add components inside an applet and make it execute on a webpage.

Listing 3: Code to execute Step 3

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Paint;
import java.awt.Polygon;
import javax.swing.JApplet;
public class GraphicApplet extends JApplet {
public void paint(Graphics appletobj)
{
appletobj.setColor(Color.YELLOW);
appletobj.fillOval(23, 44, 53, 34);
appletobj.setColor(Color.red);
appletobj.fillRect(83,44, 53, 34);
appletobj.setColor(Color.BLUE);
appletobj.fillArc(133, 44, 43, 114, 53,34);
appletobj.setColor(Color.CYAN);
appletobj.fillRoundRect(173, 44, 56, 56, 3, 45);
appletobj.setColor(Color.DARK_GRAY);
appletobj.fill3DRect(247, 44, 34, 45, true);
}
}

The above code will display some colorful shapes according to the specification. In all ‘fill’ methods above, the first two parameters defines x axis and y axis and other parameters defines size, width, height etc. We can change the parameters and colors to get different outputs. The method ‘paint’ is a predefined method from java.awt.Container class. It always accepts a ‘Graphics’ object. These things should not be changed.

Step 4

In this step we will create a simple application which will accept the user name, password and email id from the user and generates a success message according to the user name with the help of listeners.

Listing 4: Code to execute Step 4

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class SwingListeners {
    //declaration
    JTextField textField1;
    JTextField textField2;
    JPasswordField passwordField;
    JFrame f;
    Container container;
    JLabel label1;
    JLabel label2;
    JLabel label3;
    JButton button1;
    JButton button2;
    FlowLayout flowlayout;
    ActionListener cancellistener, submitlistener;
    //code to generate form
    public void generateForm() {
    textField1 = new JTextField(12);
    textField2 = new JTextField(19);
    passwordField = new JPasswordField(12);
    f = new JFrame();
    f.setTitle("Registration Form");
    flowlayout = new FlowLayout();
    container = f.getContentPane();
    label1 = new JLabel("Enter a username");
    label2 = new JLabel("Enter a password");
    label3 = new JLabel("Enter a email id");
    button1 = new JButton("Submit");
    button2 = new JButton("Cancel");
    submitlistener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    JOptionPane.showMessageDialog
            (null, "User Details Created Successfully");
            }
        };
     cancellistener = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
     textField1.setText(null);
     textField2.setText(null);
     passwordField.setText(null);
            }
        };
     button1.addActionListener(submitlistener);
     button2.addActionListener(cancellistener);
     f.add(label1);
     f.add(textField1);
     f.add(label2);
     f.add(passwordField);
     f.add(label3);
     f.add(textField2);
     f.add(button1);
    f.add(button2);
    f.setLayout(flowlayout);
    f.setSize(341, 231);
    f.setVisible(true);
    }
   //main method
    public static void main(String args[]) {
    SwingListeners swinglistenerobject = new SwingListeners();
    swinglistenerobject.generateForm();
    }
}

In the above code, a new field called ‘JpasswordField’ is introduced. ‘JPasswordField’ is similar to ‘JTextField’.

The only difference is, in ‘JPasswordField’ the text will not be displayed.

When we run the above code, we can see a window, asking for user name, password and email id. On clicking ‘Submit’ button, we will get a success message. If we click ‘Cancel’ button, the values entered in the fields will get erased. As we can see, the above code makes use of two classes, ActionEvent and ActionListener from the ‘java.awt.event’ package. ‘java.awt.event’ also has classes supporting other events like mouse click, key pressed and many other user actions.

Note that the application does not store the user name, password and email id anywhere in the system.

Screenshots of the application developed are given below.

Screenshots of step - 1

Figure 1: Screenshots of step - 1

Screenshot of step - 2

Figure 2: Screenshot of step - 2

Screenshot of step - 3

Figure 3: Screenshot of step - 3

Screenshot of step - 4
Screenshot of step - 5

Figure 4: Screenshot of step - 4

Conclusion:

In this article, we have learnt about the Swing components, Container, Listeners, Layouts and also implemented them in our program. Then we created a simple applet. We also learnt about event handling in Java. See you next time!

Also read



I have done my bachelor in Computer Science and I am well versed with programming languages such as JAVA, C#, html and done courses on Android development.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login