Calculator with Java Graphical Interface

Asked

Viewed 28,595 times

10

I started working with the Swing framework, creating a calculator with the JOptionPane, and managed normally. Now I was launched the challenge of inserting buttons +, -, *, and / in the calculator, the problem is that I researched enough and am not getting it! I am using the JButton and I can’t figure out what to do with him.

Can post, if possible, the complete code with comments explaining to me what was missing in mine, please.

How do I add the function add, subtract, etc. to the buttons?

Please, if possible and necessary to complete the entire code, explain what was missing and what I should do, because I want to learn. If necessary, I will also post the last calculator I made and it worked using only the JOptionPane.

Well with the help of @Deyel my code went like this:

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

public class Calculadora extends JFrame {

    private static final long serialVersionUID = 1L;

    public static void main(String[] args) {
        private JButton botaoMais;
        private JButton botaoMenos;
        private JButton botaoVezes;
        private JButton botaoDividi;
        private JTextField campo;

    public Calculadora() {
        this.setTitle("Exemplo");
        this.setBounds(0,0,250,250);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.getContentPane().setLayout(null);

        botaoMais = new JButton();
        botaoMais.setText("Soma");
        botaoMais.setBounds(30,60,60,30);
        this.add(botaoMais);

        botaoMenos = new JButton();
        botaoMenos.setText("Subtrai");
        botaoMenos.setBounds(30,60,60,30);
        this.add(botaoMenos);

        botaoVezes = new JButton();
        botaoVezes.setText("Multiplica");
        botaoVezes.setBounds(30,60,60,30);
        this.add(botaoVezes);

        botaoDividi = new JButton();
        botaoDividi.setText("Dividir");
        botaoDividi.setBounds(30,60,60,30);
        this.add(botaoDividi);

        campo = new JTextField();
        campo.setBounds(40,50,100,30);
        this.add(campo);

        botaoMais.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {

            }
        }
    }

}

3 answers

15


First of all congratulations on your initiative to the rest of the class and, not least, welcome to the Stack Overflow community!

Now let’s get down to business...

I realized that your problem is not in creating the buttons and the interface, but in adding a function to them, what we call events.

How events work out:

  • Every operating system that supports graphical interface monitors events (clicks, mouse movements, keystrokes, etc.).

  • When an event happens, the operating system informs the program.

  • The program decides what to do as an event according to what was programmed.

  • Are the events that control all user interactions with the program (clicks, typed text, mouse movements, etc.).

  • To work with events in Java from components SWING we can use package features java.awt.event.

  • Each component of the graphical interface (window, button, text field, etc.) has listening interfaces (Listen) when an event is generated.

  • Each interface has associated methods to treat the different events.

Now that we know a little better how events work, let’s get to the practical part!

I wrote this example that is not very useful, but it’s great to understand how events work in practice (note the comments):

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

public class MeuJFrame extends JFrame {

    private JButton botao;
    private JTextField campo;

    public MeuJFrame() {
        this.setTitle("Exemplo");
        this.setBounds(0, 0, 200, 200);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.getContentPane().setLayout(null);

        botao = new JButton();
        botao.setText("botão");
        botao.setBounds(40, 100, 100, 50);
        this.add(botao);

        campo = new JTextField();
        campo.setBounds(40, 50, 100, 30);
        this.add(campo);

        // Adicionando um evento action ao botão
        botao.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {

                // Aqui você escreve qual será a ação do botão ao ser clicado!
                botao.setText(campo.getText());
            }
        });
    } // construtor

    public static void main(String[] args) {
        MeuJFrame exemplo = new MeuJFrame();
        exemplo.setVisible(true);
    } // método main

} // classe

If you run the above example, you will notice that the action of the button I added captures the text inserted in JTextField and assigns it to the button text.

A print of the execution:

Um print da execução

Completion:

With the information cited above, you can enter any action at any button in your program.

I didn’t want to make your challenge easier by writing what a button would look like!

Any questions ask me in the comments, I hope to have helped.

EDIT:

As there are still some doubts, I decided to write a prototype of a calculator for you to have something to base:

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

public class Calculadora extends JFrame {

    private JButton numero1;
    private JButton numero2;
    private JButton somar;
    private JButton igual;
    private JTextField display;
    private int leitura;
    private int memoria;
    private char operacao;

