GUI Programming
Comprehensive exam revision notes for BCA-432E Unit 5 (ASP.NET 4.0 Web Forms & Application Deployment). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.
GUI Programming
ASP.NET 4.0 Web Forms & Application Deployment
Core Definitions & Key Concepts
What is a Data-Driven GUI Application
An interactive graphical application whose controls, displays, and workflows are dynamically populated, synchronized, and mutated in response to underlying persistent database records (CRUD operations).
The role of SwingWorker in multithreaded GUI applications
SwingWorker<T, V> is an abstract class designed for executing long-running background tasks on a worker thread (doInBackground()), streaming partial progress to the EDT (publish() / process()), and updating GUI components upon completion on the EDT (done()).
What is the difference between client-side form validation and server-side validation
- Client-Side: Immediate feedback in the GUI (e.g., verifying phone format, non-empty text fields) to enhance user experience.
- Server-Side: Mandatory cryptographic/security validation at the database/API layer to prevent tampering and malicious injection.
InputVerifier in Java Swing
An abstract class (javax.swing.InputVerifier) attached to text components (setInputVerifier()) that validates input before focus is allowed to leave the component, preventing invalid input propagation.
How do you bind database records to a JTable dynamically
By populating a DefaultTableModel with rows queried via JDBC ResultSet, using ResultSetMetaData to extract column count and headers dynamically.
What is a JAR (Java Archive) file
A platform-independent package file format aggregating multiple Java class files, associated metadata (manifest), and resources (images, audio) into a single compressed ZIP container.
What is the significance of the META-INF/MANIFEST.MF file in an executable JAR
The manifest file contains package configuration metadata. Specifically, the Main-Class: com.example.MainApp entry specifies the exact entry-point class containing the main() method, enabling direct double-click execution.
What command packages a compiled application into an executable JAR
jar cfe Application.jar com.mjpru.bca.MainClass -C bin/ . (c: create, f: file, e: entrypoint).
What is jpackage in modern Java (Java 14+)
A command-line tool that packages Java applications and an embedded minimal Java Runtime Environment (JRE) into native platform-specific installable packages (.exe/.msi on Windows, .dmg on macOS, .deb on Linux).
What are the two core methods of SwingWorker
doInBackground(): Runs on background thread pool; does heavy lifting (database/network); must never touch GUI components.done(): Runs automatically on the Event Dispatch Thread (EDT) when background work completes; safe to update UI.
Conceptual & Architectural Analysis
SwingWorker Lifecycle and Methods Architecture
[ USER ACTION: Click Fetch Button ] (On EDT)
|
v
new MySwingWorker().execute()
|
+---------> [ WORKER THREAD POOL ]
| - doInBackground()
| - Heavy SQL query / File download
| - publish(chunk) -----------------+
| - returns Result |
| v
| [ EDT (Event Dispatch Thread) ]
| - process(chunks) -> Updates progress bar
v |
[ Background Task Completes ] v
+----------------------------------> - done() -> Populates JTable / Alerts userCompare Client-Side GUI Validation Strategies
| Validation Method | Mechanism | User Experience | Best Used For |
|---|---|---|---|
| Submit-time Validation | Checks all fields upon clicking 'Submit' | User only sees errors after submission | Batch validation of full form |
| Focus-Lost Validation (`InputVerifier`) | Evaluates field when user tabs away | Catches errors per field immediately | Formatted inputs (dates, phone numbers) |
| Keystroke Validation (`DocumentFilter`) | Intercepts character insertion in real-time | Prevents invalid character typing entirely | Numeric-only fields (Roll numbers, OTP) |
DocumentFilter for Restricting Text Field Input
1AbstractDocument doc = (AbstractDocument) numericField.getDocument();2doc.setDocumentFilter(new DocumentFilter() {3 @Override4 public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {5 if (string != null && string.matches("\\d+")) super.insertString(fb, offset, string, attr);6 }7 @Override8 public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {9 if (text != null && text.matches("\\d+")) super.replace(fb, offset, length, text, attrs);10 }11});Creating an Executable JAR File with Dependencies
- Compile Source Code:
javac -d bin/ src/com/mjpru/*.java - Create Manifest File (`manifest.txt`):
1Manifest-Version: 1.02Main-Class: com.mjpru.StudentPortalApp3Class-Path: lib/mysql-connector-j.jar4
(Note: File must end with an empty newline!)
- Build JAR:
jar cfm StudentPortal.jar manifest.txt -C bin/ . - Execution:
java -jar StudentPortal.jar
Database Connection Management in Desktop GUI Applications
Desktop applications maintain a single shared connection pool or open connections on background worker threads. Long-running queries must run on SwingWorker to prevent freezing the interface.
In-Depth Analysis & Implementation
Develop a Complete Data-Driven Desktop CRUD GUI Application with SQLite/MySQL, Asynchronous SwingWorker, and Real-time Table Synchronization
package com.mjpru.bca.gui;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DatabaseStudentManager extends JFrame {
private JTable studentTable;
private DefaultTableModel tableModel;
private JTextField rollField, nameField, marksField;
private JProgressBar progressBar;
private JButton loadBtn, addBtn;
private final String DB_URL = "jdbc:sqlite:mjpru_students.db";
public DatabaseStudentManager() {
setTitle("MJPRU Asynchronous Student Database Manager");
setSize(700, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new BorderLayout(8, 8));
initDatabase();
// 1. Top Input Form
JPanel formPanel = new JPanel(new FlowLayout());
rollField = new JTextField(6);
nameField = new JTextField(12);
marksField = new JTextField(6);
addBtn = new JButton("Add Student");
formPanel.add(new JLabel("Roll:")); formPanel.add(rollField);
formPanel.add(new JLabel("Name:")); formPanel.add(nameField);
formPanel.add(new JLabel("Marks:")); formPanel.add(marksField);
formPanel.add(addBtn);
add(formPanel, BorderLayout.NORTH);
// 2. Center Table
tableModel = new DefaultTableModel(new String[]{"Roll No", "Name", "Marks"}, 0);
studentTable = new JTable(tableModel);
add(new JScrollPane(studentTable), BorderLayout.CENTER);
// 3. Bottom Progress Bar & Load Button
JPanel statusPanel = new JPanel(new BorderLayout());
progressBar = new JProgressBar();
progressBar.setStringPainted(true);
loadBtn = new JButton("Load Records Asynchronously");
statusPanel.add(progressBar, BorderLayout.CENTER);
statusPanel.add(loadBtn, BorderLayout.EAST);
add(statusPanel, BorderLayout.SOUTH);
// Asynchronous Loading with SwingWorker
loadBtn.addActionListener(e -> loadDataAsynchronously());
addBtn.addActionListener(e -> {
int roll = Integer.parseInt(rollField.getText());
String name = nameField.getText();
double marks = Double.parseDouble(marksField.getText());
insertStudent(roll, name, marks);
loadDataAsynchronously();
});
}
private void initDatabase() {
try (Connection conn = DriverManager.getConnection(DB_URL);
Statement stmt = conn.createStatement()) {
stmt.execute("CREATE TABLE IF NOT EXISTS students (roll INT PRIMARY KEY, name TEXT, marks REAL)");
} catch (SQLException ex) { ex.printStackTrace(); }
}
private void insertStudent(int roll, String name, double marks) {
String sql = "INSERT OR REPLACE INTO students VALUES (?, ?, ?)";
try (Connection conn = DriverManager.getConnection(DB_URL);
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, roll);
ps.setString(2, name);
ps.setDouble(3, marks);
ps.executeUpdate();
} catch (SQLException ex) { ex.printStackTrace(); }
}
private void loadDataAsynchronously() {
loadBtn.setEnabled(false);
progressBar.setIndeterminate(true);
progressBar.setString("Querying database on background thread...");
SwingWorker<List<Object[]>, Void> worker = new SwingWorker<List<Object[]>, Void>() {
@Override
protected List<Object[]> doInBackground() throws Exception {
List<Object[]> rows = new ArrayList<>();
Thread.sleep(1000); // Simulate network latency
try (Connection conn = DriverManager.getConnection(DB_URL);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM students")) {
while (rs.next()) {
rows.add(new Object[]{rs.getInt("roll"), rs.getString("name"), rs.getDouble("marks")});
}
}
return rows;
}
@Override
protected void done() {
try {
List<Object[]> data = get();
tableModel.setRowCount(0); // Clear old rows
for (Object[] row : data) tableModel.addRow(row);
progressBar.setIndeterminate(false);
progressBar.setString("Loaded " + data.size() + " records.");
} catch (Exception ex) {
progressBar.setString("Error loading data");
} finally {
loadBtn.setEnabled(true);
}
}
};
worker.execute();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new DatabaseStudentManager().setVisible(true));
}
}Detail the Packaging and Deployment Pipeline of Desktop Applications from .java to Native Executable Installer (.exe)
Enterprise Desktop Deployment Pipeline
[ Source Code (.java) ]
|
v javac
[ Compiled Bytecode (.class) ]
|
v jar (with MANIFEST.MF)
[ Executable JAR (.jar) ]
|
v jlink (Extracts minimal JVM runtime module strip)
[ Custom Minimal JRE Runtime ]
|
v jpackage
[ Self-Contained Native Windows Installer (.exe / .msi) ]Why Native Packaging (jpackage) Outperformed Raw JAR Files:
- No External JRE Prerequisite: The user does not need to install Java on their computer; an optimized runtime is embedded inside the installation.
- Operating System Integration: Generates desktop shortcuts, start menu entries, file type associations, and clean uninstaller in Windows Add/Remove Programs.
- Memory Optimization:
jlinkstrips unused standard modules (e.g., removing CORBA or Enterprise modules), shrinking the application footprint from 300MB to under 35MB.
Real-Time Form Input Validation with InputVerifier and Visual Error Feedback
1public class EmailInputVerifier extends InputVerifier {2 private final String EMAIL_REGEX = "^[A-Za-z0-9+_.-]+@(.+)$";3
4 @Override5 public boolean verify(JComponent input) {6 JTextField tf = (JTextField) input;7 String text = tf.getText().trim();8 boolean valid = text.matches(EMAIL_REGEX);9 if (!valid) {10 tf.setBackground(new Color(254, 226, 226)); // Soft Red11 tf.setBorder(BorderFactory.createLineBorder(Color.RED, 2));12 } else {13 tf.setBackground(Color.WHITE);14 tf.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));15 }16 return valid;17 }18}Important Exam Points & Quick Revision
Examiners frequently ask: SwingWorker architecture and threading (guaranteed 10 marks Section C), Executable JAR creation with manifest, and Input validation mechanisms.
100% left on this page — finishing it closes the gap for ASP.NET 4.0 Web Forms & Application Deployment.
ASP.NET 4.0 Web Forms & Application Deployment still counts as a weak topic until you finish this note and answer its questions.
Practise this unitTest Your Understanding
Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.