Module-4 Java Swings
Module-4 Java Swings
Module-4 Java Swings
Swing provides various containers, components, and layout managers for building user
interfaces.
Top-Level Containers:
java
Copy code
JFrame frame = new JFrame("My Swing App");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
java
Copy code
JLabel label = new JLabel("Hello, Swing!");
frame.add(label);
java
Copy code
JButton button = new JButton("Click Me");
frame.add(button);
java
Copy code
JTextField textField = new JTextField(20);
frame.add(textField);
Layout Managers
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
Swing uses the event-listener mechanism for handling user actions, such as button clicks.
java
Copy code
JButton button = new JButton("Click Me");
button.addActionListener(e -> System.out.println("Button clicked!"));
frame.add(button);
java
Copy code
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});
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);
frame.add(label);
frame.add(textField);
frame.add(button);
frame.setVisible(true);
}
}
Explanation:
java
Copy code
try {
JFrame frame = new JFrame("Swing Example");
frame.setSize(300, 200);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
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.
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.
Real-time Design View to see how the interface looks as you build.
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.
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.
java
Copy code
import javax.swing.*;
6. Run the Project: Right-click the class in the Project Explorer and select Run As >
Java Application.
1. Install WindowBuilder:
o Go to Help > Eclipse Marketplace and search for WindowBuilder.
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.
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).
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:
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).
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
3. Layout Managers
Swing uses layout managers to determine how components are arranged within containers.
Common layout managers include:
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.
1. Open NetBeans.
2. Go to File > New Project > Java > Java Application.
3. Enter a Project Name and click Finish.
java
Copy code
This code retrieves the text entered in the text field and displays it using a
JOptionPane message dialog.
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.
Basic operations: Add (+), Subtract (-), Multiply (×), Divide (÷)
Clear button to reset input and output.
User-friendly GUI with buttons for numbers and operations.
Example Layout:
78 9/
45 6*
12 3-
0C=+
java
Copy code
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public Calculator() {
// Set JFrame properties
setTitle("Calculator");
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
button.addActionListener(new ButtonClickListener());
panel.add(button);
}
add(panel);
setVisible(true);
}
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.
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.
Technologies Used:
Step-by-Step Implementation
sql
Copy code
CREATE DATABASE EmployeeDB;
USE EmployeeDB;
Example Layout:
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.