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 fromJComponent. -
JComponentis 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 (
JButtonnotButton).
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.
BorderLayoutis the default forJFrame'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,Enterin text field. -
ItemListener: Checkbox/radio button state changes, combo box selections. -
WindowListener: Window events (closing, activating).
-
-
Implementation Styles:
-
Implement Listener Interface: Class
implements ActionListener. -
Anonymous Inner Class:
button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ... } }); -
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 toJFrame.setJMenuBar(). -
Dialogs:
-
JOptionPane: Simple modal dialogs (message, confirm, input). Static methods likeshowMessageDialog(). -
JFileChooser: Standard file open/save dialog.showOpenDialog()returnsAPPROVE_OPTIONorCANCEL_OPTION.
-
-
Toolbars:
JToolBarholdsJButtonor 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,
ActionListeneron 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).
-
FileClass: 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.BufferedReaderprovidesreadLine()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/OutputStreamWriterwith charset name. -
PrintWriter/PrintStream: Convenient for formatted text output.print()/println()methods.PrintWritercan 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
transientkeyword 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>tostudents.datusingObjectOutputStream. Load it back withObjectInputStream. -
Key Pattern:
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.obj"))) { oos.writeObject(myObject); } catch (IOException e) { e.printStackTrace(); }
[!TIP] Common Pitfall:
FileNotFoundExceptionis 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
-
Extend
Threadclass: Overriderun().new MyThread().start().- Limitation: Java doesn't support multiple inheritance.
-
Implement
Runnableinterface: PassRunnabletoThreadconstructor.new Thread(new MyRunnable()).start().- Preferred: Separates task (
Runnable) from execution mechanism (Thread).
- Preferred: Separates task (
4.3.2 Thread Lifecycle and States
-
NEW: Thread created, not started.
-
RUNNABLE: Executing or ready to execute (includes OS "running" state).
-
BLOCKED: Waiting for monitor lock (to enter
synchronizedblock/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 onthis(instance) orClassName.class(static). -
Synchronized Block: More granular.
synchronized(lockObject) { ... }. Locks on specified object. -
volatileKeyword: 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>: LikeRunnablebut returns a value and can throw checked exceptions.
4.3.6 Practical Lab Focus
-
Producer-Consumer Problem: Use
synchronizedblocks withwait()/notifyAll()on a shared buffer. -
Banking Simulation:
synchronizedmethods onAccountfordeposit()/withdraw()to prevent race conditions. -
Thread Pool: Use
ExecutorServiceto 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 aSocketfor that client. -
Socket(Both sides): Represents a connection. ProvidesgetInputStream()andgetOutputStream()for communication.
4.4.3 Client-Side Programming
-
Create
Socketwith server IP/hostname and port. -
Get streams:
InputStream in = socket.getInputStream();,OutputStream out = socket.getOutputStream();. -
Wrap streams (e.g.,
BufferedReader,PrintWriter) for text communication. -
Read from
in, write toout. -
Close socket.
4.4.4 Server-Side Programming
-
Create
ServerSocketon a port. -
Loop:
Socket clientSocket = serverSocket.accept();(blocks). -
For each
clientSocket, handle communication in a new Thread (to serve multiple clients). -
In thread: get streams, read/write with client.
-
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
-
Load Driver:
Class.forName("com.mysql.cj.jdbc.Driver");(Optional for JDBC 4.0+ but good practice). -
Establish Connection:
String url = "jdbc:mysql://localhost:3306/dbname"; Connection conn = DriverManager.getConnection(url, "user", "password"); -
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): ForSELECT. ReturnsResultSet. -
executeUpdate(String sql): ForINSERT,UPDATE,DELETE. Returnsint(number of rows affected). -
execute(): For complex SQL or when type is unknown. Returnsboolean(trueforResultSet).
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 withsetXxx(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:
INSERTviaPreparedStatement. -
Read:
SELECT * FROM products-> populateJTableor list. -
Update:
UPDATE products SET price=? WHERE id=?. -
Delete:
DELETE FROM products WHERE id=?. -
Key Pattern: Use try-with-resources for
Connection,Statement,ResultSetto 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,IOExceptionwith 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:
JFramewith menu bar,JTablefor book list, forms for add/update. -
JDBC:
BookDAOclass withaddBook(),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.