Small Project-java develop a simple calculator __java

Source: Internet
Author: User

This project course uses the Java language to complete a simple calculator. You will use the Java Swing graphics components and so on.


first, the experiment introduction

The experiment produced a simple arithmetic calculator that will be developed using Java swing. 1.1 Knowledge points Java Swing Interface Programming Calculator Logic Operation Realization 1.2 experiment Environment Introduction

This experimental environment uses the Ubuntu Linux environment with the desktop, the experiment will use the program on the desktop: Eclipse: An open source, java-based extensible development Platform for Java program development. 1.3 Experiment Completion Effect Chart

The final effect figure is shown in the following illustration:

Ii. Project Creation

Double-click to open Eclipse on your desktop, wait for startup to complete, and follow these steps to create the project.

If you are already familiar with this step, you can jump directly to the next section of the study.

(1) Select New-> project in File menu files to create the project.

(2) Select Java Project in the new dialog box that pops up, and click the Next button to go to the next step.

(3) Fill out the project name in the column Calculator, and click the Finish button to complete the creation.

(4) If you encounter the dialog shown in the following figure, click the Yes button to confirm it.

(5) After the creation of the project directory src right click on the right-click menu, select New-> class to create a class.

(6) In the New Class dialog box, fill in the package name Com.shiyanlou.calculator and class name calculator (capitalize first letter). Click the Finish button to complete the creation.

(7) Edit the Calculator.java file in accordance with the content later in this course. third, interface design and implementation

To make a calculator, you first need to know which parts it consists of.

Structurally, a simple graphical interface needs to consist of interface components, component event listeners (in response to the logic of various events), and specific event-handling logic.

The entire code structure is shown in the following illustration:

We first need to make the interface section. This part of the main task is to create the interface component objects, initialize them, and control the hierarchical relationship between the components and layout. 3.1 UI component creation and initialization

First we need to declare the UI component in the interface as a member variable of the Calculator class at the beginning. Before you read the code, think about what UI components you want to use, and where that code should be written, and so on.

    Creates a JFrame object and initializes it.
    JFrame can be understood as the main form of the program.

    JFrame frame = new JFrame ("Calculator"); Creates a Jtestfield object and initializes it.
    Jtestfield is a text box that displays the actions and results of a calculation.

    Parameter 20 indicates that the text content of 20 columns can be displayed JTextField Result_textfield = new JTextField (result, 20);

    Clears the button JButton Clear_button = new JButton ("clear");
    Number keys 0 to 9 JButton button0 = new JButton ("0");
    JButton button1 = new JButton ("1");
    JButton button2 = new JButton ("2");
    JButton Button3 = new JButton ("3");
    JButton button4 = new JButton ("4");
    JButton button5 = new JButton ("5");
    JButton button6 = new JButton ("6");
    JButton button7 = new JButton ("7");
    JButton button8 = new JButton ("8");

    JButton Button9 = new JButton ("9");
    Compute command buttons, subtraction, and decimal JButton Button_dian = new JButton (".");
    JButton Button_jia = new JButton ("+");
    JButton Button_jian = new JButton ("-");
    JButton Button_cheng = new JButton ("*");

    JButton Button_chu = new JButton ("/"); Calculate button JButton Button_dy = new JButton ("=");
 
3.2 Adding UI components to a form

This calculator has two JPanel.

What is Jpanel:jpanel is a general lightweight container. As shown in the figure above, you can interpret it as a "basket" of other UI components. The JPanel is located in the Javax.swing package and is a panel container that can be added to the JFrame itself as a container, or it can add other component (components) to the JPanel, such as JButton, JTextArea, JTextField Wait

In this project, two JPanel correspond to the calculator key except the "clear" key, the other panel is the output bar and the "clear" key (intercept part of the code).

Again, when writing this code, you should think about which part it should be in. If it's not clear, you can go back to the code structure above to view it.

The code for reference is as follows:

