Finals 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

//Add References - another library

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class finals1


{
//variable declaration for global objects
public static JTextField txt1, txt2, txt3;
public static JButton btn1, btn2;

public static void main(String[] args)


{
//create a window
JFrame frame = new JFrame("Get the SUM");
frame.setPreferredSize(new Dimension(300,200));
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//set background
Container content = frame.getContentPane();
content.setBackground(Color.green);
content.setLayout(new FlowLayout());

//create label1 and textbox1


JLabel lbl1 = new JLabel(" First Input: ");
content.add(lbl1);
txt1 = new JTextField("", 15);
content.add(txt1);

//create label2 and textbox2


JLabel lbl2 = new JLabel("Second Input: ");
content.add(lbl2);
txt2 = new JTextField("", 15);
content.add(txt2);

//create label3 and textbox3


JLabel lbl3 = new JLabel(" Result : ");
content.add(lbl3);
txt3 = new JTextField("", 15);
txt3.setEnabled(false);
txt3.setBackground(Color.gray);
txt3.setDisabledTextColor(Color.black);
txt3.setBorder(BorderFactory.createEtchedBorder());
content.add(txt3);

//create buttons
btn1 = new JButton(" COMPUTE ");
btn1.setForeground(Color.red); //font color
btn1.addActionListener(new event_handler()); //command
content.add(btn1);

btn2 = new JButton(" CLEAR ");


btn2.setForeground(Color.red);
btn2.addActionListener(new event_handler());
content.add(btn2);

//show frame
frame.pack();
}
}

class event_handler implements ActionListener{


finals1 fin = new finals1();
public void actionPerformed(ActionEvent e)
{
Object ob = e.getSource();

if (ob==fin.btn1) //button 1 clicked


{
//get the inputs
String input1 = fin.txt1.getText().trim();
String input2 = fin.txt2.getText().trim();

//compute the sum


int output = Integer.parseInt(input1) + Integer.parseInt(input2);

//display the result


fin.txt3.setText(Integer.toString(output));
}

if (ob==fin.btn2) //button 2 clicked


{
fin.txt1.setText("");
fin.txt2.setText("");
fin.txt3.setText("");
}
}
}

You might also like