Search code examples
javabuttonjtextfieldgrid-layout

Problems aligning text field input using GridLayout


I want to make a form using java frame. I have two fields Name and Age. After entering the details, when the button is clicked, the entered data must be displayed as shown below, but I am not sure how to align it.

The entered data are:
     FirstName: abcd
     LastName: efg

This is what I have so far:

import java.awt.*;
import java.awt.event.*;

public class DataEntry {
  public static void main(String[] args) {
         Frame frm=new Frame("DataEntry frame");
         Label lbl = new Label("Please fill this blank:");
         frm.add(lbl);
         frm.setSize(350,200);
         frm.setVisible(true);
         frm.addWindowListener(new WindowAdapter(){
             public void windowClosing(WindowEvent e){
                     System.exit(0);
         }
        });

       Panel p = new Panel();
       Panel p1 = new Panel();
       Label jFirstName = new Label("First Name");
       TextField lFirstName = new TextField(20);
       Label jLastName =new Label("Last Name");
       TextField lLastName=new TextField(20);
       p.setLayout(new GridLayout(3,1));
       p.add(jFirstName);
       p.add(lFirstName);
       p.add(jLastName);
       p.add(lLastName);
       Button Submit=new Button("Submit");
       p.add(Submit);
       p1.add(p);
       frm.add(p1,BorderLayout.NORTH);
  }
} 

Solution

  • Firstly, you need to add an event to the button, when it is clicked.

    submit.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e)
             {
                 // Add the code to output the relevant details. 
             }
        }
    

    Then it's up to you to add the relevant code to the method body. You should read the Documentation