Creates a Jpanel object and initializes the Jpanel pan = new Jpanel ();

        The layout of the container is set to four rows four columns with a margin of 5 pixels pan.setlayout (New GridLayout (4, 4, 5, 5));
        Add the button for the calculation to the container pan.add (button7);
        Pan.add (BUTTON8);
        Pan.add (BUTTON9);
        Pan.add (Button_chu);
        Pan.add (BUTTON4);
        Pan.add (BUTTON5);
        Pan.add (BUTTON6);
        Pan.add (Button_cheng);
        Pan.add (button1);
        Pan.add (button2);
        Pan.add (Button3);
        Pan.add (Button_jian);
        Pan.add (Button0);
        Pan.add (Button_dian);
        Pan.add (Button_dy);

        Pan.add (Button_jia);

        Sets the margin Pan.setborder (Borderfactory.createemptyborder (5, 5, 5, 5)) of the Pan object;
        Set the second JPanel in the same way JPanel pan2 = new JPanel ();
        Pan2.setlayout (New BorderLayout ());
        Pan2.add (Result_textfield, borderlayout.west); Pan2.add (Clear_button, borderlayout.east);

After the layout is finished, it is the calculator's difficulty: the event handler. Iv. Adding event response logic

For calculators, the event-response logic involved is: Numeric keys, subtraction operations, decimal processing, equals, and purge.

Please think about how many of the switch states here are for what purpose.

The code is as follows (intercepting part of the code, which is handled by the class method):

Equal to the logic of the key, that is, to start computing
class Listener_dy implements ActionListener {
            @SuppressWarnings ("unchecked")
        after the input completes public void actionperformed (ActionEvent e) {

                store = (JButton) e.getsource ();
                Vt.add (store);
                Yuns ();

                Reduction Switch K1 state 
                k1 = 1; 

                Reduction Switch K2 state
                k2 = 1;

                Reduction Switch K3 state
                K3 = 1;

                Reduction Switch K4 state
                K4 = 1; 

                Prepare for 7+5=12 +5=17 this calculation
                str1 = result; 
            }
        
v. The realization of computational logic

The logic of the calculation is to operate on the operands based on the different operators of the input, taking into account the unreasonable fault tolerance of the algorithm divided by 0.

The main code is as follows:

public void Cal () {//operand 1 double A2;

        Operand 2 double B2;

        operator String C = signal;

        Operation result Double result2 = 0; if (C.equals ("")) {Result_textfield.settext ("Please input operator.");} 
                else {///String '. ' will make an error when converting to double data, so write your own logic to convert if (Str1.equals ("."))
            str1 = "0.0";
                if (Str2.equals ("."))
            str2 = "0.0";
            A2 = double.valueof (str1). Doublevalue ();

            B2 = double.valueof (str2). Doublevalue ();
            if (c.equals ("+")) {result2 = a2 + b2;
            } if (C.equals ("-")) {result2 = A2-B2;
            } if (C.equals ("*")) {result2 = a2 * B2;
                    } if (C.equals ("/")) {if (B2 = 0) {//Prevent unreasonable operation except 0
                RESULT2 = 0;
            } else {        RESULT2 = A2/B2;

            result = (new Double (RESULT2)). toString ());
        Result_textfield.settext (result);
 }
    }

At this point, the main logic of the entire calculator has been explained, please add the other details. Six, the project complete source code

The entire program complete source code is as follows, the related explanation has been given in the annotation, please read carefully.

package Com.shiyanlou.calculator;
Import java.awt.*;
Import java.awt.event.*;
Import javax.swing.*;

Import Java.util.Vector;
    public class Calculator {//operand 1, for the safety of the program, the initial value must be set, here we set to 0. 

    String str1 = "0"; 

    Operand 2 String str2 = "0"; 

    operator String signal = "+";

    The result of the operation String results = "";
    The following K1 to K2 is a state switch//switch 1 for selecting the input direction and will be written to the str1 or str2 int k1 = 1;
    Switch 2 is used to record the number of symbol keys, if the k2>1 description is 2+3-9+8 such a multi-symbol operation int k2 = 1;
    Switch 3 is used to identify whether the str1 can be cleared 0, equal to 1 can, not equal to 1 o'clock can not be clear 0 int k3 = 1;
    Switch 4 is used to identify whether STR2 can be cleared 0 int K4 = 1;
    Switch 5 is used to control whether the decimal point can be entered, equal to 1 time, not 1 o'clock, the input of the decimal point is lost int K5 = 1; 

    The store functions like a register to record whether the symbol keys are continuously pressed JButton store; 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.