0% found this document useful (0 votes)
21 views11 pages

CSL 203 Oops Lab 12,13

The document describes two Java programs: a simple calculator and a traffic light simulation using Java Swing. The calculator program allows basic arithmetic operations and handles exceptions like divide by zero, while the traffic light program uses radio buttons to display messages based on user selection of red, yellow, or green lights. Both programs successfully execute and produce the expected output.

Uploaded by

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

CSL 203 Oops Lab 12,13

The document describes two Java programs: a simple calculator and a traffic light simulation using Java Swing. The calculator program allows basic arithmetic operations and handles exceptions like divide by zero, while the traffic light program uses radio buttons to display messages based on user selection of red, yellow, or green lights. Both programs successfully execute and produce the expected output.

Uploaded by

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

Result:

The program to implement thread synchronization is successfully executed and output is obtained.
Exp No 12
Date :
SIMPLE CALCULATOR USING JAVA SWING

Aim:

Write a Java program that works as a simple calculator. Arrange Buttons for digits and the + - * %
operations properly. Add a text field to display the result. Handle any possible exceptions like divide by
zero.
.
Theory :
Java Swing is a GUI (graphical user Interface) widget toolkit for Java. Java Swing is a part of Oracle’s
Java foundation classes . Java Swing is an API for providing graphical user interface elements to Java
Programs.Swing was created to provide more powerful and flexible components than Java AWT
(Abstract Window Toolkit).
The methods used in the program :

1. add(Component c) : adds component to container.


2. addActionListenerListener(ActionListener d) : add actionListener for specified component
3. setBackground(Color c) : sets the background color of the specified container
4. setSize(int a, int b) : sets the size of container to specified dimensions.
5. setText(String s) : sets the text of the label to s.
6. getText() : returns the text of the label.

Algorithm:
Step 1 − Import the necessary header files.
Step 2 : Define a class “Calculator” by inheriting the properties of a JFrame class and implementing
ActionListener interface.
Step 2.1 :Inside the class, create a frame, textfield and variables to store operators and operands.
And a default constructor is defined.
Step 3 : Inside the main method,
Step 3.1 :Create a Jframe which is named ‘Calculator’. Inside the try, set the pluggable look and
feel while displaying on screen and catch is used to handle the exception if present.
Step 3.2 : First create an object for the class. Secondly create another object of the JFrame class
and set the textfield to non editable.
Step 3.3 : Create objects of all the components that we want to add to our window like buttons
from 0 to 9, buttons for arithmetic operations, buttons for equal & dot operator. Create a panel for
displaying.
Step 3.4 : To implement the ActionListener interface in the class , register ActionListener for all
the buttons using addActionListener().
Step 3.5 : Using the add() method add buttons to the panel and add panel to the frame. Set the
remaining properties of each component like setting their size, location and after setting their
properties add them to the frame(Window).
Step 4 : Inside the actionPerformed()
Step 4.1 : All the actions that the user wants in response when a button is clicked will be coded
inside the actionPerformed() method in that class.
Step 4.2 : Include all the conditions for getting all the calculator operations. Set a condition to
click on the equals(=) button to get the result.
Step 5 : Stop.

PROGRAM:

// Java program to create a simple calculator


// with basic +, -, /, * using java swing elements

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
class calculator extends JFrame implements ActionListener {
// create a frame
static JFrame f;

// create a textfield
static JTextField l;

// store operator and operands


String s0, s1, s2;

// default constructor
calculator()
{
s0 = s1 = s2 = "";
}

// main function
public static void main(String args[])
{
// create a frame
f = new JFrame("calculator");

try {
// set look and feel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.err.println(e.getMessage());
}

// create a object of class


calculator c = new calculator();

// create a textfield
l = new JTextField(16);

// set the textfield to non editable


l.setEditable(false);

// create number buttons and some operators


JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq, beq1;

// create number buttons


b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");

// equals button
beq1 = new JButton("=");

// create operator buttons


ba = new JButton("+");
bs = new JButton("-");
bd = new JButton("/");
bm = new JButton("*");
beq = new JButton("C");

// create . button
be = new JButton(".");

// create a panel
JPanel p = new JPanel();
// add action listeners
bm.addActionListener(c);
bd.addActionListener(c);
bs.addActionListener(c);
ba.addActionListener(c);
b9.addActionListener(c);
b8.addActionListener(c);
b7.addActionListener(c);
b6.addActionListener(c);
b5.addActionListener(c);
b4.addActionListener(c);
b3.addActionListener(c);
b2.addActionListener(c);
b1.addActionListener(c);
b0.addActionListener(c);
be.addActionListener(c);
beq.addActionListener(c);
beq1.addActionListener(c);

// add elements to panel


p.add(l);
p.add(ba);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(bs);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(bm);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(bd);
p.add(be);
p.add(b0);
p.add(beq);
p.add(beq1);

// set Background of panel


p.setBackground(Color.blue);

// add panel to frame


f.add(p);
f.setSize(200, 220);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();

// if the value is a number


if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') || s.charAt(0) == '.') {
// if operand is present then add to second no
if (!s1.equals(""))
s2 = s2 + s;
else
s0 = s0 + s;

// set the value of text


l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == 'C') {
// clear the one letter
s0 = s1 = s2 = "";

// set the value of text


l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == '=') {

double te;

// store the value in 1st


if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));

