Site icon FahmidasClassroom

Use of Java JFrame with a label, textbox and two buttons

P2

The way of creating form with a label, textbox, and button by using Java swing control has been shown in this tutorial. 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 javax.swing.*;
import java.awt.event.*;

03. Add the following lines inside the main method to create a Form with two buttons by using JFrame, Label, TextField and Button.

//Create a JFrame Object
JFrame frm = new JFrame();
     
JLabel lbl = new JLabel("Name:", JLabel.LEFT);
lbl.setBounds(80,20,60,20);
//Add label to frame
frm.add(lbl);
      
//Create a textfield object
JTextField txt = new JTextField();

//Set the position of the textfield
txt.setBounds(120,20,110,20);
//Aadd the textfield into the form
frm.add(txt);
       
//Create Submit button
JButton btn1 = new JButton("Submit");
//Set button position
btn1.setBounds(50,60,80,20);
//Add button to frame
frm.add(btn1);

//Create Exit button
JButton btn2 = new JButton("Exit");
//Set button position
btn2.setBounds(150,60,80,20);
//Add button to frame
frm.add(btn2);

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(300, 150);  
//Set the layout  
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 Submit button that will read the value of the textfield.

btn1.addActionListener((ActionEvent e) -> {
    JOptionPane.showConfirmDialog(null, "Your name is "+txt.getText(), "Info", JOptionPane.DEFAULT_OPTION, 
    JOptionPane.INFORMATION_MESSAGE);
});

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

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

07. Now, you can run the application.

Exit mobile version