    public Calculadora() {
        this.setTitle("Exemplo Botão Somar");
        this.setBounds(0, 0, 267, 235);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.getContentPane().setLayout(null);

        leitura = 0;
        memoria = 0;

        somar = new JButton();
        somar.setText("+");
        somar.setBounds(145, 70, 78, 45);
        this.add(somar);

        igual = new JButton();
        igual.setText("=");
        igual.setBounds(25, 130, 200, 45);
        this.add(igual);

        numero1 = new JButton();
        numero1.setText("1");
        numero1.setBounds(25, 70, 45, 45);
        this.add(numero1);

        numero2 = new JButton();
        numero2.setText("2");
        numero2.setBounds(85, 70, 45, 45);
        this.add(numero2);

        display = new JTextField();
        display.setBounds(25, 25, 200, 30);
        this.add(display);

        numero1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                leitura *= 10;
                leitura += 1;
                display.setText(display.getText() + "1");
            }
        });

        numero2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                leitura *= 10;
                leitura += 2;
                display.setText(display.getText() + "2");
            }
        });

        somar.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                operacao = '+';
                memoria += leitura;
                leitura = 0;
                display.setText("");
            }
        });

        igual.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                switch (operacao) {
                    case '+': {
                        memoria += leitura;
                        break;
                    }
                }
                leitura = 0;
                display.setText("" + memoria);
            }
        });
    } // construtor

    public static void main(String[] args) {
        Calculadora exemplo = new Calculadora();
        exemplo.setVisible(true);
    }
} // classe

A print of the execution:

inserir a descrição da imagem aqui

