Calculator with Java Graphical Interface

9

I started working with the Swing framework, creating a calculator with JOptionPane , and I did it normally. Now I have the challenge of inserting the buttons in the calculator, the + , - , * and / problem is that I researched a lot and I can not do it! I'm using JButton and I can not figure out what to do with it.

You can, if possible, post the complete code with comments explaining what was missing in mine, please.

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

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

Well with the help of @Deyel my code looks 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) {

            }
        }
    }

}
    
asked by anonymous 10.04.2014 / 07:36

2 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 noticed 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:

  • Every operating system that supports GUI 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 has been scheduled.

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

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

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

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

Now that we know a little better how events work, let's go the practical part!

I wrote this example that is not very useful, but it is 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'll notice that the button action I added captures the text entered in JTextField and assigns it to the button text.

A print of the execution:

Conclusion:

Withtheinformationquotedabove,youcaninsertanyactiontoanybuttoninyourprogram.

Ididnotwanttomakeiteasierforyoutowritewhatyouwouldliketoadd,forexample,becauseitiswhatyoulearn!

Anyquestionspleaseaskmeinthecomments,IhopeIhavehelped.

EDIT:

AsIstillhavesomequestions,Idecidedtowriteaprototypeofacalculatorsothatyouhavesomethingtobaseyourselfon:

importjavax.swing.*;importjava.awt.event.*;publicclassCalculadoraextendsJFrame{privateJButtonnumero1;privateJButtonnumero2;privateJButtonsomar;privateJButtonigual;privateJTextFielddisplay;privateintleitura;privateintmemoria;privatecharoperacao;publicCalculadora(){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:

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!

    
10.04.2014 / 08:14
2

What is the idea of the calculation

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

(The "- &" means the return)

  

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

     

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

     

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

Simulating 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 did not understand my explanation or need any further help, please let me know)

    
21.08.2014 / 22:00