Module-4 Java Swings

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Prepared by Mr. Lohith C, Professor, Department of Dr.

APJ Kalam School of Engineering

Subject: Advanced Java and J2EE


Module 4-Java Swings
Prepared By Mr. Lohith C
Professor
Dept of APJ Abdul Kalam School of Engineering
Garden City University

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Java Swing: Overview and Key Concepts


Java Swing is a part of Java’s GUI (Graphical User Interface) toolkit that provides
lightweight, platform-independent components for building desktop applications. It extends
the Abstract Window Toolkit (AWT) and offers richer, more flexible components.

Features of Java Swing:

 Lightweight: Components are independent of native operating system resources.


 Pluggable Look-and-Feel: Customize the appearance of components without
changing the code.
 Platform Independent: Works consistently across platforms.
 MVC Architecture: Follows Model-View-Controller (MVC) pattern for component
organization.
 Event-Driven Programming: Uses event listeners to handle user interactions.

Common Swing Components and Containers

Swing provides various containers, components, and layout managers for building user
interfaces.

Top-Level Containers:

1. JFrame: A top-level window with a title and border.

java
Copy code
JFrame frame = new JFrame("My Swing App");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

2. JDialog: A pop-up window, often used for alerts or input prompts.


3. JApplet: A container for applets (deprecated).

Basic Swing Components:

1. JLabel: Displays a text or image.

java
Copy code
JLabel label = new JLabel("Hello, Swing!");
frame.add(label);

2. JButton: A button that triggers an action when clicked.

java

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Copy code
JButton button = new JButton("Click Me");
frame.add(button);

3. JTextField: A single-line text input.

java
Copy code
JTextField textField = new JTextField(20);
frame.add(textField);

4. JTextArea: A multi-line text input area.


5. JCheckBox / JRadioButton: For selecting options.
6. JComboBox: A drop-down menu.

Layout Managers

Layout managers organize the components in a container.

1. FlowLayout: Arranges components in a row.

java
Copy code
frame.setLayout(new FlowLayout());

2. BorderLayout: Divides the container into five regions: North, South, East, West, and
Center.
3. GridLayout: Arranges components in a grid.

java
Copy code
frame.setLayout(new GridLayout(2, 2)); // 2x2 grid

4. BoxLayout: Aligns components horizontally or vertically.

Event Handling in Swing

Swing uses the event-listener mechanism for handling user actions, such as button clicks.

Example: Handling Button Click Event

1. Add an Action Listener to a button.

java
Copy code
JButton button = new JButton("Click Me");
button.addActionListener(e -> System.out.println("Button clicked!"));
frame.add(button);

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

2. Alternatively, implement the ActionListener interface:

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

Working with Menus

Menus are created using JMenuBar, JMenu, and JMenuItem.

java
Copy code
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenuItem menuItem = new JMenuItem("Open");
menu.add(menuItem);
menuBar.add(menu);
frame.setJMenuBar(menuBar);

Swing Example: A Simple GUI Application


java
Copy code
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SimpleSwingApp {


public static void main(String[] args) {
JFrame frame = new JFrame("My Swing Application");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Set layout and add components


frame.setLayout(new FlowLayout());
JLabel label = new JLabel("Enter your name:");
JTextField textField = new JTextField(15);
JButton button = new JButton("Greet");

frame.add(label);
frame.add(textField);
frame.add(button);

// Add event listener to button


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = textField.getText();
JOptionPane.showMessageDialog(frame, "Hello, " + name +
"!");
}
});

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

frame.setVisible(true);
}
}

Explanation:

 A JFrame window is created.


 The layout is set to FlowLayout.
 A JLabel, JTextField, and JButton are added.
 An ActionListener is attached to the button to display a greeting message using
JOptionPane.

Handling Exceptions in Swing

Swing code can encounter exceptions, such as NullPointerException or


IllegalComponentStateException. Use try-catch blocks to handle them gracefully.

