Share
Java Programming

Course Outline

Week 1
Week 2
Week 3
Week 4
Week 5
Week 6
Week 7
Week 8

Advanced GUI Topics

  • Using Color
  • Using Layout Managers
    •  BorderLayout
    •  FlowLayout
    •  GridLayout
    •  CardLayout
  • Using the JPanel Class
  • Creating JScrollPanes
  • Events and Event Handling
  • Using Menus
    • JCheckBoxMenuItem
    • RadioButtonMenuItem

SponsoredAdvertise

Explanation to week content part I

Computer programs usually are more user friendly (and more fun to use) when they contain user interface (UI) components. UI components are buttons, text fields, and other components with which the user can interact. Java’s creators have packaged a number of prewritten components in the Swing package. Swing components are UI elements such as dialog boxes and buttons; you can usually recognize their names because they begin with J.

 

UI components are also called controls or widgets. Each Swing component is a descendant of a JComponent, which in turn inherits from the java.awt.Container class. You can insert the statement import javax.swing.*; at the beginning of your Java program files so you can take advantage of the Swing UI components and their methods.When you import Swing classes, you use the javax.swing package instead of java.swing. The x originally stood for extension, so named because the Swing classes were an extension of the original Java language specifications.

 

When you use Swing components, you usually place them in containers. A container is a type of component that holds other components so you can treat a group of them as a single entity. Containers are defined in the Container class. Often, a container takes the form of a window that you can drag, resize, minimize, restore, and close.

 

When developing an application with graphical user interface, it is better to place the classes in packages for easy access of the classes whenever one wishes to work on them. Graphical user interface classes can be placed in the gui package and the main class which contains the public static main method can be placed in the main package.

 

To create a package, you simply right click on the src in your project and then new then package and give the package a name.

 

As it has been stated above, you have to import the javax.swing.*. So you will have to write the import syntax above the class name.

Our GUI classes will inherit from the JFrame class, hence we extend the JFrame class by writing the syntax:

 

public class NameOfTheClass extends JFrame{

           

}

 

Some of the GUI components like buttons have event handling. Event handling is what should be done when the button is clicked or when a window is closed etc.

 

For a graphic user interface which handles event, you have to implement the method for handling the events. So you have to modify your above basic syntax to:

 

public class NameOfTheClass extends JFrame implements ActionListener,ItemListener,WindowListener{

 

}

 

You will get an error because you have not yet implemented the methods for ActionListener, ItemListener and WindowListener.

 

You can click on the red error alert that appears on that line and click on the suggested solution which states add unimplemented methods or import .

 

Image 



The suggestion may not appear immediately but there maybe suggestions to import the ActionListener, ItemListener, WindowListener classes first before the Add unimplemented methods suggestion may appear.

 

After clicking on the Add unimplemented methods, those methods will be included in your project so you can add your code to the necessary event handling methods.

 

For a class by name Window, the basic class content will be like this:

 

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
 
import javax.swing.*;

public class Window extends JFrame implements ActionListener,ItemListener,WindowListener{
 
      @Override
      public void itemStateChanged(ItemEvent e) {
            // TODOAuto-generated method stub
           
      }
 
      @Override
      public void actionPerformed(ActionEvent e) {
            // TODOAuto-generated method stub
           
      }
 
