FahmidasClassroom

Learn by easy steps

P1

The way of creating form with a button by using Java swing control has been shown in this tutorial to start designing form using Java. Follow the steps properly to create the java application.

Steps:

01. Create a Java application with the class named JavaForm.java.

02. Add the following lines before the class declaration to import necessary packages for the application

import java.awt.event.*;
import javax.swing.*;

03. Add the following lines to the main method to create a Form with a button by using JFrame and JButton.

//Create a JFrame Object
JFrame frm = new JFrame();
//Create button
JButton btn = new JButton("Close");
//Set button position
btn.setBounds(150,40,80,30);
//Add button to frame
frm.add(btn);

04. Add the following lines to set the form size and layout, and display the form in the center of the screen.

  //Set the size of the form
  frm.setSize(400, 150);  
      
  frm.setLayout(null);
  //Set the title of the form
  frm.setTitle("Welecome to fahmidasclassroom");
  //set form in the center of the screen
  frm.setLocationRelativeTo(null);      
      
  //Display the form 
  frm.setVisible(true);

05. Add the following lines to add event handler code for the button that will close the application.

btn.addActionListener((ActionEvent e) -> {
    System.exit(0);
});

06. Now, you can run the application.

You can check the video to do the steps properly shown in this tutorial.