Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
61 views14 pages

Java GUI Elements & Event Handling

Uploaded by

nihalsayyad147
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views14 pages

Java GUI Elements & Event Handling

Uploaded by

nihalsayyad147
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Experiment 13

Title: Demonstrating GUI Elements and Event Handling in Java

Introduction:

This Java program showcases various graphical user interface (GUI) elements,

including buttons, text fields, check boxes, radio buttons, and toggle buttons,

while also demonstrating event handling in a Java application. These GUI

elements are implemented using Swing, a Java GUI toolkit.

Theory Points:

1. Graphical User Interface (GUI):

Graphical User Interface (GUI) is a visual way for users to interact with software

applications. GUI elements, such as buttons, text fields, check boxes, radio

buttons, and toggle buttons, provide an intuitive and user-friendly means to input

data and interact with the program.

2. Swing in Java:

Swing is a set of GUI components and tools in Java used for building desktop

applications with rich, interactive user interfaces. It is part of the Java Foundation

Classes (JFC) and provides a wide range of GUI elements.

3. Event Handling in GUI:

Event handling is a critical aspect of GUI programming, enabling a program to

respond to user actions. In this program, we use event listeners to capture and

process events triggered by user interactions with the GUI elements.

4. Text Field:

- A text field is a GUI element used for capturing user input. In this program, a

text field is created using `JTextField`, allowing the user to type text.

- The `ActionListener` is used to handle text field events. When the "Click Me"

button is pressed, the text entered in the text field is retrieved, and a message

dialog displays it.

5. Button:

- A button is a common GUI element that triggers actions when clicked. In our

program, we create a button using `JButton`.

- The `ActionListener` is registered with the button to respond to button click


events. When the button is clicked, a message dialog is shown to the user.

6. Check Box:

- A check box is a binary input element that allows users to make choices. In this

program, a check box is created using `JCheckBox`.

- An `ItemListener` is registered with the check box to detect changes in its state. When the
check box is selected, a message dialog displays a corresponding message.

7. Radio Buttons:

- Radio buttons are used to select a single option from a group of options. We create radio
buttons using `JRadioButton`.

- To ensure that only one radio button can be selected at a time, a

`ButtonGroup` is used to group them. `ActionListeners` are registered with each

radio button to display messages when a radio button is selected.

8. Toggle Button:

- A toggle button is a GUI element that can be toggled on and off. In our program, we create
a toggle button using `JToggleButton`.

- An `ItemListener` is registered with the toggle button to detect state changes.

Depending on the state (on/off), a message dialog is displayed.

9. Code Structure:

- The program's code is structured in a `main` method within a `JFrame`.

- The GUI elements are created, event listeners are registered, and layout is defined using
`FlowLayout`.

- Message dialogs from `JOptionPane` are used to communicate with the user in response to
events.

Code and Output :

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class GUIElementsDemo {

public static void main(String[] args) {

JFrame frame = new JFrame("GUI Elements Demo");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400, 200);
frame.setLayout(new FlowLayout());

// Create a text field

JTextField textField = new JTextField(20);

frame.add(textField);

// Create a button

JButton button = new JButton("Click Me");

frame.add(button);

// Create a check box

JCheckBox checkBox = new JCheckBox("Check Me");

frame.add(checkBox);

// Create radio buttons

JRadioButton radio1 = new JRadioButton("Option 1");

JRadioButton radio2 = new JRadioButton("Option 2");

ButtonGroup radioGroup = new ButtonGroup();

radioGroup.add(radio1);

radioGroup.add(radio2);

frame.add(radio1);

frame.add(radio2);

// Create a toggle button

JToggleButton toggleButton = new JToggleButton("Toggle Me");

frame.add(toggleButton);

// Button click event

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

String text = textField.getText();

JOptionPane.showMessageDialog(frame, "Button Clicked!\nText: " +

text);

});

// Check box event

checkBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {

if (checkBox.isSelected()) {

JOptionPane.showMessageDialog(frame, "Check Box Checked!");

});

// Radio button events

radio1.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(frame, "Option 1 selected");

});

radio2.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(frame, "Option 2 selected");

} });

// Toggle button event

