Skip to content
AL-406 · Java Lab/Quick Revision Short Notes

Java Lab (AL-406) - Unit 4 Short Notes

UNIT 4: ADVANCED APPLICATION DEVELOPMENT & INTEGRATION


4.1 Graphical User Interface (GUI) Programming with Swing

4.1.1 Introduction to AWT vs. Swing; Swing Component Hierarchy

  • AWT (Abstract Window Toolkit): Heavyweight components, platform-dependent, uses native peers.

  • Swing: Lightweight components, pure Java, pluggable look-and-feel, built on top of AWT.

  • Swing Component Hierarchy:

    • Top-level containers: JFrame, JDialog, JApplet.

    • Intermediate containers: JPanel, JScrollPane.

    • Basic controls: JButton, JLabel, JTextField, etc., inherit from JComponent.

    • JComponent is the root for all Swing components (except top-level containers).

[!TIP] Common Pitfall: Mixing AWT and Swing components in the same container can cause painting and event-handling issues. Prefer Swing-only (JButton not Button).

4.1.2 Core Swing Components

Component Purpose Key Methods
JLabel Display static text or image setText(), setIcon()
JTextField Single-line text input getText(), setText()
JButton Clickable button addActionListener()
JTextArea Multi-line text display/input Often used with JScrollPane
JComboBox Drop-down list getSelectedItem()
JCheckBox Multiple selection toggle isSelected()
JRadioButton Single selection from group Use with ButtonGroup

4.1.3 Layout Managers

Controls component positioning and sizing.

Layout Manager Arrangement Typical Use
FlowLayout Left-to-right, wraps Simple forms, toolbars
BorderLayout 5 regions (NORTH, SOUTH, EAST, WEST, CENTER) Main application windows
GridLayout Uniform grid (rows x cols) Calculators, keypads
GridBagLayout Flexible grid with cell constraints Complex forms (most powerful)

[!TIP] Exam Focus: Know which layout manager is appropriate for a given UI design. BorderLayout is the default for JFrame's content pane.

4.1.4 Event Handling

  • Event Source: Component (e.g., JButton).

  • Event Object: Carries event data (e.g., ActionEvent).

  • Listener Interface: Defines handler method (e.g., actionPerformed(ActionEvent e)).

  • Common Listeners:

    • ActionListener: Button clicks, menu selections, Enter in text field.

    • ItemListener: Checkbox/radio button state changes, combo box selections.

    • WindowListener: Window events (closing, activating).

  • Implementation Styles:

    1. Implement Listener Interface: Class implements ActionListener.

    2. Anonymous Inner Class: button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ... } });

    3. Lambda Expression (Java 8+): button.addActionListener(e -> { ... }); (Most concise).

[!TIP] Critical Rule: All Swing component updates must occur on the Event Dispatch Thread (EDT). Use SwingUtilities.invokeLater() for background thread updates.

4.1.5 Menus, Toolbars, and Dialogs

  • Menus: JMenuBar (container), JMenu (dropdown), JMenuItem (command). Add to JFrame.setJMenuBar().

  • Dialogs:

    • JOptionPane: Simple modal dialogs (message, confirm, input). Static methods like showMessageDialog().

    • JFileChooser: Standard file open/save dialog. showOpenDialog() returns APPROVE_OPTION or CANCEL_OPTION.

  • Toolbars: JToolBar holds JButton or other components, often with icons.

4.1.6 Practical Lab Focus

Build a functional form-based application (e.g., calculator, student registration form).

  • Key Steps: Choose appropriate layout manager, add components, register event listeners, implement business logic separate from UI.

  • Example Pattern (Calculator): GridLayout for buttons, BorderLayout for display and panel, ActionListener on all buttons to handle digit/operator input.


4.2 File I/O and Serialization

4.2.1 Streams, Readers, and Writers

  • Byte Streams (Binary Data): InputStream / OutputStream.

    • FileInputStream / FileOutputStream: Read/write raw bytes from/to file.
  • Character Streams (Text Data): Reader / Writer. Handle encoding automatically.

    • FileReader / FileWriter: Convenience classes for text files (use default encoding).
  • File Class: Represents file/directory path. Used to create, delete, check existence, list files. Not for reading/writing content.

4.2.2 Buffered Streams

Wrap raw streams to improve efficiency by reducing native I/O calls.

  • Buffered Byte Streams: BufferedInputStream, BufferedOutputStream.

  • Buffered Character Streams: BufferedReader, BufferedWriter.

    • BufferedReader provides readLine() for convenient line-by-line reading.

4.2.3 Character Encoding and PrintWriter/PrintStream

  • Encoding: Specify character set (e.g., UTF-8) when bridging bytes and characters to avoid platform dependency. Use InputStreamReader/OutputStreamWriter with charset name.

  • PrintWriter / PrintStream: Convenient for formatted text output. print()/println() methods. PrintWriter can auto-flush and is character-based.

4.2.4 Object Serialization

