GUI based Calculator
This is a simple calculator which can add, subtract, multiply and divide two numbers. There’s not much logic involved in the program, just made it to demonstrate different GUI elements.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class Calculator { JButton add,divide,multiply,sub; JTextField num1,num2; JLabel ans; public Calculator(){ JFrame frame = new JFrame("Calculator - MyCoding.net"); num1 = new JTextField (10); ans = new JLabel(""); num2 = new JTextField (9); add = new JButton ("+"); divide = new JButton("/"); multiply = new JButton("X"); sub = new JButton ("-"); frame.setVisible(true); frame.setBounds(500, 200, 290, 210); frame.setLayout(new GridLayout(0,2,1,1)); frame.add(new JLabel("First Number: ")); frame.add(num1); frame.add(new JLabel("Second Number: ")); frame.add(num2); frame.add(new JLabel("Answer: ")); frame.add(ans); frame.add(add); frame.add(sub); frame.add(multiply); frame.add(divide); add.addActionListener(new HandlerClass()); sub.addActionListener(new HandlerClass()); divide.addActionListener(new HandlerClass()); multiply.addActionListener(new HandlerClass()); } public static void main(String[] args) { new Calculator(); } public class HandlerClass implements ActionListener{ public void actionPerformed(ActionEvent ae){ try{ int fnum = Integer.parseInt(num1.getText()); int snum = Integer.parseInt(num2.getText()); if(ae.getSource()== add){ ans.setText(String.valueOf(fnum+snum)); } else if(ae.getSource()== sub){ ans.setText(String.valueOf(fnum-snum)); } else if(ae.getSource()== multiply){ ans.setText(String.valueOf(fnum*snum)); } else{ ans.setText(String.valueOf(fnum/snum)); } }catch(Exception e) { JOptionPane.showMessageDialog(null, "Please enter a valid number"); e.printStackTrace(); } } } } |
Output: Executable JAR file: http://www.mediafire.com/?6bbweg0ivd8id6n