toggleButton.addItemListener(new ItemListener() {

public void itemStateChanged(ItemEvent e) {

if (toggleButton.isSelected()) {

JOptionPane.showMessageDialog(frame, "Toggle Button Toggled

On");

} else { JOptionPane.showMessageDialog(frame, "Toggle Button Toggled Off");

});

frame.setVisible(true);

}
Experiment 14

Title: Demonstrating Touch Mode and Menus with Event Handlers in Java*

Introduction:

This Java program illustrates the use of touch mode and menus in a Swing-based

graphical user interface (GUI). The program allows users to enable or disable

touch mode, and it features two menus, "File" and "Edit," with event handlers to

respond to user actions.

Theory Points:

1. Graphical User Interface (GUI):

Graphical User Interface (GUI) is a visual interface that allows users to interact

with software using visual elements like buttons, menus, and checkboxes.

2. Swing in Java:

Swing is a Java GUI toolkit that provides a rich set of components for creating

graphical user interfaces in Java applications.

3. Menus in GUI:

Menus are an essential component of GUIs, providing users with a hierarchical

structure for accessing various functionalities and options.

4. Touch Mode:

- Touch mode is a user interface feature commonly found in applications designed for
touchscreen devices. It offers larger buttons and controls for ease of use with touch input.

- In this program, a "Touch Mode" toggle is created as a `JCheckBoxMenuItem`

that allows users to switch between touch mode and standard mode.

5. Menu Creation:

- The program creates a menu bar (`JMenuBar`) to hold menus and menu items.

- Menus, such as "File" and "Edit," are created using `JMenu` components and added to the
menu bar.

6. Menu Items:

- Menu items, such as "Touch Mode," "Exit," "Cut," and "Copy," are created using
`JMenuItem` or `JCheckBoxMenuItem` components.

- Keyboard shortcuts (mnemonics) are set using `setMnemonic()` to providekeyboard access


to menu items.

7. Event Handling:
- Event handling is the process of responding to user actions, such as button

clicks and menu selections.

- Event listeners are attached to menu items and checkboxes to handle user

interactions.

8. Touch Mode Event Handling:

- An `ActionListener` is registered with the "Touch Mode" checkbox. When the

checkbox is clicked, the listener toggles touch mode and displays a message based

on the selected state.

9. File Menu Event Handling:

- The "Exit" menu item in the "File" menu has an `ActionListener` to exit the

program when selected.

10. Edit Menu Event Handling:

- The "Cut" and "Copy" menu items in the "Edit" menu have `ActionListeners` to

perform actions such as cutting and copying data.

Code And Output :

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

public class TouchModeDemo {

public static void main(String[] args) {

JFrame frame = new JFrame("Touch Mode Demo");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400, 300);

// Create a menu bar

JMenuBar menuBar = new JMenuBar();

// Create File menu

JMenu fileMenu = new JMenu("File");

fileMenu.setMnemonic(KeyEvent.VK_F); // Alt + F shortcut


menuBar.add(fileMenu);

// Create Edit menu

JMenu editMenu = new JMenu("Edit");

editMenu.setMnemonic(KeyEvent.VK_E); // Alt + E shortcut

menuBar.add(editMenu);

// Create Touch Mode switch in File menu

JCheckBoxMenuItem touchModeMenuItem = new

JCheckBoxMenuItem("Touch Mode");

touchModeMenuItem.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

if (touchModeMenuItem.isSelected()) {

// Perform actions for enabling Touch Mode

JOptionPane.showMessageDialog(frame, "Touch Mode Enabled");

} else {

// Perform actions for disabling Touch Mode

JOptionPane.showMessageDialog(frame, "Touch Mode Disabled");

}
Experiment 15

Title: Java Multi-Threading Example*

Introduction:

Multi-threading is a programming technique that allows concurrent execution of

tasks in a single process. In Java, it is implemented using the `Thread` class, which

enables you to create and manage threads. This program demonstrates multithreading by calculating
the factorials of multiple numbers concurrently.

Theory Points:

1. Multi-Threading:

- Multi-threading is a programming concept that allows multiple threads to run

concurrently within a single process.

- Threads are lightweight, independent units of execution that share the same

memory space but can run independently.

2. Java Threads:

- In Java, multi-threading is supported by the `java.lang.Thread` class.

- Threads are used for parallel execution of tasks, which can improve application

performance and responsiveness.

3. `main` Method:

- The `main` method is the entry point of a Java application and runs in the main

thread.

- The main thread is created automatically when the application starts.

4. Creating Threads:

- Threads can be created in Java by extending the `Thread` class or

implementing the `Runnable` interface.

- In this program, multiple threads are created by extending the `Thread` class.

5. `start()` Method:

- The `start()` method is called on a `Thread` object to initiate its execution.

- It internally calls the `run()` method, allowing the thread to start running.

6. `run()` Method:

- The `run()` method is overridden in the `Thread` subclass and contains the
code to be executed concurrently by the thread.

- In this program, the `run()` method calculates the factorial of a number and

displays the result.

7. Concurrent Execution:

- Multiple threads run concurrently, each calculating the factorial of a different

number.

- This concurrent execution can lead to better performance, especially in

applications with computationally intensive tasks that can be parallelized.

8. Thread Safety:

- In multi-threaded applications, thread safety is crucial to avoid data race

conditions and ensure correct results.

- Proper synchronization mechanisms, like `synchronized` blocks or locks, may

be needed to protect shared resources.

Code and output :

public class FactorialCalculator {

public static void main(String[] args) {

int[] numbers = {5, 6, 7, 8, 9};

for (int num : numbers) {

Thread thread = new FactorialThread(num);

thread.start();

class FactorialThread extends Thread {

private int number;

public FactorialThread(int number) {

this.number = number;

@Override

public void run() {


long factorial = calculateFactorial(number);

System.out.println("Factorial of " + number + " is " + factorial);

private long calculateFactorial(int n) {

if (n == 0 || n == 1) {

return 1;

} else {

long result = 1;

for (int i = 2; i <= n; i++) {

result *= i;

return result;

You might also like