Core Java| JSP| Servlets| XML| EJB| JEE5| Web Services| J2ME| Glossary| Questions?

 

 

 

 

 

 

 

 

 

 

 

 

 

Search Tutorials

Latest Questions
Comments
 
Writing Calculator Program in Swing 
 

In this tutorial we are providing you an example which illustrates you how to a create calculator in Swing with the source code and screen shot.

 

Writing Calculator Program in Swing

                         

In this tutorial we are providing you an example which illustrates you how to a create calculator in Swing with the source code and screen shot.

For developing a small calculator program in swing we need two different classes 

1) SwingCalculator.java
2) Calculator.java

The SwingCalculator.java calls the Calculator.java class by JFrame frame = new Calculator(). All the methods and actions are to be performed in Calculator.java class.

Calculator Code in Java Swing



Please save the code as SwingCalculator.java

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

class SwingCalculator {
   public static void main(String[] args) {
    JFrame frame = new Calculator();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    }
}


Here is the code of Calculator.java

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

  class Calculator extends JFrame {
  private final Font BIGGER_FONT = new Font("monspaced",
  Font.PLAIN, 
20);
  private JTextField textfield;       
  private boolean   number = true;  
  private String    equalOp  = "=";  
  private CalculatorOp op = new CalculatorOp(); 

  public Calculator() {
  textfield = new JTextField("0"12);
  textfield.setHorizontalAlignment(JTextField.RIGHT);
  textfield.setFont(BIGGER_FONT);
  
  ActionListener numberListener = new NumberListener();
  String buttonOrder = "1234567890 ";
  JPanel buttonPanel = new JPanel();
  buttonPanel.setLayout(new GridLayout(4444));
    for (int i = 0; i < buttonOrder.length(); i++) {
            String key = buttonOrder.substring(i, i+1);
            if (key.equals(" ")) {
                buttonPanel.add(new JLabel(""));
            else {
                JButton button = new JButton(key);
                button.addActionListener(numberListener);
                button.setFont(BIGGER_FONT);
        buttonPanel.add(button);
            }
        }
  ActionListener operatorListener = new OperatorListener();
  JPanel panel = new JPanel();
  panel.setLayout(new GridLayout(4444));
  String[] opOrder = {"+""-""*""/","=","C"};
   for (int i = 0; i < opOrder.length; i++) {
    JButton button = new JButton(opOrder[i]);
    button.addActionListener(operatorListener);
    button.setFont(BIGGER_FONT);
  panel.add(button);
    }
   JPanel pan = new JPanel();
        pan.setLayout(new BorderLayout(44));
        pan.add(textfield, BorderLayout.NORTH );
        pan.add(buttonPanel   , BorderLayout.CENTER);
        pan.add(panel , BorderLayout.EAST  );
        this.setContentPane(pan);
        this.pack();
        this.setTitle("Calculator");
        this.setResizable(false);
    }
        private void action() {
        number = true;         
        textfield.setText("0");
        equalOp  = "=";
        op.setTotal("0");
  }
  class OperatorListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
        if (number) {
                action();
                textfield.setText("0");
            else {
                number = true
                String displayText = textfield.getText();
                if (equalOp.equals("=")) {
                        op.setTotal(displayText);
                    else if (equalOp.equals("+")) {
                        op.add(displayText);
                    else if (equalOp.equals("-")) {
                        op.subtract(displayText);
                    else if (equalOp.equals("*")) {
                        op.multiply(displayText);
                    else if (equalOp.equals("/")) {
                        op.divide(displayText);
                    }
                   textfield.setText("" + op.getTotalString());
                   equalOp = e.getActionCommand();
            }
           }
           }
    class NumberListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            String digit = event.getActionCommand(); 
            if (number) {
              textfield.setText(digit);
              number = false;
            else {
             textfield.setText(textfield.getText() + digit);
            }
        }
    }
  public class CalculatorOp {
    
private int total;   
public CalculatorOp() {
        total = 0;
    }
   public String getTotalString() {
        return ""+total;
    }
   public void setTotal(String n) {
        total = convertToNumber(n);
    }
   public void add(String n) {
        total += convertToNumber(n);
   }
   public void subtract(String n) {
        total -= convertToNumber(n);
    }
   public void multiply(String n) {
        total *= convertToNumber(n);
    }
   public void divide(String n) {
        total /= convertToNumber(n);
    }
   private int convertToNumber(String n) {
        return Integer.parseInt(n);
    }
}
}

 
The constructor new CalculatorOp() calls the CalculatorOp class. The Swing component JTextField is used to create textbox on which calculation is to be performed. JPanel arranges the numeric buttons in a panel. JButton is used to perform an action. OperatorListener class is called to perform action on operators, i.e, '+,-,*,/,='. The class NumberListener is called for numbers 0 to 9.


Output will be displayed as:


Download Source Code

                         

» View all related tutorials
Related Tags: c ide class methods method get icon height vi width change using int id ai create js define show paint

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

2 comments so far (
post your own) View All Comments Latest 10 Comments:

why there is no html code?

Posted by shelby on Monday, 12.15.08 @ 04:01am | #82775

Thanx For Coding calculator
it is very usefull for
me THANXXXXXXXXXXXXXXX

Posted by Harshad on Wednesday, 12.10.08 @ 04:27am | #82598

Training Courses
Tell A Friend
Your Friend Name
Software Solutions
Least Viewed
Most Rated
Recently Viewed
Search Tutorials

 

 
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Flex Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.