      @Override
      public void windowActivated(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowClosed(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowClosing(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowDeactivated(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowDeiconified(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowIconified(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowOpened(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
}


We will then have to create a constructor for the class where we design the graphic user interface in the constructor block.

 

Remember a constructor of a class has the same name as the class.

 

The basic syntax for a constructor is:

 

publc className(Arguments for the constructor){

 

}

 

When a constructor has arguments, any time the object of that class is created, the values for the arguments must be passed in the constructor.

 

If we want any window we design whose object to be created should take the title of the window, the width of the window and the height of the window, we will have three constructor inputs for the arguments.

 

Hence our constructor will be like this:

 

public className(String title, int width, int height){

 

}

 

Hence the constructor for the above class Window will be:

 

public Window(String title, int width, int height){

 

}

 

We will use the super keyword to override the JFrame title argument. So in the constructor we write super(title);This means, the window will have the title we pass in the GUI class when we create object of the class.

 

Our constructor will then be:

 

public Window(String title, int width, int height){

            super(title);

}

 

The JFrame has a method by name setSize which takes the width and height of the window as arguments. We will call this method to set the window width and height which will be the value we pass in the constructor when creating the GUI object.

 

The constructor will then be:

 

public Window(String title, int width, int height){
            super(title);
            setSize(width,height);
}

 

Our Window class will look like this:

 

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
 
import javax.swing.*;
public class Window extends JFrame implements ActionListener,ItemListener,WindowListener{
      public Window(String title, int width, int height){
            super(title);
            setSize(width,height);
      }
     
      @Override
      public void itemStateChanged(ItemEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowActivated(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowClosed(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowClosing(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowDeactivated(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowDeiconified(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowIconified(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowOpened(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
}

 

 

We create the object of the GUI class just as we create any object. Thus:

 

ClassName objectName = new ClassName(constructor arguments comes here);

 

To create an object having My first GUI Window as the title that will show on the window and a width of 200 and height of 100 for the Window class, we can write:

 

Window window = new Window(“My First GUI Window”, 200,100);

 

By default the window is invisible. You must set the window for the object to visible by calling the method setVisible(which takes one Boolean value. True will set the window visible and false will set the window invisible. We must therefore call the setVisible on our object created and pass the value true to the method.

 

Hence the code below:

 

window.setVisible(true);

 

NOTE:

 

If you create the object in a class which is not in the same package as the window class, you will have to import the class to the class you are creating the object in.

 

After creating the object, you will see the red error alert if your window class is in a different package. Just click on the error alert and choose import to import the window class.

 

Before adding the components to the window, create a project and create the gui and main packages.

 

We want to develop the salary example we create for the previous week under the multi-dimensional array.

 

So we will design an interface for the login and another interface for the salary calculation.

In the gui package add a class LoginForm which will be the interface for our login.

 

Follow the above instructions to:

 

1. import the javax.swing.*;

2. extend the JFrame class

3. add the event handlings

4. create the constructor of the class

5. add a Main class in the main package and tick the public static void method when adding the Main class.

6. Create an object of the LoginForm class in the Main class and set the login window visible.

7. Run your project.

 

 

LoginForm class in the gui package

 

package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
 
import javax.swing.*;
public class LoginForm extends JFrame implements ActionListener,ItemListener,WindowListener{
      public LoginForm(String title, int width, int height){
            super(title);
            setSize(width,height);
      }
     
      @Override
      public void windowActivated(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowClosed(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowClosing(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowDeactivated(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowDeiconified(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowIconified(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void windowOpened(WindowEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void itemStateChanged(ItemEvent e) {
            // TODO Auto-generated method stub
           
      }
 
      @Override
      public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
           
      }
 
}

 

Main class in the main package

 

package main;

public class Main{
      //Set constant values
      public static void main(String[] args) {
            // TODOAuto-generated method stub
            LoginForm form = new LoginForm("Salary Calculator",400,300);
            form.setVisible(true);
      }
 
}

 

 

Result

 

 Image

 


ADDING COMPONENT TO THE WINDOW FRAME

 

JFrame Class Argument Description
JButton JButton(String button_text) For a button
JTextField JTextField(int field_columns) For a text input field
JPasswordField JPasswordField(int field_columns) For a password input field
JLabel JLabel(String label_text) Writing text on the window

 

There are more of the JFrame component classes but we will familiarize ourselves with these ones at the moment.

 

You have to create object of the above classes and then add them to the Window frame.

 

Examples

 

JLabel usernameLabel = new JLabel(“Username”);

JTextField usernameTxt = new JTextField(20);

JLabel passwordLabel = new JLabel(“Password”);

JPasswordField passwordTxt = new JPasswordField(20);

JButton loginBtn = new JButton(“Login”);

 

The add method is used to add a component to the frame.

 

In your constructor of your LoginForm class, create the above objects and add them to the window component using the add method.Thus:

 

add(usernameLabel);

add(usernameTxt);

add(passwordLabel);

add(passwordTxt);

add(loginBtn);

 

Run your project.

 

Output:

 

 Image

 

 

What was your observation?

 

You could see that only the last component added is placed on the window. The last component override the other components.

 

You could also see that the component takes the entire screen.

 

The main component(Root pane) of the window can therefore take only one component.

 

To resolve this we will need another component call the JPanel which we can create one and add to the root pane and then add the other components to our JPanel object. You can place other panels in the JPanel object which is added to the main window. You can see the JPanel like a window or door frame where the actual door or window will be fixed to.

 

To create a JPanel object, the syntax below is used:

 

JPanel panelName = new JPanel();

 

e.g

 

JPanel mainPanel = new JPanel();

 

Let’s create our JPanel in the LoginForm class and add our components to the JPanel object.

 

To add a component to a panel, you simply write the panel object and call the add method on the object and pass the component to add to that panel.

 

Thus to add our above component objects to our mainPanel object, we write the syntax below:

 

mainPanel.add(usernameTxt);

mainPanel.add(passwordLabel);

mainPanel.add(passwordTxt);

mainPanel.add(loginBtn);

 

After adding your component to the main panel, you then add the main panel to the Window using the add method.

 

Thus:

 

add(mainPanel);

 

Let’s modify the LoginForm class and run again.

 

LoginForm classs

 

package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.*;


public class LoginForm extends JFrame  implements ActionListener,ItemListener,WindowListener{


      public LoginForm(String title, int width, int height){

            super(title);

            setSize(width,height);

            JLabel usernameLabel = new JLabel("Username");
            JTextField usernameTxt = new JTextField(20);
            JLabel passwordLabel = new JLabel("Password");
            JPasswordField passwordTxt = new JPasswordField(20);
            JButton loginBtn = new JButton("Login");


            JPanel mainPanel = new JPanel();
            mainPanel.add(usernameLabel);
            mainPanel.add(usernameTxt);
            mainPanel.add(passwordLabel);
            mainPanel.add(passwordTxt);
            mainPanel.add(loginBtn); 
            add(mainPanel);

      }

      @Override
      public void windowActivated(WindowEvent e) {
            // TODO Auto-generated method stub
      }

      @Override

      public void windowClosed(WindowEvent e) {
            // TODO Auto-generated method stub
      }

      @Override

      public void windowClosing(WindowEvent e) {
            // TODO Auto-generated method stub
      }

      @Override


      public void windowDeactivated(WindowEvent e) {
            // TODO Auto-generated method stub
      }


      @Override


      public void windowDeiconified(WindowEvent e) {
            // TODO Auto-generated method stub
      }
      @Override

      public void windowIconified(WindowEvent e) {

            // TODO Auto-generated method stub

      }

      @Override

      public void windowOpened(WindowEvent e) {
            // TODO Auto-generated method stub

      }

      @Override
      public void itemStateChanged(ItemEvent e) {
            // TODO Auto-generated method stub
      }

      @Override
      public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub

      }

}


Image



As you can see, all our components are now on the Window but the interface doesn’t look nice.

 

By default, components are position in rows from left to right across their container. The default layout type for panels is the FlowLayout which positions the components in rows from left to right across their container.

 

There are other layouts that are used to position the controls in the panels.

 

The table below shows the types of Layouts and when to use them.

 

Layout When to use
BorderLayout Use when you add components to a maximum of five sections arranged in north, south, east, west, and center positions
GridLayout Use when you need to add components into a grid of rows and columns; each component is the same size  
CardLayout Use when you need to add components that are displayed one at a time
BoxLayout Use when you need to add components into a single row or a single column
GridBagLayout Use when you need to set size, placement, and alignment constraints for every component that you add

 

USING THE GRIDLAYOUT

 

The gridlayout layout manager has two arguments, the number of rows and number of columns.

 

In order to position each of the controls horizontally, you can set the column to 1. The number of rows will therefore be the total number of horizontal rows to have in the window. For example designing the LoginForm below:


Image



You can see that, the number of horizontals for the controls are 5, thus the horizontal row for the username label, password field,password label, password field and the login button.

 

Our GridLayout will therefore have 5 rows and 1 column.

 

We can therefore set the layout of our mainPanel panel to GridLayout by calling the setLayout method and passing the object of a GridLayout to it. Thus after creating the mainPanel object, we can add the code:

 

mainPanel.setLayout(new GridLayout(5,1));

 

The LoginForm class will then be:


package gui;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.*;


public class LoginForm extends JFrame implements ActionListener,ItemListener,WindowListener{
      public LoginForm(String title, int width, int height){
            super(title);
            setSize(width,height);
            JLabel usernameLabel = new JLabel("Username");
            JTextField usernameTxt = new JTextField(20);
            JLabel passwordLabel = new JLabel("Password");
            JPasswordField passwordTxt = new JPasswordField(20);
            JButton loginBtn = new JButton("Login");
            JPanel mainPanel = new JPanel();

            mainPanel.setLayout(new GridLayout(5,1));
            mainPanel.add(usernameLabel);
            mainPanel.add(usernameTxt);
            mainPanel.add(passwordLabel);
            mainPanel.add(passwordTxt);
            mainPanel.add(loginBtn);
            add(mainPanel);
      }
      @Override
      public void windowActivated(WindowEvent e) {
            // TODO Auto-generated method stub
      }
      @Override
      public void windowClosed(WindowEvent e) {
            // TODO Auto-generated method stub
      }
      @Override
      public void windowClosing(WindowEvent e) {
            // TODO Auto-generated method stub
      }
      @Override
      public void windowDeactivated(WindowEvent e) {
            // TODO Auto-generated method stub
      }
      @Override
      public void windowDeiconified(WindowEvent e) {
            // TODO Auto-generated method stub
      }
      @Override
      public void windowIconified(WindowEvent e) {
            // TODO Auto-generated method stub
      }
      @Override
      public void windowOpened(WindowEvent e) {
            // TODO Auto-generated method stub
      }
      @Override


      public void itemStateChanged(ItemEvent e) {
            // TODO Auto-generated method stub
      }

      @Override
      public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
      }

}


Run your project after the modification. You can see that the controls were arranged horizontally but they took the entire width of the panel.


Image



To resolve this, we must create panels for each horizontal row which we will add the controls to the panels and then the panels to our mainPanel object in the order they appear on the form horizontally.

 

Thus we create a panel for the username label,username input, password label, password input, and the login button. We add each of the controls to their panels and then add the panels to our mainPanel object.

 

Our LoginForm class will then be:


package gui;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.*;


public class LoginForm extends JFrame implements ActionListener,ItemListener,WindowListener{
      public LoginForm(String title, int width, int height){
            super(title);
            setSize(width,height);
            JLabel usernameLabel = new JLabel("Username");
            JTextField usernameTxt = new JTextField(20);
            JLabel passwordLabel = new JLabel("Password");
            JPasswordField passwordTxt = new JPasswordField(20);
            JButton loginBtn = new JButton("Login");
            JPanel mainPanel = new JPanel();
            mainPanel.setLayout(new GridLayout(5,1));
            //Create a panel for row 1 horizontal control(s)
            JPanel p_1 = new JPanel();
            // Add the control(s) to the panel
            p_1.add(usernameLabel);
            // Add the panel to the mainPanel
            mainPanel.add(p_1);
            //Create a panel for row 2 horizontal control(s)
            JPanel p_2 = new JPanel();
            //Add the control(s) to the panel
            p_2.add(usernameTxt);
            //Add the panel to the main Panel
            mainPanel.add(p_2);
            //Create a panel for row 3 horizontal control(s)
            JPanel p_3 = new JPanel();
            //Add the control(s) to the panel
            p_3.add(passwordLabel);       
            //Add the panel to the main Panel
            mainPanel.add(p_3);
            //Create a panel for row 4 horizontal control(s)
            JPanel p_4 = new JPanel();
            //Add the control(s) to the panel
            p_4.add(passwordTxt);         
            //Add the panel to the main Panel
            mainPanel.add(p_4);
            //Create a panel for row 4 horizontal control(s)
            JPanel p_5 = new JPanel();
            //Add the control(s) to the panel
            p_5.add(loginBtn);            
            //Add the panel to the main Panel
            mainPanel.add(p_5);
            add(mainPanel);
      }
      @Override
      public void windowActivated(WindowEvent e) {
            // TODO Auto-generated method stub
      }
      @Override
      public void windowClosed(WindowEvent e) {
            // TODO Auto-generated method stub

      }
      @Override
      public void windowClosing(WindowEvent e) {
            // TODO Auto-generated method stub
      }
      @Override
      public void windowDeactivated(WindowEvent e) {
            // TODO Auto-generated method stub
      }
      @Override
      public void windowDeiconified(WindowEvent e) {
            // TODO Auto-generated method stub
      }
      @Override
      public void windowIconified(WindowEvent e) {
            // TODO Auto-generated method stub
      }

      @Override
      public void windowOpened(WindowEvent e) {
            // TODO Auto-generated method stub
      }
      @Override
      public void itemStateChanged(ItemEvent e) {
            // TODO Auto-generated method stub
      }
      @Override
      public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
      }
}


You can do the modification and run your project.


Image


As you can see, the controls are centered on the panels.

 

The FlowLayout

 

FlowLayout manager class arranges components in rows across the width of a Container. With FlowLayout, each Component that you add is placed to the right of previously added components in a row; or, if the current row is filled, the Component is placed to start a new row.

 

When you use BorderLayout, the Components you add fill their regions—that is, each Component expands or contracts based on its region’s size. However, when you use FlowLayout, each Component retains its default size, or preferred size. For example, a JButton’s preferred size is the size that is large enough to hold the JButton’s text. When you use BorderLayout and then resize the window, the components change size accordingly because their regions change.

 

When you use FlowLayout and then resize the window, each component retains its size,but it might become partially obscured or change position.

 

The FlowLayout class contains three constants you can use to align Components with a Container:


  • FlowLayout.LEFT
  • FlowLayout.CENTER
  • FlowLayout.RIGHT

 

If you do not specify alignment, Components are center-aligned in a FlowLayout Container by default.

 

By default panels have FlowLayout as Layout which are center-aligned. In order to align the components of the panel to either left or right, you have to create a FlowLayout object and set the alignment to left or right in the FlowLayout argument. Then set the layout of the panel to the FlowLayout object.

 

In our LoginForm case, we want the components in the panels to be left aligned,hence we create a FlowLayout object and set the alignment to left and set each of the panels the controls are placed on to the FlowLayout object.

 

Thus the code modification below:

 

FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
 
//Set each of the panels to the flow object
p_1.setLayout(flow);
p_2.setLayout(flow);
p_3.setLayout(flow);
p_4.setLayout(flow);
p_5.setLayout(flow);

 

Modify the code and run your project again.


The LoginForm class code


package gui;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.*;

public class LoginForm extends JFrame  implements ActionListener,ItemListener,WindowListener{
	public LoginForm(String title, int width, int height){
		super(title);
		setSize(width,height);
		
		JLabel usernameLabel = new JLabel("Username");
		JTextField usernameTxt = new JTextField(20);
		JLabel passwordLabel = new JLabel("Password");
		JPasswordField passwordTxt = new JPasswordField(20);
		JButton loginBtn = new JButton("Login");
		
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new GridLayout(5,1));
		
		FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
		//Create a panel for row 1 horizontal control(s)
		JPanel p_1 = new JPanel();
		p_1.setLayout(flow);
		// Add the control(s) to the panel
		p_1.add(usernameLabel);
		
		// Add the panel to the mainPanel
		mainPanel.add(p_1);
		
		//Create a panel for row 2 horizontal control(s)
		JPanel p_2 = new JPanel();
		p_2.setLayout(flow);
		//Add the control(s) to the panel
		p_2.add(usernameTxt);
		//Add the panel to the main Panel
		mainPanel.add(p_2);
		
		
		//Create a panel for row 3 horizontal control(s)
		JPanel p_3 = new JPanel();
		p_3.setLayout(flow);
		//Add the control(s) to the panel
		p_3.add(passwordLabel);		
		//Add the panel to the main Panel
		mainPanel.add(p_3);
		
		//Create a panel for row 4 horizontal control(s)
		JPanel p_4 = new JPanel();
		p_4.setLayout(flow);
		//Add the control(s) to the panel
		p_4.add(passwordTxt);		
		//Add the panel to the main Panel
		mainPanel.add(p_4);
				
		//Create a panel for row 4 horizontal control(s)
		JPanel p_5 = new JPanel();
		p_5.setLayout(flow);
		//Add the control(s) to the panel
		p_5.add(loginBtn);		
		//Add the panel to the main Panel
		mainPanel.add(p_5);
		
		add(mainPanel);

	}
	
	@Override
	public void windowActivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosed(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosing(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeactivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeiconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowIconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowOpened(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		
	}

}

 

The Output


Image


We can adjust the input field columns to cover the entire width. Let’s change it from 20 to 33 and run and see the output.


Image


The LoginForm class


package gui;

import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.*;

public class LoginForm extends JFrame  implements ActionListener,ItemListener,WindowListener{
	public LoginForm(String title, int width, int height){
		super(title);
		setSize(width,height);
		
		JLabel usernameLabel = new JLabel("Username");
		JTextField usernameTxt = new JTextField(33);
		JLabel passwordLabel = new JLabel("Password");
		JPasswordField passwordTxt = new JPasswordField(33);
		JButton loginBtn = new JButton("Login");
		
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new GridLayout(5,1));
		
		FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
		//Create a panel for row 1 horizontal control(s)
		JPanel p_1 = new JPanel();
		p_1.setLayout(flow);
		// Add the control(s) to the panel
		p_1.add(usernameLabel);
		
		// Add the panel to the mainPanel
		mainPanel.add(p_1);
		
		//Create a panel for row 2 horizontal control(s)
		JPanel p_2 = new JPanel();
		p_2.setLayout(flow);
		//Add the control(s) to the panel
		p_2.add(usernameTxt);
		//Add the panel to the main Panel
		mainPanel.add(p_2);
		
		
		//Create a panel for row 3 horizontal control(s)
		JPanel p_3 = new JPanel();
		p_3.setLayout(flow);
		//Add the control(s) to the panel
		p_3.add(passwordLabel);		
		//Add the panel to the main Panel
		mainPanel.add(p_3);
		
		//Create a panel for row 4 horizontal control(s)
		JPanel p_4 = new JPanel();
		p_4.setLayout(flow);
		//Add the control(s) to the panel
		p_4.add(passwordTxt);		
		//Add the panel to the main Panel
		mainPanel.add(p_4);
				
		//Create a panel for row 4 horizontal control(s)
		JPanel p_5 = new JPanel();
		p_5.setLayout(flow);
		//Add the control(s) to the panel
		p_5.add(loginBtn);		
		//Add the panel to the main Panel
		mainPanel.add(p_5);
		
		add(mainPanel);

	}
	
	@Override
	public void windowActivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosed(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosing(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeactivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeiconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowIconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowOpened(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		
	}

}


IMPLEMENTINGTHE ACTION LISTENERS

 

You have to declare your controls (buttons, output labels and input fields) as global variables since we will be using them in the event handling methods.

 

Global variables are the variables declared above the class constructor.

 

We have to modify our LoginForm class and declare our usernameTxt, passwordTxt and the loginBtn as global variables.

 

We have to add an action listener to our button.

 

The method addActionListener is called on the button in order for an action to be handled any time the button is clicked.

 

The addActionListener will have the constructor this which refers to the action listener method implemented in our class.

 

For our button, the actionPerformed method is the one used to handle the button clicked. So we put our code to process the button clicked in that method.

 

Our loginBtn button class will therefore call the addActionListener method as:

 

loginBtn.addActionListener(this);

 

NOTE:

 

If you don’t add the above line of code to the button, even if you write your code in the actionPerformed method, nothing will happen when the button is clicked because you haven’t added an action listener to it yet.

 

In the actionPerformed method, the method has the ActionEvent in the argument. You have to determine the source of the event. The source will be the name of the object which has been clicked. We declared the names of those object as global so that we can access them in our actionPerformed method.

 

the getSource method is called on the ActionEvent class which returns the name of the object which has been clicked.

 

our actionPerformed method in the LoginForm class is:


@Override
public void actionPerformed(ActionEvent e) {
// TODOAuto-generated method stub
           
}

 

The variable name for the ActionEvent class is e.

 

To get the source of the click, we therefore call the getSource() method on that variable.

 

Thus e.getSource will return the object name which was clicked.

 

To check if the loginBtn button has been clicked, we write the code below:

 

if(e.getSource()==loginBtn){
    //We write to code to perform the task when the login button is clicked here
}

 

The getText() method is called on input fields to return the text entered by a user.

 

We can therefore access the username and password entered by the code below:

 

String username = usernameTxt.getText();
String password = passwordTxt.getText();

 

As we learnt in week 6, you can check if a String is empty or not using the isEmpty() method. We therefore check if the username is empty, then we tell the user to enter the username, then we check if the password is empty, then we tell the user to enter the password but if all fields filled, we authenticate the user.

 

The form validation code is shown below:

 

if(username.isEmpty()){
     //alert user to enter username
     JOptionPane.showMessageDialog(this,”Please enter your username”);
}elseif(password.isEmpty()){
     //alert user to enter password
     JOptionPane.showMessageDialog(this,”Please enter your password”);
}else{
     //implement the validation
}


Let’s now create a basic window for the Salary calculator to show when the user enters the correct login details.

 

Create another class by name SalaryCalculator in the gui package

 

1.import the javax.swing.*;

2.extend the JFrame class

3.add the event handlings

4.create the constructor of the class


SalaryCalculator class in the gui package


package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.*;

public class SalaryCalculator  extends JFrame  implements ActionListener,ItemListener,WindowListener{
	public SalaryCalculator(String title, int width, int height){
		super(title);
		setSize(width,height);
	}
	
	@Override
	public void windowActivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosed(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosing(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeactivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeiconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowIconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowOpened(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		
	}

}


Now let’s complete the login feature using the two-dimensional array concept in last week.

We now complete the actionPerformed method in the LoginForm

 

LoginForm class


package gui;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.*;

public class LoginForm extends JFrame  implements ActionListener,ItemListener,WindowListener{
	JTextField usernameTxt;
	JPasswordField passwordTxt;
	JButton loginBtn;
	public LoginForm(String title, int width, int height){
		super(title);
		setSize(width,height);
		
		JLabel usernameLabel = new JLabel("Username");
		usernameTxt = new JTextField(33);
		JLabel passwordLabel = new JLabel("Password");
		passwordTxt = new JPasswordField(33);
		loginBtn = new JButton("Login");
		
		loginBtn.addActionListener(this);
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new GridLayout(5,1));
		
		FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
		//Create a panel for row 1 horizontal control(s)
		JPanel p_1 = new JPanel();
		p_1.setLayout(flow);
		// Add the control(s) to the panel
		p_1.add(usernameLabel);
		
		// Add the panel to the mainPanel
		mainPanel.add(p_1);
		
		//Create a panel for row 2 horizontal control(s)
		JPanel p_2 = new JPanel();
		p_2.setLayout(flow);
		//Add the control(s) to the panel
		p_2.add(usernameTxt);
		//Add the panel to the main Panel
		mainPanel.add(p_2);
		
		
		//Create a panel for row 3 horizontal control(s)
		JPanel p_3 = new JPanel();
		p_3.setLayout(flow);
		//Add the control(s) to the panel
		p_3.add(passwordLabel);		
		//Add the panel to the main Panel
		mainPanel.add(p_3);
		
		//Create a panel for row 4 horizontal control(s)
		JPanel p_4 = new JPanel();
		p_4.setLayout(flow);
		//Add the control(s) to the panel
		p_4.add(passwordTxt);		
		//Add the panel to the main Panel
		mainPanel.add(p_4);
				
		//Create a panel for row 4 horizontal control(s)
		JPanel p_5 = new JPanel();
		p_5.setLayout(flow);
		//Add the control(s) to the panel
		p_5.add(loginBtn);		
		//Add the panel to the main Panel
		mainPanel.add(p_5);
		
		add(mainPanel);

	}
	
	@Override
	public void windowActivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosed(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosing(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeactivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeiconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowIconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowOpened(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
             if(e.getSource()==loginBtn){
		// TODO Auto-generated method stub
		String username = usernameTxt.getText();
		String password = passwordTxt.getText();
		if(username.isEmpty()){
			//alert user to enter username
			JOptionPane.showMessageDialog(this,"Please enter your username");
		}else if(password.isEmpty()){
			//alert user to enter password
			JOptionPane.showMessageDialog(this,"Please enter your password");
		}else{
			//implement the validation
			String[][] login_details = new String[3][2];
			login_details[0][0] = "pass";
			login_details[0][1] = "PASSWORD";
			login_details[1][0] = "admin";
			login_details[1][1] = "root";
			login_details[2][0] = "2019";
			login_details[2][1] = "12345";
			int grant_access = 0;
			for(int i=0;i<3;i++){
				if((login_details[i][0].equalsIgnoreCase(username))&&(login_details[i][1].equals(password))){
					//If the username and the password matches the user inputs, set grant_access to 1
					grant_access = 1;
				}
			}
			//Now check the value of grant_access to see if it has changed or still 0
			if(grant_access==1){
				//Show the salary calculator Window
				SalaryCalculator calculator = new SalaryCalculator("Salary Calculator",400,300);
				//Set the window visible
				calculator.setVisible(true);
				//Hide the login form
				this.setVisible(false);
			}else{
				JOptionPane.showMessageDialog(this, "Incorrect login details");
			}
		}
           }

	}

}


Now complete the salary calculator form.


Image


Figure: Salary Calculator form before fields are filled


Image


Figure: Salary Calculator form after fields filled and the CALCULATE button clicked


When the CLEAR button is clicked all the fields and the result must also be cleared.


The SalaryCalculator Class


package gui;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.*;
public class SalaryCalculator extends JFrame implements ActionListener, ItemListener,WindowListener{
    JTextField hrsTxt = new JTextField(33);	
    JTextField hrly_rateTxt = new JTextField(33);	
    JTextField tax_rateTxt = new JTextField(33);
    JButton btn = new JButton("CALCULATE");
    JButton clear_btn = new JButton("CLEAR");
    JLabel resultLabel = new JLabel("");
    public SalaryCalculator(String title, int width, int height) {
    	super(title);
    	setSize(width,height);
    	JPanel mainPanel = new JPanel();
    	JPanel p_1 = new JPanel();
    	JPanel p_2 = new JPanel();
    	JPanel p_3 = new JPanel();
    	JPanel p_4 = new JPanel();
    	JPanel p_5 = new JPanel();
    	JPanel p_6 = new JPanel();
    	JPanel p_7 = new JPanel();
    	JPanel p_8 = new JPanel();
    	
    	FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
    	 
    	//Set main panel to gridlayout so that each panel takes the entire row
    	mainPanel.setLayout(new GridLayout(8,1));
    	
    	//Align panels to the left
    	p_1.setLayout(flow);
    	p_2.setLayout(flow);
    	p_3.setLayout(flow);
    	p_4.setLayout(flow);
    	p_5.setLayout(flow);
    	p_6.setLayout(flow);
    	p_7.setLayout(flow);
    	p_8.setLayout(flow);
    	
    	JLabel hrs_label = new JLabel("Hours");
    	p_1.add(hrs_label);
    	p_2.add(hrsTxt);
    	
    	JLabel hr_rate_label = new JLabel("Hourly Rate");
    	p_3.add(hr_rate_label);
    	p_4.add(hrly_rateTxt);
    	
    	JLabel tax_rate_label = new JLabel("Tax Rate");
    	p_5.add(tax_rate_label);
    	p_6.add(tax_rateTxt);
    	
    	p_7.add(btn);
    	p_7.add(clear_btn);
    	
    	p_8.add(resultLabel);
    	
    	p_8.setLayout(flow);
    	
    	//Add action listener to buttons
    	btn.addActionListener(this);
    	clear_btn.addActionListener(this);
    	
    	/* Add each panel to the main panel */
    	mainPanel.add(p_1);
    	mainPanel.add(p_2);
    	mainPanel.add(p_3);
    	mainPanel.add(p_4);
    	mainPanel.add(p_5);
    	mainPanel.add(p_6);
    	mainPanel.add(p_7);
    	mainPanel.add(p_8);
    	/* Add main panel to window */
    	add(mainPanel);
    }
	@Override
	public void windowOpened(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosing(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosed(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowIconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeiconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowActivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeactivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource()==btn) {
			/* Get string from fields */
			String hrs_txt = hrsTxt.getText();
			String hrly_rate_txt = hrly_rateTxt.getText();
			String tax_rate_txt = tax_rateTxt.getText();
			if(hrs_txt.isEmpty()) {
				JOptionPane.showMessageDialog(this,"Please enter the hours worked");
			}else if(hrly_rate_txt.isEmpty()) {
				JOptionPane.showMessageDialog(this,"Please enter the hourly rate");
			}else if(tax_rate_txt.isEmpty()) {
				JOptionPane.showMessageDialog(this,"Please enter the tax rate");
			}else {
				//Convert the strings to double for calculations
				double hrs = Double.parseDouble(hrs_txt);
				double hrly_rate = Double.parseDouble(hrly_rate_txt);
				double tax_rate = Double.parseDouble(tax_rate_txt);
				double gross_salary = hrs*hrly_rate;
				double tax = gross_salary*tax_rate/100;
				double net_salary = gross_salary - tax;
				resultLabel.setText("Gross Salary: GHS "+gross_salary+"
Tax : GHS "+tax+"
Net Salary: GHS "+net_salary+""); } }else if(e.getSource()==clear_btn) { hrsTxt.setText(""); hrly_rateTxt.setText(""); tax_rateTxt.setText(""); resultLabel.setText(" "); } } @Override public void itemStateChanged(ItemEvent e) { // TODO Auto-generated method stub } }


Examples in the video tutorials


1. The Potential Energy Calculator


Image


Figure: Potential Energy Calculator form


Image


Figure: When fields filled and the Calculate button clicked


When the Clear button is clicked all the fields and the results must be cleared.


The Window class


package potential_energy_calculator;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.*;
public class Window extends JFrame implements ActionListener, ItemListener, WindowListener{
    JTextField massTxt = new JTextField(33);
    JTextField accTxt = new JTextField(33);
    JTextField heightTxt = new JTextField(33);
    JButton calBtn = new JButton("Calculate");
    JButton clearBtn = new JButton("Clear");
    JLabel resultLabel = new JLabel("");
	public Window(String title, int width, int height) {
    	super(title);
    	setSize(width,height);
    	JPanel mainPanel = new JPanel();
    	mainPanel.setLayout(new GridLayout(8,1));
    	FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
    	JPanel p_1 = new JPanel();
    	p_1.setLayout(flow);
    	JLabel massLb = new JLabel("Mass");
    	p_1.add(massLb);
    	mainPanel.add(p_1);
    	JPanel p_2 = new JPanel();
    	p_2.setLayout(flow);
    	p_2.add(massTxt);
    	mainPanel.add(p_2);
    	JPanel p_3 = new JPanel();
    	p_3.setLayout(flow);
    	JLabel accLb = new JLabel("Acceleration Due Gravity");
    	p_3.add(accLb);
    	mainPanel.add(p_3);
    	JPanel p_4 = new JPanel();
    	p_4.setLayout(flow);
    	p_4.add(accTxt);
    	mainPanel.add(p_4);
    	JPanel p_5 = new JPanel();
    	p_5.setLayout(flow);
    	JLabel heightLb = new JLabel("Height");
    	p_5.add(heightLb);    	
    	mainPanel.add(p_5);
    	JPanel p_6 = new JPanel();
    	p_6.setLayout(flow);
    	p_6.add(heightTxt);
    	mainPanel.add(p_6);
    	JPanel p_7 = new JPanel();
    	p_7.setLayout(flow);
    	p_7.add(calBtn);
    	calBtn.addActionListener(this);
    	p_7.add(clearBtn);
    	mainPanel.add(p_7);
    	JPanel p_8 = new JPanel();
    	p_8.setLayout(flow);
    	p_8.add(resultLabel);
    	mainPanel.add(p_8);
    	clearBtn.addActionListener(this);
    	add(mainPanel);
    }
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Window gui = new Window("Potential Energy Calculator",400,300);
        gui.setVisible(true);
	}

	@Override
	public void windowOpened(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosing(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosed(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowIconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeiconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowActivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeactivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource()==calBtn) {
			String sMass = massTxt.getText();
			String sAcc = accTxt.getText();
			String sHeight = heightTxt.getText();
			if(sMass.isEmpty()) {
				JOptionPane.showMessageDialog(this, "Please enter mass");
			}else if(sAcc.isEmpty()) {
				JOptionPane.showMessageDialog(this, "Please enter acceleration due to gravity");
			}else if(sHeight.isEmpty()) {
				JOptionPane.showMessageDialog(this, "Please enter height");
			}else {
				double mass = Double.parseDouble(sMass);
				double acc = Double.parseDouble(sAcc);
				double height = Double.parseDouble(sHeight);
				double pe = mass*acc*height;
				resultLabel.setText("Potential Energy: "+pe+"J");
			}
		}else if(e.getSource()==clearBtn) {
			massTxt.setText("");
			accTxt.setText("");
			heightTxt.setText("");
			resultLabel.setText("");
		}
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		// TODO Auto-generated method stub
		
	}

}


2. The Calculator


Image


Figure: The Calculator Form


Image


Figure: When the plus button is clicked.


When the clear button is clicked, all the fields and the result must be cleared.


The Calculator class


package calculator;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
public class Calculator extends JFrame implements ActionListener{
    JTextField num_1Txt = new JTextField(23);
    JTextField num_2Txt = new JTextField(23);
    JButton addBtn = new JButton("+");
    JButton subBtn = new JButton("-");
    JButton multBtn = new JButton("x");
    JButton clearBtn = new JButton("Clear");
    JButton divBtn = new JButton("/");
    JLabel resultLabel = new JLabel("");
	public Calculator(String title, int width, int height) {
    	super(title);
    	setSize(width,height);
    	//Create and add components
    	JPanel mainPanel = new JPanel();
    	mainPanel.setLayout(new GridLayout(6,1));
    	FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
    	JPanel p_1 = new JPanel();
    	p_1.setLayout(flow);
    	JLabel num_1Label = new JLabel("NUMBER 1");
    	p_1.add(num_1Label);
    	mainPanel.add(p_1);
    	JPanel p_2 = new JPanel();
    	p_2.setLayout(flow);
    	p_2.add(num_1Txt);
    	mainPanel.add(p_2);
    	JPanel p_3 = new JPanel();
    	p_3.setLayout(flow);
    	p_3.add(addBtn);
    	p_3.add(subBtn);
    	p_3.add(multBtn);
    	p_3.add(divBtn);
    	p_3.add(clearBtn);
    	addBtn.addActionListener(this);
    	subBtn.addActionListener(this);
    	multBtn.addActionListener(this);
    	divBtn.addActionListener(this);
    	clearBtn.addActionListener(this);
    	mainPanel.add(p_3);
    	JPanel p_4 = new JPanel();
    	p_4.setLayout(flow);
    	JLabel num_2Label = new JLabel("NUMBER 2");
    	p_4.add(num_2Label);
    	mainPanel.add(p_4);
    	JPanel p_5 = new JPanel();
    	p_5.setLayout(flow);
    	p_5.add(num_2Txt);
    	mainPanel.add(p_5);
    	JPanel p_6 = new JPanel();
    	p_6.setLayout(flow);
    	JLabel equalLabel = new JLabel("= ");
    	p_6.add(equalLabel);
    	p_6.add(resultLabel);
    	mainPanel.add(p_6);
    	add(mainPanel);
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Calculator cal = new Calculator("Calculator",300,300);
		cal.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource()==addBtn) {
			String sNum_1 = num_1Txt.getText();
			String sNum_2 = num_2Txt.getText();
			if(sNum_1.isEmpty()) {
				JOptionPane.showMessageDialog(this, "Please enter first number");
			}else if(sNum_2.isEmpty()) {
				JOptionPane.showMessageDialog(this, "Please enter second number");
			}else {
				double num_1 = Double.parseDouble(sNum_1);
				double num_2 = Double.parseDouble(sNum_2);
				double result = num_1+num_2;
				resultLabel.setText(""+result);
			}
		}else if(e.getSource()==subBtn) {
			String sNum_1 = num_1Txt.getText();
			String sNum_2 = num_2Txt.getText();
			if(sNum_1.isEmpty()) {
				JOptionPane.showMessageDialog(this, "Please enter first number");
			}else if(sNum_2.isEmpty()) {
				JOptionPane.showMessageDialog(this, "Please enter second number");
			}else {
				double num_1 = Double.parseDouble(sNum_1);
				double num_2 = Double.parseDouble(sNum_2);
				double result = num_1-num_2;
				resultLabel.setText(""+result);
			}
		}else if(e.getSource()==multBtn) {
			String sNum_1 = num_1Txt.getText();
			String sNum_2 = num_2Txt.getText();
			if(sNum_1.isEmpty()) {
				JOptionPane.showMessageDialog(this, "Please enter first number");
			}else if(sNum_2.isEmpty()) {
				JOptionPane.showMessageDialog(this, "Please enter second number");
			}else {
				double num_1 = Double.parseDouble(sNum_1);
				double num_2 = Double.parseDouble(sNum_2);
				double result = num_1*num_2;
				resultLabel.setText(""+result);
			}
		}else if(e.getSource()==divBtn) {
			String sNum_1 = num_1Txt.getText();
			String sNum_2 = num_2Txt.getText();
			if(sNum_1.isEmpty()) {
				JOptionPane.showMessageDialog(this, "Please enter first number");
			}else if(sNum_2.isEmpty()) {
				JOptionPane.showMessageDialog(this, "Please enter second number");
			}else {
				double num_1 = Double.parseDouble(sNum_1);
				double num_2 = Double.parseDouble(sNum_2);
				double result = num_1/num_2;
				resultLabel.setText(""+result);
			}
		}else if(e.getSource()==clearBtn) {
			num_1Txt.setText("");
			num_2Txt.setText("");
			resultLabel.setText("");
		}
	}

}


More example


The figure below is a force calculator. Design the graphical user interface and implement the action listeners for the calculate and clear button. When the calculate button is clicked, the force should be calculated and displayed on the form. If any of the forms is not filled, alert the user to enter the field which hasn't been filled yet.


Image


Figure: The graphical user interface


package forcecalculator;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.*;

public class ForceCalculator extends JFrame implements ActionListener, ItemListener, WindowListener{
     //Declare all global variables which would be used in the listener method(s)
	 JTextField massTxt = new JTextField(20);
     JTextField accTxt = new JTextField(20);
     JButton calBtn = new JButton("CALCULATE");
     JButton clearBtn = new JButton("CLEAR");
     JLabel resultLabel = new JLabel(" ");
	
	 public ForceCalculator(String title,int width, int height) {
		 super(title);
		 setSize(width,height);
		 //Create the main panel object
		 JPanel p_main = new JPanel();
		 /* Align controls to the left */
		 FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
		 /* Create Panels and add their controls to them */
		 JLabel massLabel = new JLabel("Mass");
		 JPanel p_1 = new JPanel();
		 p_1.setLayout(flow);
		 p_1.add(massLabel);
		 JPanel p_2 = new JPanel();
		 p_2.setLayout(flow);
		 p_2.add(massTxt);
		 JLabel accLabel = new JLabel("Acceleration Due To Gravity");
		 JPanel p_3 = new JPanel();
		 p_3.setLayout(flow);
		 p_3.add(accLabel);
		 JPanel p_4 = new JPanel();
		 p_4.setLayout(flow);
		 p_4.add(accTxt);
		 //Add action listeners
		 calBtn.addActionListener(this);
		 clearBtn.addActionListener(this);
		 JPanel p_5 = new JPanel();
		 p_5.setLayout(flow);
		 p_5.add(calBtn);
		 p_5.add(clearBtn);
		 JPanel p_6 = new JPanel();
		 p_6.setLayout(flow);
		 p_6.add(resultLabel);
		 /* Set GridLayout of main panel. 6 rows and 1 column */
		 p_main.setLayout(new GridLayout(6,1));
		 /* Add all panels to the main panel */
		 p_main.add(p_1);
		 p_main.add(p_2);
		 p_main.add(p_3);
		 p_main.add(p_4);
		 p_main.add(p_5);
		 p_main.add(p_6);
		 add(p_main);
	
	 }
     public static void main(String[] args) {
		// TODO Auto-generated method stub
    	 ForceCalculator cal = new ForceCalculator("Force Calculator",250,300);
    	 cal.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource()==calBtn) {
			String sMass = massTxt.getText();
			String sAcc = accTxt.getText();
			/* Check if fields has been field */
			if(sMass.isEmpty()) {
				JOptionPane.showMessageDialog(this,"Please enter the mass of the body");
			}else if(sAcc.isEmpty()) {
				JOptionPane.showMessageDialog(this,"Please enter the acceleration due to gravity of the body");
			}else {
				//Calculate and show the result in the result label
				double mass = Double.parseDouble(sMass);
				double acc = Double.parseDouble(sAcc);
				double force = mass*acc;
				resultLabel.setText("Force:"+force);
			}
		}else if(e.getSource()==clearBtn) {
			massTxt.setText("");
			accTxt.setText("");
			resultLabel.setText("");
		}
	}

	@Override
	public void windowOpened(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosing(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosed(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowIconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeiconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowActivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeactivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		// TODO Auto-generated method stub
		
	}

}

SponsoredAdvertise