Java GUI
In Java,Graphical user interface is the collection of visual components that enable intuitive and user-friendly user interaction with a program. Users can interact with graphical elements such as buttons, text fields, checkboxes, and menus rather than text-based commands.
Component
A Component is an individual graphical element that can be displayed on the screen and used to interact with the user. Components serve as the core elements of a graphical user interface and include items such as:
- Button: A clickable element used to trigger actions.
- Label: Displays non-editable, static text.
- TextField: Allows users to input text.
- Checkbox: Enables selection between true and false options.
In Abstract Window Toolkit (AWT), all these components inherit from the base class:
java.awt.Component
Container
A Container is a special type of component designed to hold and organize other components. Acting as a parent, it manages the placement and grouping of its child components.
Key Features of a Container
- It maintains a record of all components.
- It organizes its child components using layout managers like
BorderLayout
,FlowLayout
, orGridLayout
. - It supports a clean, modular approach to building graphical user interfaces.
Panel, Frame, Window, and Dialog are common Java container types. A Panel is a simple container that is perfect for grouping and organizing similar components because it may be integrated into other containers. Usually used as the primary window of a desktop application, a Frame is a top-level window with borders and a title bar. Another kind of top-level container is a window, which is different from a frame in that it doesn't have a menu bar or other typical window decorations. Finally, a dialog is a pop-up window that is frequently used for brief interactions, such presenting messages or asking the user for input.
Abstract Window Toolkit(AWT) and Swing
Abstract Window Toolkit: One of the first graphical user interface (GUI) libraries was the Abstract Window Toolkit (AWT), which Sun Microsystems included in Java's core libraries in 1995. Because it is a platform-dependent API, GUI elements are rendered by the windowing system of the underlying native operating system. This may lead to minor variations in behavior and appearance between systems.
AWT offers a basic collection of GUI components that form the foundation for building graphical applications. These include:
Some AWT Components
- Frame: Serves as the primary window container.
- Label: Used to show fixed, non-editable text.
- TextField: Enables user text input.
- Button, Checkbox, Scrollbar, and various others.
All of these elements are part of the java.awt
package and act as the essential tools for constructing simple GUI programs. However, because AWT components rely on the native graphical resources of the operating system, they can lack consistency and offer limited flexibility when running across different platforms.
Swing: is an advanced GUI toolkit built on top of AWT,
but it is a platform-independent. It offers more powerful and flexible components
such as JFrame
, JLabel
,
JButton
, and more located in the javax.swing
package.
Swing supports a rich set of features and is widely used for desktop applications.
Apart from the fundamental elements, Swing facilitates sophisticated features like pluggable look-and-feel, which allow programs to dynamically modify their visual appearance without compromising functionality. Additionally, it supports a variety of layout managers to effectively arrange components, double buffering for fluid graphics, and rich event handling. Because of these potent features, Swing is frequently used to create complex, responsive desktop apps that offer a flawless user experience.
Event Handling in AWT and Swing
An event is a change in the state of a component, triggered by user interaction such as clicking a button, typing on the keyboard, or selecting an item from a list.
Event Handling is the process of responding to these events. Java uses the Delegation Event Model to handle events in a structured way. This model includes:
Here is the step involved in event handling:
1. The User Takes Action
When the user interacts with a GUI element such as clicking a button, entering data in a text field, selecting an item from a list, or moving the mouse the process begins. This user action triggers an event. Every action type corresponds to a specific event type.
2. Creation of an Event Object
Once the action occurs, the system creates an object of the corresponding event class. For example, clicking a button generates an ActionEvent
object.
This event object contains essential information such as the source of the event, the time it occurred, and other context-specific data.
3. Event Object Is Passed to the Registered Listener
The event object is passed to the listener registered with the source component.
A listener is an object that implements the appropriate event listener interface, such as ActionListener
for an ActionEvent
.
The listener’s callback method like actionPerformed(ActionEvent e)
receives the event object.
Multiple listeners can be registered for the same event, and all will be notified when it occurs.
4. The Listener Reacts to the Event
The event-handling code is placed inside the listener’s callback method. This code defines how the program should respond to the event.
Common actions include:
- Updating the GUI (e.g., changing text, colors, or layout)
- Validating or verifying user input
- Starting or stopping processes
- Displaying messages or alerts to the user
After handling the event, the program resumes waiting for the next event.
Let us see the following simple GUI example:


package loginForm;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class LoginForm extends JFrame {
private JLabel username; // Labels
private JLabel password;
private JTextField txtusername; // Attribute declaration
private JPasswordField txtpassword;
private JButton login;
public LoginForm() { // Constructor
setTitle("Login"); // Title
username = new JLabel("User Name:");
password = new JLabel("Password:");
txtusername = new JTextField();
txtpassword = new JPasswordField();
login = new JButton("Login");
setLayout(null); // Custom layout
username.setBounds(10, 10, 200, 30);
txtusername.setBounds(100, 10, 200, 30);
password.setBounds(10, 50, 200, 30);
txtpassword.setBounds(100, 50, 200, 30);
login.setBounds(30, 100, 100, 30);
add(username);
add(password);
add(txtusername);
add(txtpassword);
add(login);
setSize(400, 200);
setLocation(400, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
ActionListener lis = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked!!");
}
};
login.addActionListener(lis);
}
public static void main(String[] args) {
LoginForm obj = new LoginForm();
}
}
Java Database Connectivity
Java Database Connectivity Java Database Connectivity (JDBC) is a specification that defines a standard Application Programming Interface(API) for Java applications to interact with database management systems. It enables developers to write Java applications that can:
- Connect to various databases
- Send SQL queries
- Retrieve and process results
The JDBC API comprises a collection of interfaces and classes in the Java language. Since JDBC is platform-independent, a single JDBC-based Java program can communicate with any DBMS that provides a compatible driver.
Setting Up JDBC in Java IDE
Here are steps that shows how to install and configure JDBC with java programming language:
- First, we have to install a DBMS. It can be MySQL, PostgreSQL, or another.
- Next, download the JDBC driver such as mysql-connector-java-5.1.12-bin.jar.
- Finally, add the driver to your Java IDE’s library or build path.
- Import required packages → import java.sql.*;
-
Load and register the driver
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver);
Note: The name of the driver class may vary depending on your DBMS. -
Establish a connection
String url = "jdbc:mysql://localhost:3306/oop";
String user = "root";
String password = "yilm2721";
Connection con = DriverManager.getConnection(url, user, password); - Create a statement
Statement stmt = con.createStatement(); - Execute SQL query
String query = "SELECT * FROM employee";
ResultSet rs = stmt.executeQuery(query); - Process the result set
while (rs.next()) {
String name = rs.getString("name");
System.out.println(name);
} - Close resources
stmt.close(); con.close();
In general,the following classes are esential during JDBC to java connectivity
- import java.sql.DriverManager;
- import java.sql.Connection;
- import java.sql.Statement;
- import java.sql.ResultSet;
How to create Table in Java?
In Java, the JTable class from the Swing framework is frequently used to generate tables. There are two main methods for making a table:
-
Direct JTable constructor:by directly passing the data and column names as arrays to the JTable constructor, you can create a table.
Steps- Create a two-dimensional
Object
array for the rows, with a row of data represented by each inner array. - For the column headers, create a one-dimensional
String
array. - Use these arrays to create the
JTable
. - To improve display, you can optionally set the viewport height and desired size.
- If there is more content than what can be shown, wrap the table inside a
JScrollPane
to allow scrolling. - Insert the scroll pane (such as into a
JFrame
orJPanel
) into the container.
Example- Object[][] rows = new Object[][]{{1,"ff"},{2,"gg"}};
- String[] columns = new String[]{"id","name"};
JTable table = new JTable(rows, columns); table.setPreferredScrollableViewportSize(new Dimension(400, 300)); table.setFillsViewportHeight(true); JScrollPane pane = new JScrollPane(table); add(pane);
- Using DefaultTableModel: a more adaptable method of managing table data is offered by the DefaultTableModel. Once the table has been built, it enables you to dynamically add, remove, or alter rows.
Example- Object[][] rows = new Object[][]{{1,"ff"},{2,"gg"}};
- String[] columns = new String[]{"id","name"};
DefaultTableModel model = new DefaultTableModel(rows, columns); JTable table = new JTable(model); table.setFillsViewportHeight(true); JScrollPane pane = new JScrollPane(table); add(pane);
- Create a two-dimensional