1. Write a GUI program using components to find sum and difference of two numbers.
Use
two text fields for giving input and a label for output. The program should display sum
if user presses mouse and difference if user release mouse.
Objectives:
To demonstrate the use of mouse events in Abstract Window Toolkit (AWT) by performing
arithmetic operations based on mouse interactions through implementation of the Mouse Listener
Interface.
Project Directory:
Source Code:
import java.awt.*;
import java.awt.event.*;
public class App implements MouseListener {
Label lblResult;
TextField txtFirstNumber;
TextField txtSecondNumber;
App() {
Frame frame = new Frame("Sum and Difference");
// Labels for instructions
Label lblFirst = new Label("Enter First Number:");
lblFirst.setBounds(20, 50, 130, 20);
txtFirstNumber = new TextField();
txtFirstNumber.setBounds(160, 50, 100, 20);
Label lblSecond = new Label("Enter Second Number:");
1
lblSecond.setBounds(20, 90, 130, 20);
txtSecondNumber = new TextField();
txtSecondNumber.setBounds(160, 90, 100, 20);
lblResult = new Label("Result will appear here");
lblResult.setBounds(20, 130, 200, 20);
// Add components
frame.add(lblFirst);
frame.add(txtFirstNumber);
frame.add(lblSecond);
frame.add(txtSecondNumber);
frame.add(lblResult);
// Mouse listener
frame.addMouseListener(this);
// Frame settings
frame.setSize(350, 250);
frame.setLayout(null);
frame.setVisible(true);
}
public static void main(String[] args) {
new App();
}
// Mouse events
@Override
public void mousePressed(MouseEvent e) {
try {
int first = Integer.parseInt(txtFirstNumber.getText());
int second = Integer.parseInt(txtSecondNumber.getText());
int sum = first + second;
lblResult.setText("Sum: " + sum);
} catch (NumberFormatException ex) {
lblResult.setText("Enter valid numbers!");
}
}
2
@Override
public void mouseReleased(MouseEvent e) {
try {
int first = Integer.parseInt(txtFirstNumber.getText());
int second = Integer.parseInt(txtSecondNumber.getText());
int diff = first - second;
lblResult.setText("Difference: " + diff);
} catch (NumberFormatException ex) {
lblResult.setText("Enter valid numbers!");
}
}
@Override public void mouseClicked(MouseEvent e) {}
@Override public void mouseEntered(MouseEvent e) {}
@Override public void mouseExited(MouseEvent e) {}
}
Output:
Conclusion:
This code successfully demonstrates handling of mouse events in Java using the Mouse Listener
interface. It shows how user interactions with the mouse can trigger specific actions in a GUI, such
as performing calculations and displaying results.
3
2. Write a Program using swing components to add two digits. Use text fields for inputs and
output. Your program should display the result when the user presses a button.
Objectives:
To perform basic arithmetic operations (addition, subtraction) programmatically based on user
interactions.
Project Directory:
Source Code:
import javax.swing.*;
import java.awt.event.*;
public class App implements ActionListener {
JTextField txtFirstNumber;
JTextField txtSecondNumber;
JButton btnSum;
JTextField txtResult;
JFrame frame = new JFrame();
public App() {
frame.setTitle("Two Number Calculator");
JLabel lblFirst = new JLabel("Enter First Number:");
lblFirst.setBounds(20, 20, 200, 25);
txtFirstNumber = new JTextField();
txtFirstNumber.setBounds(200, 20, 150, 25);
frame.add(lblFirst);
frame.add(txtFirstNumber);
JLabel lblSecond = new JLabel("Enter Second Number:");
lblSecond.setBounds(20, 60, 200, 25);
4
txtSecondNumber = new JTextField();
txtSecondNumber.setBounds(200, 60, 150, 25);
frame.add(lblSecond);
frame.add(txtSecondNumber);
btnSum = new JButton("Calculate Sum");
btnSum.setBounds(200, 100, 150, 25);
frame.add(btnSum);
btnSum.addActionListener(this);
JLabel lblOutput = new JLabel("Result:");
lblOutput.setBounds(20, 140, 200, 25);
txtResult = new JTextField();
txtResult.setBounds(200, 140, 150, 25);
frame.add(lblOutput);
frame.add(txtResult);
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
}
public static void main(String[] args) {
new App();
}
@Override
public void actionPerformed(ActionEvent e) {
int num1 = Integer.parseInt(txtFirstNumber.getText());
int num2 = Integer.parseInt(txtSecondNumber.getText());
int sum = num1 + num2;
txtResult.setText(String.valueOf(sum));
}
}
5
Output:
Conclusion:
This program demonstrates the use of GUI components and event handling in Java. It allows users
to input numbers, perform arithmetic operations, and display the result interactively, illustrating
basic concepts of user interaction and event-driven programming.
6
3. Write a program to create a Form Below using Swing and perform Add, Subtract,
Multiply and Divide as user click button with selected option.
Objectives:
To allow the user to input two numbers and select an arithmetic operation.
Project Directory:
Source Code:
import javax.swing.*;
import java.awt.event.*;
public class App implements ActionListener {
JTextField txtNum1;
JTextField txtNum2;
JComboBox<String> cmbOperation;
JButton btnCompute;
JTextField txtAnswer;
JFrame frame = new JFrame();
public App() {
frame.setTitle("Simple Calculator");
JLabel lblNum1 = new JLabel("Enter First Number:");
lblNum1.setBounds(20, 20, 200, 25);
txtNum1 = new JTextField();
txtNum1.setBounds(200, 20, 150, 25);
frame.add(lblNum1);
frame.add(txtNum1);
JLabel lblNum2 = new JLabel("Enter Second Number:");
lblNum2.setBounds(20, 60, 200, 25);
7
txtNum2 = new JTextField();
txtNum2.setBounds(200, 60, 150, 25);
frame.add(lblNum2);
frame.add(txtNum2);
JLabel lblOperation = new JLabel("Choose Operation:");
lblOperation.setBounds(20, 100, 200, 25);
String[] choices = {"Add", "Subtract", "Multiply", "Divide"};
cmbOperation = new JComboBox<>(choices);
cmbOperation.setBounds(200, 100, 150, 25);
frame.add(lblOperation);
frame.add(cmbOperation);
btnCompute = new JButton("Compute");
btnCompute.setBounds(200, 140, 150, 25);
frame.add(btnCompute);
btnCompute.addActionListener(this);
JLabel lblResult = new JLabel("Result:");
lblResult.setBounds(20, 180, 200, 25);
txtAnswer = new JTextField();
txtAnswer.setBounds(200, 180, 150, 25);
frame.add(lblResult);
frame.add(txtAnswer);
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
}
public static void main(String[] args) {
new App();
}
@Override
public void actionPerformed(ActionEvent e) {
int num1 = Integer.parseInt(txtNum1.getText());
int num2 = Integer.parseInt(txtNum2.getText());
String selected = (String) cmbOperation.getSelectedItem();
int ans = 0;
8
switch (selected) {
case "Add":
ans = num1 + num2;
break;
case "Subtract":
ans = num1 - num2;
break;
case "Multiply":
ans = num1 * num2;
break;
case "Divide":
if (num2 != 0) {
ans = num1 / num2;
} else {
JOptionPane.showMessageDialog(null, "Cannot divide by zero!");
return;
}
break;
}
txtAnswer.setText(String.valueOf(ans));
}
}
Output:
Conclusion:
This program demonstrates the use of Swing components and event-driven programming in Java.
It allows users to input numbers, select an operation, and see the result interactively, highlighting
the practical application of GUI design and user interaction.
9
4. Write a GUI program using components to find sum and difference of two numbers. Use
two text fields for giving input and a label for output. The program should display sum
if user presses mouse and difference if user release mouse using adapter class.
Objectives:
To perform arithmetic operations (sum and difference) based on mouse events.
Project Directory:
Source Code:
import javax.swing.*;
import java.awt.event.*;
public class App {
JLabel lblFirst, lblSecond, lblResult;
JTextField txtFirst, txtSecond, txtResult;
JFrame frame = new JFrame("Mouse Adapter Example");
public App() {
// Labels
lblFirst = new JLabel("Enter First Number:");
lblFirst.setBounds(10, 10, 200, 20);
txtFirst = new JTextField();
txtFirst.setBounds(150, 10, 200, 20);
lblSecond = new JLabel("Enter Second Number:");
lblSecond.setBounds(10, 40, 200, 20);
txtSecond = new JTextField();
txtSecond.setBounds(150, 40, 200, 20);
lblResult = new JLabel("Result:");
10
lblResult.setBounds(10, 70, 200, 20);
txtResult = new JTextField();
txtResult.setBounds(150, 70, 200, 20);
// Add mouse listener to result text field
txtResult.addMouseListener(new MouseHandler());
// Add components to frame
frame.add(lblFirst); frame.add(txtFirst);
frame.add(lblSecond); frame.add(txtSecond);
frame.add(lblResult); frame.add(txtResult);
// Frame settings
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
}
// Inner class for mouse handling
class MouseHandler extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
try {
int num1 = Integer.parseInt(txtFirst.getText());
int num2 = Integer.parseInt(txtSecond.getText());
int sum = num1 + num2;
txtResult.setText(String.valueOf(sum));
} catch (NumberFormatException ex) {
txtResult.setText("Invalid Input!");
}
}
@Override
public void mouseReleased(MouseEvent e) {
try {
int num1 = Integer.parseInt(txtFirst.getText());
int num2 = Integer.parseInt(txtSecond.getText());
int diff = num1 - num2;
txtResult.setText(String.valueOf(diff));
} catch (NumberFormatException ex) {
11
txtResult.setText("Invalid Input!");
}
}
}
public static void main(String[] args) {
new App();
}
}
Output:
Conclusion:
This program demonstrates how mouse events can trigger arithmetic operations in a Java Swing
GUI. It shows how users can interact with the interface, and how event handling using Mouse
Adapter can dynamically perform calculations and display results.
12
5. Create a Simple Login Form using Grid Layout in Java.
Objectives:
To implement event handling using Action Listener to respond to button clicks and perform
validation.
Project Directory:
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class App {
public static void main(String[] args) {
JFrame frame = new JFrame("Login Form");
frame.setLayout(new GridLayout(3, 2, 10, 10));
JLabel lblUsername = new JLabel("Username:");
JLabel lblPassword = new JLabel("Password:");
JTextField txtUsername = new JTextField();
JPasswordField txtPassword = new JPasswordField();
JButton btnLogin = new JButton("Login");
// Add components to frame
frame.add(lblUsername);
frame.add(txtUsername);
frame.add(lblPassword);
frame.add(txtPassword);
13
frame.add(new JLabel("")); // Empty label for spacing
frame.add(btnLogin);
// Login button action
btnLogin.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String user = txtUsername.getText();
String pass = new String(txtPassword.getPassword());
if(user.equals("Risap") && pass.equals("1234")) {
JOptionPane.showMessageDialog(frame, "Login Successful!");
} else {
JOptionPane.showMessageDialog(frame, "Invalid Username or Password");
}
}
});
frame.setSize(400, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); // Center on screen
frame.setVisible(true);
}
}
Output:
Conclusion:
This program demonstrates the creation of a login form using Java Swing and Grid Layout. It
shows how to handle user input, validate credentials, and provide interactive feedback, illustrating
fundamental concepts of GUI design and event-driven programming in Java.
14
6. Create a Simple Login Form using GridBagLayout in Java.
Objectives:
To understand and implement the GridBagLayout manager and GridBagConstraints for flexible
and precise component placement.
Project Directory:
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class App {
public static void main(String[] args) {
JFrame frame = new JFrame("Login Form");
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10); // Padding around components
// Username Label
JLabel lblUser = new JLabel("Username:");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.EAST;
frame.add(lblUser, gbc);
// Username Field
JTextField txtUser = new JTextField(15);
gbc.gridx = 1;
gbc.gridy = 0;
15
gbc.anchor = GridBagConstraints.WEST;
frame.add(txtUser, gbc);
// Password Label
JLabel lblPass = new JLabel("Password:");
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.EAST;
frame.add(lblPass, gbc);
// Password Field
JPasswordField txtPass = new JPasswordField(15);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.WEST;
frame.add(txtPass, gbc);
// Login Button
JButton btnLogin = new JButton("Login");
gbc.gridx = 1;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.CENTER;
frame.add(btnLogin, gbc);
// Button Action
btnLogin.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String user = txtUser.getText();
String pass = new String(txtPass.getPassword());
if(user.equals("Risap") && pass.equals("1234")) {
JOptionPane.showMessageDialog(frame, "Login Successful!");
} else {
JOptionPane.showMessageDialog(frame, "Invalid Username or Password");
txtUser.setText(""); // Clear fields on failure
txtPass.setText("");
txtUser.requestFocus();
}
}
16
});
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); // Center on screen
frame.setVisible(true);
}
}
Output:
Conclusion:
This program demonstrates the use of Swing components and the GridBagLayout manager to
create a responsive and organized login form. It highlights how to handle user input, validate
credentials, and provide interactive feedback, emphasizing the principles of event-driven
programming and user-friendly GUI design in Java.
17
7. Write a program that divides the frame into five regions by using border layout and then
add panels in the east, north and center region. Finally add some descriptive label in the
north panel, buttons with icon in the east panel and a sample form in the center panel.
You can further subdivide the center panel, if necessary. Prepare a program with three
text boxes First Number, Second Number, and Result and four buttons add, subtract,
multiply and divide. Handle the events to perform the required operation and display
results.
Objectives:
To create a simple calculator using Java Swing that performs basic arithmetic operations (addition,
subtraction, multiplication, and division) through a graphical user interface.
Project Directory:
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class App implements ActionListener {
JTextField txtFirst;
JTextField txtSecond;
JTextField txtOutput;
public App() {
JFrame frame = new JFrame("Calculator");
frame.setSize(600, 400);
frame.setLayout(new BorderLayout(10, 10));
// Top Panel
JPanel topPanel = new JPanel();
18
JLabel lblTitle = new JLabel("Simple Calculator");
lblTitle.setFont(new Font("Arial", Font.BOLD, 20));
topPanel.add(lblTitle);
frame.add(topPanel, BorderLayout.NORTH);
// Right Panel with Buttons
JPanel btnPanel = new JPanel(new GridLayout(5, 1, 15, 15));
JButton btnAdd = new JButton("Add");
JButton btnSub = new JButton("Subtract");
JButton btnMul = new JButton("Multiply");
JButton btnDiv = new JButton("Divide");
btnAdd.addActionListener(this);
btnSub.addActionListener(this);
btnMul.addActionListener(this);
btnDiv.addActionListener(this);
btnPanel.add(btnAdd);
btnPanel.add(btnSub);
btnPanel.add(btnMul);
btnPanel.add(btnDiv);
frame.add(btnPanel, BorderLayout.EAST);
// Center Panel with Inputs
JPanel formPanel = new JPanel(new GridLayout(4, 2, 15, 15));
formPanel.setBorder(BorderFactory.createTitledBorder("Calculator Form"));
formPanel.add(new JLabel("Enter First Number:"));
txtFirst = new JTextField();
formPanel.add(txtFirst);
formPanel.add(new JLabel("Enter Second Number:"));
txtSecond = new JTextField();
formPanel.add(txtSecond);
formPanel.add(new JLabel("Result:"));
txtOutput = new JTextField();
formPanel.add(txtOutput);
19
frame.add(formPanel, BorderLayout.CENTER);
// Frame settings
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new App();
}
@Override
public void actionPerformed(ActionEvent e) {
try {
int val1 = Integer.parseInt(txtFirst.getText());
int val2 = Integer.parseInt(txtSecond.getText());
int ans = 0;
switch (e.getActionCommand()) {
case "Add":
ans = val1 + val2;
break;
case "Subtract":
ans = val1 - val2;
break;
case "Multiply":
ans = val1 * val2;
break;
case "Divide":
if (val2 != 0) {
ans = val1 / val2;
} else {
JOptionPane.showMessageDialog(null, "Cannot divide by zero!");
return;
}
break;
}
txtOutput.setText(String.valueOf(ans));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Please enter valid numbers!");
20
}
}
}
Output:
Conclusion:
The program successfully demonstrates the use of Java Swing components, event handling, and
layout management to build a functional calculator. It allows users to enter two numbers and
perform basic operations with proper error handling for division by zero. This project highlights
how GUI programming in Java can be used to create user-friendly and efficient desktop
applications.
21
8. Design a form with three buttons with captions “RED,” “BLUE,” and “GREEN,”
respectively. Then write a program to handle the event such that when the user clicks the
button, the color of that button will be the same as its caption.
Objectives:
To dynamically change the appearance of buttons (background and foreground color) based on
user input.
Project Directory:
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class App {
public static void main(String[] args) {
JFrame win = new JFrame("Color Buttons Example");
JButton btnRed = new JButton("RED");
JButton btnBlue = new JButton("BLUE");
JButton btnGreen = new JButton("GREEN");
btnRed.setBounds(50, 50, 100, 40);
btnBlue.setBounds(160, 50, 100, 40);
btnGreen.setBounds(270, 50, 100, 40);
btnRed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnRed.setBackground(Color.RED);
btnRed.setForeground(Color.WHITE);
}
});
22
btnBlue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnBlue.setBackground(Color.BLUE);
btnBlue.setForeground(Color.WHITE);
}
});
btnGreen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnGreen.setBackground(Color.GREEN);
btnGreen.setForeground(Color.BLACK);
}
});
win.add(btnRed);
win.add(btnBlue);
win.add(btnGreen);
win.setSize(450, 200);
win.setLayout(null);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setVisible(true);
}
}
Output:
Conclusion:
This program demonstrates how to create an interactive GUI where button clicks trigger changes
in the interface. It highlights the use of Swing components and event handling to dynamically
update button colors based on user actions, illustrating core concepts of user interaction and event-
driven programming in Java.
23
9. Write a Java program using Swing that demonstrates the use of different layout
managers (Flow Layout, Grid Layout, and Border Layout).
• Divide the main frame into three panels using Border Layout:
o North Panel: Use Flow Layout to arrange three labels (Name, Roll No, Class) in a
single row.
o Center Panel: Use Grid Layout (3x2) to create a simple login form with two text
fields (Username, Password), a J Check Box (“Remember Me”), and a J Button
(“Login”).
o South Panel: Use Flow Layout to add two buttons (Reset and Exit).
• Handle events so that:
o When Login is pressed, display the entered username in a message dialog.
o When Reset is pressed, clear the text fields.
o When Exit is pressed, close the program.
Objectives:
To implement event handling using Action Listener for buttons like Login, Reset, and Exit.
Project Directory:
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class App{
public static void main(String[] args) {
JFrame frame = new JFrame("Layout Manager EXAMPLE");
frame.setLayout(new BorderLayout(10, 10));
JPanel northPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
24
northPanel.add(new JLabel("Name: Risap"));
northPanel.add(new JLabel("Roll No: 20"));
northPanel.add(new JLabel("Class: BCA"));
frame.add(northPanel, BorderLayout.NORTH);
JPanel centerPanel = new JPanel(new GridLayout(3, 2, 10, 10));
JLabel userLabel = new JLabel("Username:");
JTextField userField = new JTextField();
JLabel passLabel = new JLabel("Password:");
JPasswordField passField = new JPasswordField();
JCheckBox rememberMe = new JCheckBox("Remember Me");
JButton loginBtn = new JButton("Login");
centerPanel.add(userLabel);
centerPanel.add(userField);
centerPanel.add(passLabel);
centerPanel.add(passField);
centerPanel.add(rememberMe);
centerPanel.add(loginBtn);
frame.add(centerPanel, BorderLayout.CENTER);
JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
JButton resetBtn = new JButton("Reset");
JButton exitBtn = new JButton("Exit");
southPanel.add(resetBtn);
southPanel.add(exitBtn);
frame.add(southPanel, BorderLayout.SOUTH);
loginBtn.addActionListener(e -> {
String username = userField.getText();
JOptionPane.showMessageDialog(frame, "Logged in as: " + username);
});
resetBtn.addActionListener(e -> {
userField.setText("");
passField.setText("");
rememberMe.setSelected(false);
});
exitBtn.addActionListener(e -> System.exit(0));
frame.setSize(400, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); // center of screen
frame.setVisible(true);
}
25
}
Output:
Conclusion:
This program effectively demonstrates the use of multiple layout managers in Java Swing to design
a structured and interactive GUI. It highlights how different layouts can organize components,
handle user input, and provide dynamic responses, emphasizing the principles of event-driven
programming and user-friendly interface design.
26
10. Design a form with three buttons with captions “Circle,” “Square,” and “Triangle.”
• When the user clicks the “Circle” button, draw a red circle in the center of the frame.
• When the user clicks the “Square” button, draw a blue square in the center of the
frame.
• When the user clicks the “Triangle” button, draw a green triangle in the center of the
frame.
Objectives:
To design an interactive form with buttons labeled Circle, Square, and Triangle.
Project Directory:
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class App extends JFrame {
private String selectedShape = "";
// Custom panel for drawing
class ShapeCanvas extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int w = getWidth();
int h = getHeight();
int size = Math.min(w, h) / 2;
int x = (w - size) / 2;
int y = (h - size) / 2;
27
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(3));
switch (selectedShape) {
case "Circle":
g2.setColor(Color.RED);
g2.fillOval(x, y, size, size);
break;
case "Square":
g2.setColor(Color.BLUE);
g2.fillRect(x, y, size, size);
break;
case "Triangle":
g2.setColor(Color.GREEN);
int[] xPoints = {w / 2, x, x + size};
int[] yPoints = {y, y + size, y + size};
g2.fillPolygon(xPoints, yPoints, 3);
break;
}
}
}
public App() {
setTitle("Shape Drawer Example");
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// Drawing area
ShapeCanvas canvas = new ShapeCanvas();
add(canvas, BorderLayout.CENTER);
// Button panel
JPanel controls = new JPanel();
JButton btnCircle = new JButton("Circle");
JButton btnSquare = new JButton("Square");
JButton btnTriangle = new JButton("Triangle");
controls.add(btnCircle);
28
controls.add(btnSquare);
controls.add(btnTriangle);
add(controls, BorderLayout.SOUTH);
// Button actions
btnCircle.addActionListener(e -> {
selectedShape = "Circle";
canvas.repaint();
});
btnSquare.addActionListener(e -> {
selectedShape = "Square";
canvas.repaint();
});
btnTriangle.addActionListener(e -> {
selectedShape = "Triangle";
canvas.repaint();
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new App().setVisible(true));
}
}
Output:
Conclusion:
This program demonstrates how to create an interactive GUI that responds to button clicks by
drawing different shapes. It highlights the use of Swing components, custom painting, and event
handling, providing a clear example of dynamic graphical rendering and user interaction in Java.
29