Java Swing Login Screen - Full Explanation
1. Imports
import [Link].*;
import [Link].*;
import [Link].*;
- [Link].*: Imports everything from the Swing library (buttons, labels, frames, etc.)
- [Link].*: For layout managers and graphical elements
- [Link].*: Lets you listen and respond to user actions (e.g., button clicks)
2. Class Declaration
public class LoginScreen extends JFrame implements ActionListener {
- LoginScreen: The class name; you can rename it as needed.
- extends JFrame: Inherits from JFrame, which is the top-level window in Swing.
- implements ActionListener: This means the class can respond to button clicks.
3. Declare Fields
private JTextField txtUsername;
private JPasswordField txtPassword;
private JButton btnLogin, btnExit;
Declared outside any method so they can be accessed throughout the class.
4. Constructor - public LoginScreen()
This sets up the whole GUI when the class is instantiated.
- setTitle: Sets the window title.
- setSize: Sets width and height.
- setLocationRelativeTo(null): Centers the window on the screen.
- setDefaultCloseOperation: Clicking "X" closes the app.
- setLayout: Uses BorderLayout for structured placement.
5. Title Label (Top Section)
JLabel lblTitle = new JLabel("Login", [Link]);
[Link](new Font("Arial", [Link], 24));
add(lblTitle, [Link]);
Displays the title at the top of the frame.
Java Swing Login Screen - Full Explanation
6. Form Panel (Middle Section)
Uses GridLayout for structured form entry.
Includes fields for Username and Password.
Validation or retrieval is done later in button events.
7. Button Panel (Bottom Section)
Creates Login and Exit buttons, assigns action listeners, and places them at the bottom.
8. Action Listener
Handles what happens when Login or Exit is clicked.
Validates credentials, shows success or error, and proceeds accordingly.
9. Main Method
public static void main(String[] args) {
[Link](() -> {
new LoginScreen().setVisible(true);
});
}
Starts the GUI application using the Event Dispatch Thread.
10. Summary
Students learn:
- Java Swing basics
- Event-driven programming
- GUI design and structure
- User input handling
- Program control and flow