Creating a graphical user interface (GUI)
Task for the project. Continue to refine Assignment 5.
1. Explore the Swing library for graphic design. You need to redesign your project using
graphic design. Your project should have functions such as creating, adding, changing
and deleting data.
2. Connect your project to a database for storing and processing data. I suggest using
MySQL.
Tasks:
Creating a Simple GUI Using Components
Swing.
Handling events that interact with user interface elements.
Work with layouts to organize the layout of components.
Project setup
Create a new Java project in your IDE.
Make sure the project is configured to use JDK 8 or higher.
Creating a GUI
Create a Main class that will contain the main method.
Import the required packages:
Example 1
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
Create a GUI class to create a GUI:
public class GUI extends JFrame {
private JButton button;
private JLabel label;
public GUI() {
setTitle("Sample app by Swing");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
button = new JButton("Push me!");
1
label = new JLabel("Text");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("Button is clicked!");
}
});
add(button);
add(label);
setVisible(true);
}
public static void main(String[] args) {
GUI gui = new GUI();
}
}
Run the application to ensure that the GUI is working properly.
Try pressing the button and make sure that the text on the label changes.
Example 2
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class AdvancedGUI extends JFrame {
private JTextField inputField;
private JButton submitButton;
private JTextArea outputArea;
private JComboBox<String> comboBox;
public AdvancedGUI() {
setTitle("Advanced Swing Application");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel topPanel = new JPanel();
topPanel.setLayout(new FlowLayout());
JLabel inputLabel = new JLabel("Input:");
2
inputField = new JTextField(15);
submitButton = new JButton("Submit");
topPanel.add(inputLabel);
topPanel.add(inputField);
topPanel.add(submitButton);
add(topPanel, BorderLayout.NORTH);
outputArea = new JTextArea();
outputArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(outputArea);
add(scrollPane, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout());
JLabel selectLabel = new JLabel("Select:");
String[] options = {"Option 1", "Option 2", "Option 3"};
comboBox = new JComboBox<>(options);
bottomPanel.add(selectLabel);
bottomPanel.add(comboBox);
add(bottomPanel, BorderLayout.SOUTH);
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String inputText = inputField.getText();
outputArea.append("Input: " + inputText + "\n");
inputField.setText("");
}
});
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selectedOption = (String) comboBox.getSelectedItem();
outputArea.append("Selected: " + selectedOption + "\n");
}
});
setVisible(true);
}
public static void main(String[] args) {
AdvancedGUI gui = new AdvancedGUI();
3
}
}
1. JTextField for text input.
2. JButton to send the entered text.
3. JTextArea to display the output.
4. JComboBox to select an option.
5. Event handlers for the button and drop-down list.
Database
Objective: To familiarize students with the basics of working with databases in Java using the
MySQL database management system. The assignment includes creating a database, writing a
Java application to connect to the database, execute basic queries (SELECT, INSERT, UPDATE,
DELETE), and testing the application.
Steps to be followed:
1. Creating the database and table:
Create a MySQL database named "university" and a table named "students". The table should
have the following fields:
id (type INT, auto-increment) - student ID
name (type VARCHAR) - student name
age (type INT) - student age
major (type VARCHAR) - student's major
2. Writing the Java application:
Write a Java application that performs the following actions:
Connects to the MySQL database.
Retrieves and displays all students from the table.
Adds a new student to the table.
Updates student information.
Deletes a student from the table.
3. Testing the application:
Test your application by running it and verifying the results of the operations. Ensure that all
operations are executed correctly and without errors.
Notes:
Use JDBC to connect to the database.
Handle exceptions that may occur during database operations.
Ensure security when executing database queries (e.g., use parameterized queries to
prevent SQL injection).
Provide documentation for your application, explaining how to run and use it.
4
Sample Code:
Below is a sample Java code for connecting to the MySQL database and executing queries:
import java.sql.*;
public class Main {
private static final String URL = "jdbc:mysql://localhost:3306/university";
private static final String USER = "root";
private static final String PASSWORD = "password";
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection(URL, USER,
PASSWORD);
Statement statement = connection.createStatement()) {
// Display all students
System.out.println("List of students:");
ResultSet resultSet = statement.executeQuery("SELECT * FROM students");
while (resultSet.next()) {
System.out.println("ID: " + resultSet.getInt("id") +
", Name: " + resultSet.getString("name") +
", Age: " + resultSet.getInt("age") +
", Major: " + resultSet.getString("major"));
}
// Add a new student
String insertQuery = "INSERT INTO students (name, age, major) VALUES ('John',
20, 'Computer Science')";
int rowsInserted = statement.executeUpdate(insertQuery);
if (rowsInserted > 0) {
System.out.println("New student added successfully.");
}
// Update student information
String updateQuery = "UPDATE students SET age = 21 WHERE name = 'John'";
int rowsUpdated = statement.executeUpdate(updateQuery);
if (rowsUpdated > 0) {
System.out.println("Student information updated successfully.");
}
// Delete a student
String deleteQuery = "DELETE FROM students WHERE name = 'John'";
int rowsDeleted = statement.executeUpdate(deleteQuery);
if (rowsDeleted > 0) {
System.out.println("Student deleted successfully.");
}
5
} catch (SQLException e) {
e.printStackTrace();
}
}
}