Table of contents
This is a Java program that creates a simple login form. I am using here several components like JLabel, JTextfield, and Buttons. I am also using ActionListener here.
The Program creates a Login class that extends the JFrame class and sets the frame's size, layout, and visibility of the frame. Here you can also set the background color, and define Font type and size for JLabel, JTextField, and Buttons.
The Login class contains several instance variables for every component that will be added to the frame. these variables set their position size and font using the setBounds() and setFont().
Finally, The Login class adds the component to the frame using the add() method and sets the event LIsteners for the buttons using the addActionListener() method.
When we implement ActionListener(), we have to import awt event package.
After that, we have to call the Constructor of ActionListener() i.e actionPerformed.
In which we will handle all the button events.
The Package that will be used here...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
Source Code
package swing_awt;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Login extends JFrame implements ActionListener {
JButton submit, reset, close;
JTextField tfusername;
JPasswordField tfpassword;
public Login(){
getContentPane().setBackground(Color.WHITE);
setLayout(null);
JLabel lblusername = new JLabel("Username");
lblusername.setBounds(20, 20, 100, 20);
lblusername.setForeground(Color.BLACK);
lblusername.setFont(new Font("Tahoma", Font.PLAIN, 15));
add(lblusername);
tfusername = new JTextField();
tfusername.setBounds(130, 20, 200, 20);
add(tfusername);
JLabel lblpassword = new JLabel("Password");
lblpassword.setBounds(20, 60, 100, 20);
lblpassword.setForeground(Color.BLACK);
lblpassword.setFont(new Font("Tahoma", Font.PLAIN, 15));
add(lblpassword);
tfpassword = new JPasswordField();
tfpassword.setBounds(130, 60, 200, 20);
add(tfpassword);
reset = new JButton("Reset");
reset.setBounds(40, 120, 120, 20);
reset.addActionListener(this);
add(reset);
submit = new JButton("Submit");
submit.setBounds(190, 120, 120, 20);
submit.addActionListener(this);
add(submit);
close = new JButton("Close");
close.setBounds(120, 160, 120, 20);
close.addActionListener(this);
add(close);
setSize(400,250);
setLocation(500,250);
setVisible(true);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == close){
setVisible(false);
}else{
tfusername.setText("");
tfpassword.setText("");
}
}
}
public static void main(String[] args) {
new Login();
}
}