Process of converting an object's state into a byte stream for storage or transmission.

  • Requirement: Class must implement java.io.Serializable (marker interface).

  • Key Classes:

    • ObjectOutputStream: Writes objects to a stream (writeObject()).

    • ObjectInputStream: Reads objects from a stream (readObject()).

  • Transient Fields: Mark with transient keyword to exclude from serialization.

4.2.5 Practical Lab Focus

  • Text File Operations: Copy file using buffered streams. Read configuration file line-by-line.

  • Object Persistence: Save a List<Student> to students.dat using ObjectOutputStream. Load it back with ObjectInputStream.

  • Key Pattern:

    
    try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.obj"))) {
    
        oos.writeObject(myObject);
    
    } catch (IOException e) { e.printStackTrace(); }
    
    

[!TIP] Common Pitfall: FileNotFoundException is a checked exception; always handle or declare. Use try-with-resources (Java 7+) for automatic stream closing.


4.3 Multithreading and Concurrency

4.3.1 Creating Threads

  1. Extend Thread class: Override run(). new MyThread().start().

    • Limitation: Java doesn't support multiple inheritance.
  2. Implement Runnable interface: Pass Runnable to Thread constructor. new Thread(new MyRunnable()).start().

    • Preferred: Separates task (Runnable) from execution mechanism (Thread).

4.3.2 Thread Lifecycle and States

DiagramCANVAS: Thread lifecycle diagram showing NEW -> RUNNABLE -> (BLOCKED/WAITING/TIMED_WAITING) -> TERMINATED
  • NEW: Thread created, not started.

  • RUNNABLE: Executing or ready to execute (includes OS "running" state).

  • BLOCKED: Waiting for monitor lock (to enter synchronized block/method).

  • WAITING: Waiting indefinitely (Object.wait(), Thread.join()).

  • TIMED_WAITING: Waiting for specified time (Thread.sleep(), Object.wait(timeout)).

  • TERMINATED: Completed execution.

4.3.3 Synchronization

Prevents thread interference and memory consistency errors.

  • Synchronized Method: public synchronized void method() { ... } locks on this (instance) or ClassName.class (static).

  • Synchronized Block: More granular. synchronized(lockObject) { ... }. Locks on specified object.

  • volatile Keyword: Guarantees visibility of changes across threads (but not atomicity).

4.3.4 Inter-Thread Communication

Must be called from within a synchronized context on the same lock object.

  • wait(): Releases lock and suspends thread until notified.

  • notify(): Wakes up one waiting thread (arbitrary).

  • notifyAll(): Wakes up all waiting threads (preferred to avoid missed signals).

4.3.5 java.util.concurrent Package Overview

High-level concurrency utilities.

  • ExecutorService: Manages a pool of threads. Submit tasks (Runnable/Callable).

    
    ExecutorService pool = Executors.newFixedThreadPool(4);
    
    pool.submit(() -> System.out.println("Task"));
    
    pool.shutdown();
    
    
  • Future<V>: Represents result of an asynchronous computation. get() blocks until result ready.

  • Callable<V>: Like Runnable but returns a value and can throw checked exceptions.

4.3.6 Practical Lab Focus

  • Producer-Consumer Problem: Use synchronized blocks with wait()/notifyAll() on a shared buffer.

  • Banking Simulation: synchronized methods on Account for deposit()/withdraw() to prevent race conditions.

  • Thread Pool: Use ExecutorService to handle multiple client connections in a server.

[!TIP] Critical Concept: Deadlock occurs when two or more threads are blocked forever, each waiting for the other's lock. Avoid by acquiring locks in a consistent global order.


4.4 Networking with Sockets

4.4.1 Fundamentals of Client-Server Architecture

  • Server: Listens on a known port for incoming connection requests.

  • Client: Initiates connection to server's IP and port.

  • Socket: Endpoint for communication between two machines.

4.4.2 Socket and ServerSocket Classes

  • ServerSocket (Server-side): Listens on a port. accept() blocks until a client connects, returns a Socket for that client.

  • Socket (Both sides): Represents a connection. Provides getInputStream() and getOutputStream() for communication.

4.4.3 Client-Side Programming

  1. Create Socket with server IP/hostname and port.

  2. Get streams: InputStream in = socket.getInputStream();, OutputStream out = socket.getOutputStream();.

  3. Wrap streams (e.g., BufferedReader, PrintWriter) for text communication.

  4. Read from in, write to out.

  5. Close socket.

4.4.4 Server-Side Programming

  1. Create ServerSocket on a port.

  2. Loop: Socket clientSocket = serverSocket.accept(); (blocks).

  3. For each clientSocket, handle communication in a new Thread (to serve multiple clients).

  4. In thread: get streams, read/write with client.

  5. Close client socket after communication.

4.4.5 Practical Lab Focus

  • Echo Client-Server: Server reads a line from client and sends it back.

  • Simple Chat (Multi-client): Server broadcasts each client's message to all other connected clients. Requires thread-safe collection of client sockets/streams.

  • Key Protocol: Define a simple text-based protocol (e.g., commands: LOGIN, MSG).