java
Copy code
try {
JFrame frame = new JFrame("Swing Example");
frame.setSize(300, 200);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

IDEs: Using NetBeans IDE and Eclipse IDE with Swing


Both NetBeans and Eclipse are popular Integrated Development Environments (IDEs) for
developing Java applications, including Swing-based GUI applications. Below is a
breakdown of how these IDEs support Swing development, along with key features, steps,
and examples for creating Swing projects in each.

1. NetBeans IDE with Swing


Features of NetBeans for Swing Development

 Drag-and-Drop GUI Builder: NetBeans provides a built-in GUI Designer (Matisse)


that lets you visually design Swing interfaces using drag-and-drop.
 Pre-configured Swing Components: Labels, buttons, text fields, panels, and other
Swing components are available directly in the GUI builder.
 Event Handling Integration: NetBeans allows automatic event generation by
clicking on components in the GUI Designer.
 Code Synchronization: Any changes in the GUI Designer are automatically reflected
in the code.

Creating a Swing Application in NetBeans

1. Open NetBeans and select File > New Project.


2. Choose Java > Java Application and click Next.
3. Provide a Project Name and click Finish.
4. Right-click on the Source Packages folder and select New > JFrame Form.
5. Name the form and click Finish.

Designing the GUI with the GUI Builder:

 Drag components like JButton or JLabel from the Palette to the form.
 Use the Properties window to set properties (e.g., button text or label font).
 Double-click the button to generate an ActionListener for it.

Sample Code with ActionListener in NetBeans:

java
Copy code
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// Display a message dialog on button click
JOptionPane.showMessageDialog(this, "Hello, Swing in NetBeans!");
}

6. Run the Project: Click Run > Run Project, or press F6 to see the GUI.

Advantages of NetBeans for Swing:

 GUI Builder simplifies interface creation.


 Automatic Event Handling reduces boilerplate code.
 Project Templates for Swing applications.
Garden City University
Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

 Real-time Design View to see how the interface looks as you build.

2. Eclipse IDE with Swing


Features of Eclipse for Swing Development

 Eclipse doesn’t have a built-in drag-and-drop GUI builder like NetBeans, but
plugins (e.g., WindowBuilder) can be installed to add this functionality.
 Manual Code-Driven Development: More suitable for developers who prefer to
manually create Swing interfaces via code.
 Powerful Debugger and Code Refactoring Tools.

Creating a Swing Application in Eclipse (With and Without Plugins)

Method 1: Swing Application Without Plugins (Manual Code)

1. Open Eclipse and select File > New > Java Project.
2. Provide a Project Name and click Finish.
3. Right-click the src folder and select New > Class.
4. Name the class (e.g., MySwingApp) and check the public static void main() option.
5. Write the Swing code in the main method.

Sample Code for Swing in Eclipse:

java
Copy code
import javax.swing.*;

public class MySwingApp {


public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("Swing Application in Eclipse");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a button and add it to the frame


JButton button = new JButton("Click Me");
button.addActionListener(e -> JOptionPane.showMessageDialog(frame,
"Hello from Eclipse!"));
frame.add(button);

// Display the frame


frame.setVisible(true);
}
}

6. Run the Project: Right-click the class in the Project Explorer and select Run As >
Java Application.

Method 2: Swing Application with WindowBuilder Plugin

1. Install WindowBuilder:
o Go to Help > Eclipse Marketplace and search for WindowBuilder.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

oInstall it and restart Eclipse.


2. Create a Swing Application with WindowBuilder:
o Right-click on the src folder and select New > Other > WindowBuilder >
Swing Designer > JFrame.
o Use the drag-and-drop editor to design your GUI.
o Double-click components to generate event-handling code.

Advantages of Eclipse for Swing:

 Highly Configurable: Great for developers who prefer manual control over code.
 WindowBuilder Plugin: Adds GUI design support similar to NetBeans.
 Better for Large Projects: Advanced debugging and refactoring tools.

Comparison: NetBeans vs Eclipse for Swing Development

Feature NetBeans Eclipse


GUI Builder Built-in (Matisse) Requires WindowBuilder plugin
Ease of Use Easier with drag-and-drop design More manual but flexible
Event Handling Automatic generation Manual or through WindowBuilder
Learning Curve Easier for beginners Better for experienced users
Plugin Support Limited Extensive plugin ecosystem
Best Use Case Simple GUI applications Complex projects with code control

Conclusion
 NetBeans is ideal for developers looking for ease of use with drag-and-drop
functionality through its built-in GUI builder.
 Eclipse offers more flexibility and control but requires additional plugins (like
WindowBuilder) for visual design.
 Both IDEs support Swing and event-driven programming, making them suitable for
