Java GUI Programming: A Comprehensive Guide

Java GUI Programming

Displaying Two-Dimensional Objects in Java

import javax.swing.*;
import java.awt.*;

public class DrawingPanel extends JPanel {
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.RED);
        g.drawRect(50, 50, 100, 100);
        g.setColor(Color.BLUE);
        g.fillOval(200, 50, 100, 100); 
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("2D Drawing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.add(new DrawingPanel());
        frame.setVisible(true);
    }
}

Containers and Panels

  1. JPanel: A generic container for grouping other components.
  2. JScrollPane: Provides a scrollable view of another component.
  3. JSplitPane: Divides two components and allows the user to resize them dynamically.
  4. JTabbedPane: A container that allows multiple components to be displayed in tabbed pages.
  5. JLayeredPane: Provides a container that can be used to place components in layers, stacking them.
  6. JDesktopPane: Provides a container for JInternalFrame objects (used for creating Multiple Document Interface (MDI) applications).
  7. JInternalFrame: A frame that can be contained within a JDesktopPane.

Java’s Event Handling Model

Java’s event handling model is based on the delegation event model with four main components:

  1. Event Source: The object (e.g., button, text field) that generates the event.
  2. Event Object: An instance that carries event details (e.g., ActionEvent, MouseEvent).
  3. Event Listener: An interface with methods to handle specific events (e.g., ActionListener, MouseListener).
  4. Event Handler: The method that defines what happens when the event occurs (e.g., actionPerformed).

Handling a Button Click Event

import javax.swing.*;
import java.awt.event.*;

public class ButtonClickExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Event Handling Example");
        JButton button = new JButton("Click Me");

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Button clicked!");
            }
        });

        frame.add(button);
        frame.setSize(200, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Adapter Class

Adapter classes are special classes that provide default, empty implementations for all methods of a listener interface. They allow you to override only the methods you need, avoiding the implementation of unused methods. Example:

import java.awt.event.*;
import javax.swing.*;

public class WithAdapterExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Mouse Event Example");
        JButton button = new JButton("Click Me");

        button.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                System.out.println("Mouse clicked!");
            }
        });

        frame.add(button);
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

With the MouseAdapter, you only need to override the mouseClicked method, simplifying the code. This reduces unnecessary boilerplate, making the program cleaner and more maintainable.

MVC (Model-View-Controller)

MVC (Model-View-Controller) is a design pattern that separates an application into three components:

  • Model: Represents the data and business logic.
  • View: The user interface (UI) that displays the data.
  • Controller: Handles user input and updates the model and view.

Example:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class CounterModel {
    private int count = 0;

    public int getCount() {
        return count;
    }

    public void increment() {
        count++;
    }
}

public class MVCDemo extends JFrame {
    private CounterModel model = new CounterModel();
    private JLabel label = new JLabel("0");
    private JButton button = new JButton("Increment");

    public MVCDemo() {
        setLayout(new FlowLayout());
        add(label);
        add(button);

        button.addActionListener(e -> {
            model.increment();
            label.setText(String.valueOf(model.getCount()));
        });

        setSize(200, 100);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new MVCDemo();
    }
}

Executing SQL Statements Using JDBC

To execute SQL statements using JDBC (Java Database Connectivity), follow these steps:

  1. Load JDBC Driver (Optional for newer JDBC versions)
  2. Establish a connection to the database using DriverManager.
  3. Create a statement using Connection.
  4. Execute the SQL query (e.g., SELECT, INSERT, UPDATE).
  5. Process the result (for queries that return results).
  6. Close the resources (statement, connection).

ResultSet vs. RowSet in JDBC

FeatureResultSetRowSet
ConnectionConnectedDisconnected
MutabilityRead-onlyScrollable and updatable by default
WeightHeavyweightLightweight
XML SupportNoYes

PreparedStatement

A PreparedStatement is a precompiled SQL statement used to execute dynamic queries with parameters. It helps prevent SQL injection and improves performance by pre-compiling the query. Example:

import java.sql.*;

public class PreparedStatementExample {
    public static void main(String[] args) {
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");
            String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "john_doe");
            pstmt.setString(2, "password123");
            int rowsInserted = pstmt.executeUpdate();
            System.out.println(rowsInserted + " row(s) inserted.");
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Accessing Data in a ResultSet

import java.sql.*;

public class ResultSetExample {
    public static void main(String[] args) {
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT id, username, email FROM users");

            while (rs.next()) {
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String email = rs.getString("email");
                System.out.println("ID: " + id + ", Username: " + username + ", Email: " + email);
            }

            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Connecting to a Database and Displaying Data in a JTable

import javax.swing.*;
import java.awt.*;
import java.sql.*;
import javax.swing.table.DefaultTableModel;

public class JTableExample {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Student/Employee Details");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(600, 400);

            DefaultTableModel model = new DefaultTableModel();
            JTable table = new JTable(model);

            model.addColumn("ID");
            model.addColumn("Name");
            model.addColumn("Email");

            try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");
                 Statement stmt = conn.createStatement();
                 ResultSet rs = stmt.executeQuery("SELECT id, name, email FROM students")) {

                while (rs.next()) {
                    Object[] row = {
                            rs.getInt("id"),
                            rs.getString("name"),
                            rs.getString("email")
                    };
                    model.addRow(row);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            JScrollPane scrollPane = new JScrollPane(table);
            frame.add(scrollPane, BorderLayout.CENTER);
            frame.setVisible(true);
        });
    }
}

JDBC Updatable ResultSet Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Jdbc_Updatable_ResultSet {
    public static void main(String[] args) throws Exception {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/onlinetutorialspoint", "root", "123456");
        Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        ResultSet rs = st.executeQuery("select * from person");

        rs.next();
        rs.updateInt(1, 1001);
        rs.updateRow();
        System.out.println("1 ROW UPDATED...");

        rs.moveToInsertRow();
        rs.updateInt(1, 1002);
        rs.updateString(2, "Banglore");
        rs.updateString(3, "Vinayak");
        rs.insertRow();
        System.out.println("1 ROW INSERTED...");

        System.out.println("After Updation...");

        con.close();
    }
}

Program: Insert and Display Data Using JDBC

import java.sql.*;
import java.util.Scanner;

public class JDBCExample {
    private static final String URL = "jdbc:mysql://localhost:3306/mydb";
    private static final String USER = "root";
    private static final String PASSWORD = "password";

    public static void main(String[] args) {
        try {
            Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
            Statement stmt = conn.createStatement();

            insertData(conn);
            displayData(stmt);

            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void insertData(Connection conn) {
        String insertSQL = "INSERT INTO students (id, name, email) VALUES (?, ?, ?)";

        try (PreparedStatement pstmt = conn.prepareStatement(insertSQL);
             Scanner scanner = new Scanner(System.in)) {

            System.out.println("Enter student ID:");
            int id = scanner.nextInt();
            scanner.nextLine(); // Consume newline

            System.out.println("Enter student name:");
            String name = scanner.nextLine();

            System.out.println("Enter student email:");
            String email = scanner.nextLine();

            pstmt.setInt(1, id);
            pstmt.setString(2, name);
            pstmt.setString(3, email);

            int rowsInserted = pstmt.executeUpdate();
            System.out.println(rowsInserted + " row(s) inserted.");

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void displayData(Statement stmt) {
        String querySQL = "SELECT id, name, email FROM students";

        try (ResultSet rs = stmt.executeQuery(querySQL)) {
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String email = rs.getString("email");
                System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}