Note: It is not perfect, there are several purposeful bugs that you will have to solve to improve your programming logic... Use this code as a starting point!

  • 2

    I believe you are walking well, thank you very much man ! However, my only question now is: As in your example, the action of the button was to capture the text, how do I for the action of a button be sum, or subtraction for my calculator ? See, I’ve come this far: field = new Jtextfield(); field.setBounds(40,50,100,30); this.add(field); botaoMais.addActionListener(new Actionlistener(){ public void actionPerformed(Actionevent evt){ Now all I need to know is how to make the function sum or any other element of a calculator on each button !

  • Explaining here by the comments is complicated... I added another example to my answer, more like a calculator. Any doubt warns me!

  • 1

    I’ll try my best ! Thank you very much, friend ! You have no idea how much you helped !

  • That’s it! I bet you’ll get it!!

3

What’s the idea of calculus

The idea is to take a language that has the method val (like python and javascript), which is a function that takes a string, converts it to a line of code and returns the value of the result.

(The "->" means the return)

Example1: eval("5 + 5") -> 10

Exemplo2: eval("10 / (5 + 5)") -> 1

Example3: eval("5 > 3") -> true

How to Simulate a Script Language

ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
int resultado = (Integer) engine.eval("5 + 5");

getEngineByName("Javascript"); It will return us a Scriptengine, which allows us to use language codes

engine.Eval("5 + 5"); returns the value of 5 + 5

(If you can’t understand my explanation or if you need any more help, please let me know)

0

Follow the example:

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

public class Calculadora extends JFrame {

    private JButton numero1;
    private JButton numero2;
    private JButton numero3;
    private JButton numero4;
    private JButton numero5;
    private JButton numero6;
    private JButton numero7;
    private JButton numero8;
    private JButton numero9;
    private JButton numero0;
    private JButton numeroP;
    
    private JButton dividir;
    private JButton multiplicar;
    private JButton subtrair;
    private JButton somar;
    private JButton igual;
    private JTextField display;
    
    private int leitura;
    private int memoria;
    private char operacao;

    public Calculadora() {
        this.setTitle("Exemplo Botão Somar");
        this.setBounds(500, 100, 292, 450);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.getContentPane().setLayout(null);

        leitura = 0;
        memoria = 0;

        display = new JTextField();
        display.setBounds(0, 0, 300, 100);
        this.add(display);
        
        //FAIXA 01
        numero7 = new JButton();
        numero7.setText("7");
        numero7.setBounds(0, 120, 65, 65);
        this.add(numero7);
        
        numero4 = new JButton();
        numero4.setText("4");
        numero4.setBounds(0, 190, 65, 65);
        this.add(numero4);
        
        numero1 = new JButton();
        numero1.setText("1");
        numero1.setBounds(0, 260, 65, 65);
        this.add(numero1);
        
        numero0 = new JButton();
        numero0.setText("0");
        numero0.setBounds(0, 330, 65, 65);
        this.add(numero0);
        
        //FAIXA 02
        numero8 = new JButton();
        numero8.setText("8");
        numero8.setBounds(70, 120, 65, 65);
        this.add(numero8);
        
        numero5 = new JButton();
        numero5.setText("5");
        numero5.setBounds(70, 190, 65, 65);
        this.add(numero5);
        
        numero2 = new JButton();
        numero2.setText("2");
        numero2.setBounds(70, 260, 65, 65);
        this.add(numero2);
        
        numeroP = new JButton();
        numeroP.setText(".");
        numeroP.setBounds(70, 330, 65, 65);
        this.add(numeroP);
        
        //FAIXA 03
        numero9 = new JButton();
        numero9.setText("9");
        numero9.setBounds(140, 120, 65, 65);
        this.add(numero9);
        
        numero6 = new JButton();
        numero6.setText("6");
        numero6.setBounds(140, 190, 65, 65);
        this.add(numero6);
        
        numero3 = new JButton();
        numero3.setText("3");
        numero3.setBounds(140, 260, 65, 65);
        this.add(numero3);
        
        somar = new JButton();
        somar.setText("+");
        somar.setBounds(140, 330, 65, 65);
        this.add(somar);
        
        //FAIXA 04
        dividir = new JButton();
        dividir.setText("/");
        dividir.setBounds(210, 120, 65, 65);
        this.add(dividir);
        
        multiplicar = new JButton();
        multiplicar.setText("X");
        multiplicar.setBounds(210, 190, 65, 65);
        this.add(multiplicar);
        
        subtrair = new JButton();
        subtrair.setText("-");
        subtrair.setBounds(210, 260, 65, 65);
        this.add(subtrair);
        
        igual = new JButton();
        igual.setText("=");
        igual.setBounds(210, 330, 65, 65);
        this.add(igual);

        numero1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                leitura *= 10;
                leitura += 1;
                display.setText(display.getText() + "1");
            }
        });

        numero2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                leitura *= 10;
                leitura += 2;
                display.setText(display.getText() + "2");
            }
        });
        
        numero3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                leitura *= 10;
                leitura += 3;
                display.setText(display.getText() + "3");
            }
        });
        
        numero4.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                leitura *= 10;
                leitura += 4;
                display.setText(display.getText() + "4");
            }
        });
        
        numero5.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                leitura *= 10;
                leitura += 5;
                display.setText(display.getText() + "5");
            }
        });
        
        numero6.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                leitura *= 10;
                leitura += 6;
                display.setText(display.getText() + "6");
            }
        });
        
        numero7.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                leitura *= 10;
                leitura += 7;
                display.setText(display.getText() + "7");
            }
        });
        
        numero8.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                leitura *= 10;
                leitura += 8;
                display.setText(display.getText() + "8");
            }
        });
        
        numero9.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                leitura *= 10;
                leitura += 3;
                display.setText(display.getText() + "9");
            }
        });
        
        numero0.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                leitura *= 10;
                leitura += 0;
                display.setText(display.getText() + "0");
            }
        });

        somar.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                operacao = '+';
                memoria += leitura;
                leitura = 0;
                display.setText(memoria + " + ");
            }
        });
        
        subtrair.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                operacao = '-';
                memoria += leitura;
                leitura = 0;
                display.setText(memoria + " - ");
            }
        });
        
        multiplicar.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                operacao = 'X';
                memoria += leitura;
                leitura = 0;
                display.setText(memoria + " X ");
            }
        });
        
        dividir.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                operacao = '/';
                memoria += leitura;
                leitura = 0;
                display.setText(memoria + " / ");
            }
        });

        igual.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                switch (operacao) {
                    case '.': {
                        memoria = memoria + '.';
                        break;
                    }
                    case '+': {
                        memoria += leitura;
                        break;
                    }
                    
                    case '-': {
                        memoria -= leitura;
                        break;
                    }
                    
                    case 'X': {
                        memoria *= leitura;
                        break;
                    }
                    
                    case '/': {
                        memoria /= leitura;
                        break;
                    }
                    
                }
                leitura = 0;
                display.setText("" + memoria);
            }
        });
    } // construtor

    public static void main(String[] args) {
        Calculadora exemplo = new Calculadora();
        exemplo.setVisible(true);
    }
} // classe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.