building modern Java desktop applications. The choice depends on whether you
prefer visual design (NetBeans) or manual code control (Eclipse).

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Swing Components: Containers and Controls


Swing provides a wide range of components to build GUI applications. These components
are broadly divided into Containers (which hold other components) and Controls
(interactive elements such as buttons, labels, etc.).

1. Swing Containers

A container is a component that can hold other components or containers. The main
containers in Swing are:

Top-Level Containers:

1. JFrame
o A top-level window with a title bar, used to build the main window of the
application.
o Example:

java
Copy code
JFrame frame = new JFrame("My Application");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

2. JDialog
o A pop-up window for alerts, confirmations, or custom dialogs.
o Can be modal (blocks input to other windows) or non-modal.
3. JApplet
o Deprecated but previously used for embedding Java programs into web
browsers.
4. JWindow
o A simpler window without a title bar or borders.

Intermediate Containers:

1. JPanel
o A lightweight container used to group components.
o Useful for creating separate sections of a GUI.
o Example:

Java Copy code


JPanel panel = new JPanel();
panel.add(new JButton("Button"));
frame.add(panel);

2. JScrollPane
o Provides a scrollable view of components that are too large to fit in the visible
area.
3. JSplitPane
o Splits the window into two resizable sections (horizontal/vertical).

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

2. Swing Controls (Basic Components)

Swing provides interactive components (controls) to build user interfaces.

1. JLabel
o Displays text or images.

java
Copy code
JLabel label = new JLabel("Welcome to Swing!");
panel.add(label);

2. JButton
o A clickable button that triggers actions.

java
Copy code
JButton button = new JButton("Click Me");
button.addActionListener(e -> System.out.println("Button clicked!"));
panel.add(button);

3. JTextField
o Single-line input field for text.

java
Copy code
JTextField textField = new JTextField(20);
panel.add(textField);

4. JTextArea
o Multi-line text area for user input or displaying text.
5. JCheckBox
o A toggle button for selecting/deselecting an option.
6. JRadioButton
o A mutually exclusive option (used with ButtonGroup).
7. JComboBox
o A drop-down list for selecting options.
8. JTable
o Displays tabular data.
9. JProgressBar
o Displays the progress of a task.
10. JMenu

 Used to create application menus (File, Edit, etc.).

3. Layout Managers

Swing uses layout managers to determine how components are arranged within containers.
Common layout managers include:

1. FlowLayout: Places components in a row (default layout for JPanel).

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

2. BorderLayout: Divides the container into five regions (North, South, East, West,
Center).
3. GridLayout: Arranges components in a grid with equal-sized cells.
4. BoxLayout: Aligns components horizontally or vertically.

Working of Front-End Application in NetBeans using


Swing
NetBeans makes it easy to build front-end applications using Swing through its GUI Builder
(Matisse). Below is a step-by-step guide to creating a basic front-end application with
NetBeans.

Step 1: Create a New Java Project

1. Open NetBeans.
2. Go to File > New Project > Java > Java Application.
3. Enter a Project Name and click Finish.

Step 2: Create a JFrame Form

1. Right-click on the Source Packages folder in the Projects window.


2. Select New > JFrame Form.
3. Provide a name for the form (e.g., MainFrame) and click Finish.

Step 3: Design the GUI with GUI Builder

1. Open the JFrame file (e.g., MainFrame.java).


2. Switch to the Design View tab at the top.
3. Drag and drop components from the Palette (like JButton, JLabel, JTextField) onto
the JFrame.

Example GUI Design:

oLabel: "Enter Name:"


oText Field: To input the name.
oButton: "Submit"
4. Use the Properties Window to set properties like text, size, and layout.

Step 4: Add Event Handling

 To handle button clicks, double-click the button to open the ActionPerformed


method.

Sample Code for Button Click Event:

java
Copy code

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {


String name = jTextField1.getText();
JOptionPane.showMessageDialog(this, "Hello, " + name + "!");
}

 This code retrieves the text entered in the text field and displays it using a
JOptionPane message dialog.

Step 5: Run the Application

1. Click Run > Run Project, or press F6 to run the application.


2. Enter your name in the text field and click Submit.
You should see a pop-up with the message: "Hello, [Your Name]!"

Advantages of Using NetBeans for Swing Applications

 Drag-and-Drop GUI Builder: Speeds up interface design.


 Automatic Event Handling: Events are generated automatically when you double-
click components.
 Code Synchronization: Changes in the GUI Builder are reflected in the code and
vice-versa.
 Real-time Preview: View how your application will look at design time.

Conclusion
Swing provides a rich set of containers and controls for building GUI applications.
NetBeans IDE simplifies Swing development through its drag-and-drop GUI Builder and
automatic event handling. Using Swing components like JButton, JLabel, JTextField, and
managing events with ActionListeners, developers can quickly build interactive and
responsive front-end applications. This combination of Swing and NetBeans provides a
powerful and efficient way to create Java-based desktop applications.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Case Study: Calculator Application using Swing in


NetBeans
In this case study, we will walk through the development of a Calculator application using
Java Swing in NetBeans IDE. This simple calculator will provide basic arithmetic
operations like addition, subtraction, multiplication, and division with a well-organized
GUI.

Features of the Calculator Application:

 Basic operations: Add (+), Subtract (-), Multiply (×), Divide (÷)
 Clear button to reset input and output.
 User-friendly GUI with buttons for numbers and operations.

Step-by-Step Implementation in NetBeans

Step 1: Create a New Java Application in NetBeans

1. Open NetBeans IDE.


2. Select File > New Project > Java > Java Application.
3. Name the project (e.g., CalculatorApp) and click Finish.

Step 2: Create a New JFrame Form

1. Right-click on Source Packages in the Projects window.


2. Select New > JFrame Form.
3. Name the JFrame form (e.g., Calculator) and click Finish.

Step 3: Design the Calculator GUI using the GUI Builder

1. Switch to the Design View in the JFrame.


2. From the Palette, drag and drop the following components onto the form:
o JTextField (for displaying input and results)
o JButtons for numbers (0-9) and operations (+, -, *, /, =, C)
o JPanel to group and organize the buttons (optional for cleaner design)

Arrange the Components:

 Use a GridLayout for the button panel to arrange buttons neatly.


 Set the JTextField to be non-editable for better control of input.

Step 4: Add Components to the Form

1. JTextField: Set the name to txtDisplay.


2. Buttons: Create buttons for digits (0-9) and operations.
o Example buttons:
 btn1, btn2, btnAdd, btnEqual, btnClear, etc.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Example Layout:

78 9/
45 6*
12 3-
0C=+

Step 5: Add Action Listeners to Buttons

1. Double-click each button in the design view to generate an ActionPerformed


method.
2. Use these methods to implement the calculator logic.

Step 6: Implement the Calculator Logic

Below is the full code for the Calculator application.

java
Copy code
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Calculator extends JFrame {


private JTextField txtDisplay;
private double num1, num2, result;
private String operator;

public Calculator() {
// Set JFrame properties
setTitle("Calculator");
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);

// Create display field


txtDisplay = new JTextField();
txtDisplay.setBounds(30, 40, 320, 50);
txtDisplay.setEditable(false);
add(txtDisplay);

// Create panel for buttons


JPanel panel = new JPanel();
panel.setBounds(30, 100, 320, 300);
panel.setLayout(new java.awt.GridLayout(4, 4, 10, 10));

// Add buttons to panel


String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+"
};

for (String text : buttons) {


JButton button = new JButton(text);

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

button.addActionListener(new ButtonClickListener());
panel.add(button);
}

add(panel);
setVisible(true);
}

// Button click event handler


private class ButtonClickListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();

if (command.charAt(0) >= '0' && command.charAt(0) <= '9') {


// If a number is pressed, append it to the display
txtDisplay.setText(txtDisplay.getText() + command);
} else if (command.equals("C")) {
// Clear the display
txtDisplay.setText("");
num1 = num2 = result = 0;
operator = "";
} else if (command.equals("=")) {
// Perform calculation when '=' is pressed
num2 = Double.parseDouble(txtDisplay.getText());
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0) {
result = num1 / num2;
} else {
JOptionPane.showMessageDialog(null, "Cannot
divide by zero");
return;
}
break;
}
txtDisplay.setText(String.valueOf(result));
operator = "";
} else {
// Store the first number and operator
num1 = Double.parseDouble(txtDisplay.getText());
operator = command;
txtDisplay.setText("");
}
}
}

public static void main(String[] args) {


new Calculator();
}
}

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Explanation of the Code

1. GUI Setup:
o A JFrame is created with a title and layout.
o A JTextField is used to display input and results.
o A JPanel with a GridLayout is used to arrange buttons neatly.
2. Event Handling:
o A ButtonClickListener inner class is created to handle button events.
o Number buttons append digits to the text field.
o Operation buttons store the first number and the operator.
o The equals (=) button performs the calculation and displays the result.
o The clear (C) button resets the calculator.
3. Arithmetic Operations:
o Depending on the operator, the corresponding arithmetic operation is
performed.
4. Division by Zero Handling:
o A JOptionPane message box is used to handle division by zero errors
gracefully.

Step 7: Run the Calculator Application

1. Click Run > Run Project or press F6.


2. The Calculator GUI will open, and you can start using it to perform arithmetic
operations.

Features of the Calculator Application:

 Basic Operations: Addition, Subtraction, Multiplication, Division.


 Clear Functionality: Reset input and output.
 Error Handling: Displays a message for division by zero.

Conclusion

In this case study, we have created a simple calculator application using Java Swing in
NetBeans. We utilized JFrame, JTextField, JButton, and JPanel to build the GUI. The
project demonstrates how to handle button click events and implement basic arithmetic
operations. With NetBeans’ GUI Builder, the development process becomes faster and
more intuitive, making it easy to design and implement front-end applications like this
calculator.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Case Study: Database Application Creation using Swing


In this case study, we will design and implement a Database Application using Java Swing
and MySQL. The application will manage a simple Employee Management System (EMS),
allowing users to add, view, update, and delete employee records. This application will
demonstrate how to interact with a database using JDBC while providing a user-friendly
graphical interface.

Features of the Employee Management System:

1. Add Employee: Add new employee records to the database.


2. View Employees: Display all employee records in a table.
3. Update Employee: Update existing employee details.
4. Delete Employee: Remove employee records from the database.
5. Search Employee: Find an employee by ID.

Technologies Used:

 Java Swing for the user interface.


 MySQL as the database management system.
 JDBC (Java Database Connectivity) for database interaction.

Step-by-Step Implementation

Step 1: Set Up the MySQL Database

1. Install MySQL Server and set up a database for the application.


2. Create a Database named EmployeeDB.

sql
Copy code
CREATE DATABASE EmployeeDB;
USE EmployeeDB;

CREATE TABLE employees (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
designation VARCHAR(100),
salary DECIMAL(10, 2)
);

Step 2: Create a New Java Application in NetBeans

1. Open NetBeans IDE.


2. Select File > New Project > Java > Java Application.
3. Name the project (e.g., EmployeeManagementSystem) and click Finish.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Step 3: Add JDBC Driver to Project

1. Download the MySQL JDBC Driver (e.g., mysql-connector-java-x.x.x.jar).


2. Right-click on the project, select Properties > Libraries > Add JAR/Folder and add
the downloaded JDBC driver.

Step 4: Create a New JFrame Form

1. Right-click on Source Packages in the Projects window.


2. Select New > JFrame Form.
3. Name the JFrame form (e.g., EmployeeForm) and click Finish.

Step 5: Design the GUI Using the GUI Builder

1. Switch to the Design View in the JFrame.


2. Drag and drop the following components from the Palette onto the form:
o JTextField for inputting employee name, designation, and salary.
o JButtons for actions (Add, Update, Delete, View, Search).
o JTable for displaying employee records.
o JScrollPane for making the JTable scrollable.

Example Layout:

 Labels for Name, Designation, and Salary.


 Text Fields for user input.
 Buttons for operations.
 JTable to display records.

Step 6: Implement Java Code Refer: Experiment 3 in Syllabus

Conclusion

In this case study, we successfully developed an Employee Management System using Java
Swing and MySQL. The application demonstrates how to perform CRUD (Create, Read,
Update, Delete) operations using JDBC for database interactions. By leveraging Swing
components and event handling, we created a user-friendly interface that effectively
manages employee records. This example can be extended further with additional features
like input validation, search functionality, and more sophisticated UI designs.

Garden City University

You might also like