// set the value of text


l.setText(s0 + s1 + s2 + "=" + te);

// convert it to string
s0 = Double.toString(te);

s1 = s2 = "";
}
else {
// if there was no operand
if (s1.equals("") || s2.equals(""))
s1 = s;
// else evaluate
else {
double te;

// store the value in 1st


if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));

// convert it to string
s0 = Double.toString(te);

// place the operator


s1 = s;

// make the operand blank


s2 = "";
}

// set the value of text


l.setText(s0 + s1 + s2);
}
}
}
Output :

Result:

The program that works as a simple calculator using java swing is successfully executed and output is
obtained.
Exp No 13
Date :

TRAFFIC LIGHT USING JAVA SWING

Aim:

Write a Java program that simulates a traffic light. The program lets the user select one of three lights: red,
yellow, or green. When a radio button is selected, the light is turned on, and only one light can be on at a
time. No light is on when the program starts.

Theory :

Swing in java is part of the Java foundation class which is lightweight and platform independent. It is used
for creating window based applications. It includes components like buttons, scroll bar, text field etc.
Putting together all these components makes a graphical user interface.

Java ItemListener Interface


The Java ItemListener is notified whenever you click on the checkbox. It is notified against ItemEvent. The
ItemListener interface is found in java.awt.event package. It has only one method: itemStateChanged().

itemStateChanged() method
The itemStateChanged() method is invoked automatically whenever you click or unclick on the registered
checkbox component.

Here Creating a Button Group such that it contains three radio buttons Red, Yellow, Green when red is
clicked display “Stop”, when yellow is clicked display “ready”, when the green button is clicked Display
“Go”.
Algorithm:

Step 1 − Import the necessary header files.


Step 2 : Define a class “App” by inheriting the properties of a JFrame class and implementing ItemListener
interface.
Step 2.1 :Inside the class, create a frame, message label, button group and two panel named
messageContainer, lightsContainer.
Step 3 : Inside the constructor App,
Step 3.1 : Set up the font as per the user choice. Set the frame name as ‘Traffic Lights’. Then set
the message label “Select light”.
Step 3.2 : Set three radio button groups- red green yellow. For each button the foreground color is
set respectively.
Step 3.3 :To implement the ItemListener interface in the class , register ItemListener for all the
buttons using addItemListener().
Step 3.4 : Using the add() method, add buttons to the container and add the containers to the frame.
Set the remaining properties of each component like setting their size, visibility and add them to
the frame(Window).
Step 4 : Inside the itemStateChanged(),
Step 4.1 : Based on the input obtained by clicking the radio button. 3 types of messages can be
displayed onto the display screen as traffic signal rule.
Step 4.2 : If the radio button clicked is red, then display the message “STOP” with foreground
color ‘red’.
Step 4.3 : If the radio button clicked is yellow, then display the message “READY” with foreground
color ‘yellow’.
Step 4.4 : If the radio button clicked is green, then display the message “GO” with foreground color
‘green’.
Step 5 : Inside the main class TrafficLight, create the main method and create an object of the App class
inside the main method.
Step 6 : Stop.

PROGRAM:

import java.awt.Color;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
class App extends JFrame implements ItemListener
{
JFrame actualWindow;
JPanel messageContainer, lightsContainer;
JLabel message;
ButtonGroup btn_group;
JRadioButton rb_red, rb_yellow, rb_green;
App ()
{
Font myFont = new Font ("Verdana", Font.BOLD, 30);
actualWindow = new JFrame ("Traffic Lights");
messageContainer = new JPanel ();
lightsContainer = new JPanel ();
message = new JLabel ("Select Light");
btn_group = new ButtonGroup ();
rb_red = new JRadioButton ("Red");
rb_yellow = new JRadioButton ("Yellow");
rb_green = new JRadioButton ("Green");
actualWindow.setLayout (new GridLayout (2, 1));
message.setFont (myFont);
rb_red.setForeground (Color.RED);
rb_yellow.setForeground (Color.YELLOW);
rb_green.setForeground (Color.GREEN);
btn_group.add (rb_red);
btn_group.add (rb_yellow);
btn_group.add (rb_green);
rb_red.addItemListener (this);
rb_yellow.addItemListener (this);
rb_green.addItemListener (this);
messageContainer.add (message);
lightsContainer.add (rb_red);
lightsContainer.add (rb_yellow);
lightsContainer.add (rb_green);
actualWindow.add (messageContainer);
actualWindow.add (lightsContainer);
actualWindow.setSize (300, 200);
actualWindow.setVisible (true);
}
public void itemStateChanged (ItemEvent ie)
{
JRadioButton selected = (JRadioButton) ie.getSource ();
String textOnButton = selected.getText ();
if (textOnButton.equals ("Red"))
{
message.setForeground (Color.RED);
message.setText ("STOP");
}
else if (textOnButton.equals ("Yellow"))
{
message.setForeground (Color.YELLOW);
message.setText ("READY");
}
else
{
message.setForeground (Color.GREEN);
message.setText ("GO");
}
}
}

public class TrafficLight


{
public static void main (String[]args)
{
new App ();
}}

Output;

Result:

The program to simulate a traffic light.is successfully executed and output is obtained.

You might also like