[!TIP] Common Pitfall: Forgetting to close sockets/streams leads to resource leaks. Always use try-with-resources for Socket, ServerSocket, and stream wrappers.


4.5 Database Connectivity (JDBC)

4.5.1 Introduction to JDBC Architecture and Drivers

  • JDBC API: Java interfaces (Connection, Statement, ResultSet).

  • JDBC Driver: Vendor-specific implementation (JAR file) that translates API calls to DB-specific protocol.

  • Driver Types: Type 4 (pure Java, network protocol) is most common (e.g., MySQL Connector/J).

4.5.2 Steps to Connect

  1. Load Driver: Class.forName("com.mysql.cj.jdbc.Driver"); (Optional for JDBC 4.0+ but good practice).

  2. Establish Connection:

    
    String url = "jdbc:mysql://localhost:3306/dbname";
    
    Connection conn = DriverManager.getConnection(url, "user", "password");
    
    
  3. Create Statement:

    • Statement: For static SQL. conn.createStatement().

    • PreparedStatement: For dynamic SQL with parameters. conn.prepareStatement(sql).

4.5.3 Executing Queries

  • executeQuery(String sql): For SELECT. Returns ResultSet.

  • executeUpdate(String sql): For INSERT, UPDATE, DELETE. Returns int (number of rows affected).

  • execute(): For complex SQL or when type is unknown. Returns boolean (true for ResultSet).

4.5.4 Processing ResultSet

  • Cursor initially before first row. Use next() to move forward.

  • Retrieve column data: getInt("colname"), getString(1), etc.

  • Loop pattern:

    
    ResultSet rs = stmt.executeQuery("SELECT * FROM students");
    
    while (rs.next()) {
    
        int id = rs.getInt("id");
    
        String name = rs.getString("name");
    
    }
    
    

4.5.5 Using PreparedStatement

  • Prevents SQL Injection: Parameters are sent to DB separately from SQL string.

  • Syntax: Use ? placeholders. Set values with setXxx(int parameterIndex, Xxx value).

    
    String sql = "INSERT INTO users(name, email) VALUES(?, ?)";
    
    PreparedStatement pstmt = conn.prepareStatement(sql);
    
    pstmt.setString(1, "Alice");
    
    pstmt.setString(2, "[email protected]");
    
    pstmt.executeUpdate();
    
    

4.5.6 Practical Lab Focus

Build a CRUD application for a table (e.g., products).

  • Create: INSERT via PreparedStatement.

  • Read: SELECT * FROM products -> populate JTable or list.

  • Update: UPDATE products SET price=? WHERE id=?.

  • Delete: DELETE FROM products WHERE id=?.

  • Key Pattern: Use try-with-resources for Connection, Statement, ResultSet to auto-close.

[!TIP] Exam Essential: Always close JDBC resources in reverse order of creation (ResultSet -> Statement -> Connection). Try-with-resources is the modern standard.


4.6 Integration Project: Mini-Project Development

4.6.1 Requirement Analysis and Design

  • Functional Requirements: What the system must do (e.g., "User can add a new book").

  • Non-Functional: Performance, security, usability.

  • Design Artifacts:

    • UML Class Diagram: Shows classes, attributes, methods, relationships.

    • Flowchart/Activity Diagram: Visualizes workflow (e.g., login process).

4.6.2 Combining Technologies

Typical integrations:

  • GUI + JDBC: Desktop app with database backend (e.g., inventory system).

  • GUI + File I/O: Import/export data to CSV or binary files.

  • GUI + Networking: Client-server application with rich UI (e.g., chat client).

  • All Three: GUI frontend, JDBC for main data, file I/O for backup/export.

4.6.3 Modular Programming and Code Organization

  • Packages: Group related classes (e.g., com.rgpv.app.ui, com.rgpv.app.db, com.rgpv.app.model).

  • Separation of Concerns:

    • Model: Data objects (POJOs/Entity classes).

    • View: GUI components (JFrame, JPanel).

    • Controller/Logic: Event handlers, business logic, database operations.

4.6.4 Basic Error Handling and User Feedback

  • Checked Exceptions: Handle SQLException, IOException with try-catch.

  • User Feedback: Use JOptionPane.showMessageDialog() for success/error messages. Log exceptions to console/file.

  • Validation: Validate user input before processing (e.g., non-empty fields, numeric values).

4.6.5 Practical Lab Focus

Develop a complete, menu-driven desktop application.

  • Example: Library Management System

    • GUI: JFrame with menu bar, JTable for book list, forms for add/update.

    • JDBC: BookDAO class with addBook(), getAllBooks(), deleteBook() methods.

    • File I/O: "Export to CSV" feature using FileWriter.

    • Structure:

      
      src/
      
      ├── model/Book.java
      
      ├── db/BookDAO.java (JDBC logic)
      
      ├── ui/LibraryFrame.java (Swing UI)
      
      └── Main.java
      
      

[!TIP] Project Success: Start with a simple working prototype (e.g., GUI with mock data), then integrate JDBC, then add file features. Test each integration step separately.

Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in