info@tutsfinder.in



Java Swing

Swing is used to create windows based applications. Swing is a GUI(Graphical User Interface) toolkit for java.

Swings components are not platfotm-specefic, they are written purely in java that’s why they are platform independent.

Swing enables customization in look and feel of components in an application without making changes in the code. Also it supports pluggable look and feel.

Swing components are loosely coupled because they makes use of MVC(Model/View/Controller) architecture.

Model - It is responsible to store and manipulate data.

View - It is responsible to represent data that model contains.

Controller - It acts as bridge between Model and view.


MVC Architecture



Program to show you how swing components works:

import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField; 
import javax.swing.JPasswordField;
import javax.swing.JButton;

public class SwingExample {
    
    public static void main(String[] args) {    
       
        JFrame frame = new JFrame("Login Form");
        
        frame.setSize(500, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();    
        
        frame.add(panel);
        
        placeComponents(panel);

        
        frame.setVisible(true);
    }

    private static void placeComponents(JPanel panel) {

        
        panel.setLayout(null);

        
        JLabel userNameLabel = new JLabel("User Name");
        
        userNameLabel.setBounds(20,30,90,30);
        panel.add(userNameLabel);

        
        JTextField userText = new JTextField(20);
        userText.setBounds(200,30,200,30);
        panel.add(userText);

        JLabel passwordLabel = new JLabel("Password");
        passwordLabel.setBounds(20,80,100,30);
        panel.add(passwordLabel);

        JPasswordField passwordText = new JPasswordField(20);
        passwordText.setBounds(200,80,200,30);
        panel.add(passwordText);

        JButton loginButton = new JButton("login");
        loginButton.setBounds(235, 150, 80, 30);
        panel.add(loginButton);
    }

}


Output: