Getting Started with Java GUI


Illustration showing Java GUI components

Java GUI

In java,Graphical User Interfacerefers to the visual components that make user interaction intuitive and seamless. Java offers built-in libraries like AWT and Swing to create graphical interfaces using elements such as buttons, labels, windows, and text fields.

  • Component: is A GUI element that has a graphical representation and can interact with the user. Examples include Button, Checkbox, and Scrollbar. All components in AWT extend from java.awt.Component.
  • Container: is a special type of component that can hold other components. It keeps a list of the child components it contains. Common containers include Panel, Frame, and Window.

Abstract Window Toolkit(AWT) and Swing

Abstract Window Toolkit: is a type of graphical user interface liberaries introduced by Sun Microsystems in 1995.This liberary is platform-dependent API for building GUI applications. It provides basic components such as Frame, Label, TextField, etc., found in the java.awt package.

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.

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:

  • Source: The object like a button that generates the event.
  • Listener: Also known as the event handler, it is an object that waits for events and executes a method when an event occurs.

Here is the step involved in event handling:

  1. The user performs an action (e.g., clicks a button), triggering an event.
  2. An object of the event class (like ActionEvent) is created and contains information about the event.
  3. This event object is passed to the appropriate method in the registered listener.
  4. The listener processes the event and executes the corresponding response.

Let us see the following simple GUI example:

Thumbnail for video tutorial on creating a login form in Java using Swing

Source code


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:"); //Object creation
       password = new JLabel("Password:");
       txtusername = new JTextField();
       txtpassword = new JPasswordField();
       login = new JButton("Login");
	   
       setLayout(null); //Setting custom layout
	   
       username.setBounds(10, 10, 200, 30);  //Setting pacement
       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); //putting component on a container
       add(password);
       add(txtusername);
       add(txtpassword);
       add(login);
       setSize(400,200); //Setting size of the window
       setLocation(400,150); //Setting location of the window
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Setting close operation
       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 (JDBC)

Java Database Connectivity is a JavaSoft specification that defines a standard API for Java programs to interact with database management systems (DBMS). 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:

  1. First,we have to install a DBMS.It can be MySQL,PostgreSQL,or other.
  2. Next,download the JDBC driver such as mysql-connector-java-5.1.12-bin.jar).
  3. Finally,Add the driver to your Java IDE’s library or build path.
  4. Import required packages → import java.sql.*;
  5. Load and register the driver String driver = "com.mysql.jdbc.Driver";
    Class.forName(driver);

    (Note:The name of Driver class may vary depending on your DBMS.)
  6. Establish a connection
    String url = "jdbc:mysql://localhost:3306/oop";
    String user = "root";
    String password = "yilm2721";
    Connection con = DriverManager.getConnection(url, user, password);
  7. Create a statement
    Statement stmt = con.createStatement();
  8. Execute SQL query
    String query = "SELECT * FROM employee";
    ResultSet rs = stmt.executeQuery(query);
  9. Process the result set
    while (rs.next()) {
    String name = rs.getString("name");
    System.out.println(name);
    }
  10. Close resources
    stmt.close(); con.close();

Generally,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 order to create table in java,we can use the following two methods:

  1. Direct JTable constructor:
    • 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);
  2. Using DefaultTableModel:
    • 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);
Yilma Goshime

I’m committed to providing tailored solutions and always ready to assist if any issue arises.

LetUsLearn