Calculadora

14 respostas
M
Como faço para somar, dividir, multiplicar e colcoar o resultado no visor? ja fiz isso
package gui;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Calculadora extends JFrame implements ActionListener {
	
	JTextField display;
	JButton bt_7 = new JButton("7");
	JButton bt_8 = new JButton("8");
	JButton bt_9 = new JButton("9");
	JButton bt_dividir = new JButton("/");
	JButton bt_4 = new JButton("4");
	JButton bt_5 = new JButton("5");
	JButton bt_6 = new JButton("6");
	JButton bt_multiplicar = new JButton("*");
	JButton bt_1 = new JButton("1");
	JButton bt_2 = new JButton("2");
	JButton bt_3 = new JButton("3");
	JButton bt_subtrair = new JButton("-");
	JButton bt_0 = new JButton("0");
	JButton bt_ponto = new JButton(".");
	JButton bt_somar = new JButton("+");
	JButton bt_igual = new JButton("=");
	
	public Calculadora() {
		super("Calculadora");

		Container n = new JPanel();
		n.setLayout(new GridLayout(4,4, 5,5));
		n.add(bt_7);
		bt_7.addActionListener(this);
		n.add(bt_8);
		bt_8.addActionListener(this);
		n.add(bt_9);
		bt_9.addActionListener(this);
		n.add(bt_dividir);
		bt_dividir.addActionListener(this);
		n.add(bt_4);
		bt_4.addActionListener(this);
		n.add(bt_5);
		bt_5.addActionListener(this);
		n.add(bt_6);
		bt_6.addActionListener(this);
		n.add(bt_multiplicar);
		bt_multiplicar.addActionListener(this);
		n.add(bt_1);
		bt_1.addActionListener(this);
		n.add(bt_2);
		bt_2.addActionListener(this);
		n.add(bt_3);
		bt_3.addActionListener(this);
		n.add(bt_subtrair);
		n.add(bt_0);
		bt_0.addActionListener(this);
		n.add(bt_ponto);
		bt_ponto.addActionListener(this);
		n.add(bt_somar);
		bt_somar.addActionListener(this);
		n.add(bt_igual);
		bt_igual.addActionListener(this);
	
		display = new JTextField();
		display.setFont(new Font("Serif", Font.PLAIN, 26));
		
		Container c = getContentPane();
		c.add(BorderLayout.NORTH, display);
		c.add(BorderLayout.CENTER, n);
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(300,300);
		setVisible(true);
	}
	
	public static void main(String[] args) {
		new Calculadora();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == bt_7) {
			display.setText(display.getText()+"7");
		} else if(e.getSource() == bt_8) {
			display.setText(display.getText()+"8");
		} else if(e.getSource() == bt_9) {
			display.setText(display.getText()+"9");
		} else if(e.getSource() == bt_dividir) {
			display.setText(display.getText());
		} else if(e.getSource() == bt_4) {
			display.setText(display.getText()+"4");
		} else if(e.getSource() == bt_5) {
			display.setText(display.getText()+"5");
		} else if(e.getSource() == bt_6) {
			display.setText(display.getText()+"6");
		} else if(e.getSource() == bt_multiplicar) {
			display.setText(display.getText());
		} else if(e.getSource() == bt_1) {
			display.setText(display.getText()+"1");
		} else if(e.getSource() == bt_2) {
			display.setText(display.getText()+"2");
		} else if(e.getSource() == bt_3) {
			display.setText(display.getText()+"3");
		} else if(e.getSource() == bt_subtrair) {
			display.setText(display.getText());
		} else if(e.getSource() == bt_0) {
			display.setText(display.getText()+"0");
		} else if(e.getSource() == bt_ponto) {
			display.setText(display.getText());
		} else if(e.getSource() == bt_ponto) {
			display.setText(display.getText());
		} else if(e.getSource() == bt_igual) {
			display.setText(display.getText()+" = ");
		}
	}

}

14 Respostas

M

alguem?

douglas_arantes

Olá, você precisa criar os métodos para cada uma dessas operações (adição, subtração, multiplicação, divisão), tratar o evento quando clicar no botão “+” somar, etc…

M

pode dar um exemplo?

ViniGodoy
RiQuInHo_

dá uma olhada

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

public class Calculadora extends JFrame implements ActionListener {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JButton somar, subtrair, multiplicar, dividir, limpar, voltar, igual, ponto;
    private JButton bt0, bt1, bt2, bt3, bt4, bt5, bt6, bt7, bt8, bt9;
    private JTextField tfVisor;
    private double n1, n2;
    private char operacao = ' ';
    private boolean segundo = true;
    private boolean utd = false;

    public Calculadora() {
        //Ajuste do formulário
        setTitle("Calculadora");
        setSize(245, 260);
        setLocation(WIDTH, WIDTH);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        getContentPane().setLayout(null);
        setLocationRelativeTo(null);
        

        //Inicialização dos botões
        somar = new JButton("+");
        subtrair = new JButton("-");
        multiplicar = new JButton("*");
        dividir = new JButton("/");
        limpar = new JButton("CE");
        voltar = new JButton("Backspace");
        igual = new JButton("=");
        ponto = new JButton(",");
        bt0 = new JButton("0");
        bt1 = new JButton("1");
        bt2 = new JButton("2");
        bt3 = new JButton("3");
        bt4 = new JButton("4");
        bt5 = new JButton("5");
        bt6 = new JButton("6");
        bt7 = new JButton("7");
        bt8 = new JButton("8");
        bt9 = new JButton("9");
        tfVisor = new JTextField();

        //Posicionar componentes no formulário
        tfVisor.setBounds(10, 10, 220, 40);

        voltar.setBounds(10, 55, 160, 30);
        limpar.setBounds(180, 55, 50, 30);

        bt7.setBounds(10, 90, 50, 30);
        bt8.setBounds(65, 90, 50, 30);
        bt9.setBounds(120, 90, 50, 30);
        dividir.setBounds(180, 90, 50, 30);

        bt4.setBounds(10, 125, 50, 30);
        bt5.setBounds(65, 125, 50, 30);
        bt6.setBounds(120, 125, 50, 30);
        multiplicar.setBounds(180, 125, 50, 30);

        bt1.setBounds(10, 160, 50, 30);
        bt2.setBounds(65, 160, 50, 30);
        bt3.setBounds(120, 160, 50, 30);
        subtrair.setBounds(180, 160, 50, 30);

        bt0.setBounds(10, 195, 50, 30);
        ponto.setBounds(65, 195, 50, 30);
        igual.setBounds(120, 195, 50, 30);
        somar.setBounds(180, 195, 50, 30);

        //Cores dos componentes
        bt0.setForeground(Color.BLUE);
        bt1.setForeground(Color.BLUE);
        bt2.setForeground(Color.BLUE);
        bt3.setForeground(Color.BLUE);
        bt4.setForeground(Color.BLUE);
        bt5.setForeground(Color.BLUE);
        bt6.setForeground(Color.BLUE);
        bt7.setForeground(Color.BLUE);
        bt8.setForeground(Color.BLUE);
        bt9.setForeground(Color.BLUE);
        ponto.setForeground(Color.BLUE);

        somar.setForeground(Color.red);
        subtrair.setForeground(Color.red);
        multiplicar.setForeground(Color.red);
        dividir.setForeground(Color.red);
        igual.setForeground(Color.red);
        limpar.setForeground(Color.red);
        voltar.setForeground(Color.red);

        tfVisor.setHorizontalAlignment(JTextField.RIGHT);

        //Registro de componentes que executam ações

        bt0.addActionListener(this);
        bt1.addActionListener(this);
        bt2.addActionListener(this);
        bt3.addActionListener(this);
        bt4.addActionListener(this);
        bt5.addActionListener(this);
        bt6.addActionListener(this);
        bt7.addActionListener(this);
        bt8.addActionListener(this);
        bt9.addActionListener(this);
        somar.addActionListener(this);
        subtrair.addActionListener(this);
        multiplicar.addActionListener(this);
        dividir.addActionListener(this);
        igual.addActionListener(this);
        limpar.addActionListener(this);
        voltar.addActionListener(this);
        ponto.addActionListener(this);

        //Colocar os componentes no formulário
        this.getContentPane().add(somar);
        this.getContentPane().add(subtrair);
        this.getContentPane().add(multiplicar);
        this.getContentPane().add(dividir);
        this.getContentPane().add(tfVisor);
        this.getContentPane().add(bt0);
        this.getContentPane().add(bt1);
        this.getContentPane().add(bt2);
        this.getContentPane().add(bt3);
        this.getContentPane().add(bt4);
        this.getContentPane().add(bt5);
        this.getContentPane().add(bt6);
        this.getContentPane().add(bt7);
        this.getContentPane().add(bt8);
        this.getContentPane().add(bt9);
        this.getContentPane().add(igual);
        this.getContentPane().add(limpar);
        this.getContentPane().add(voltar);
        this.getContentPane().add(dividir);
        this.getContentPane().add(ponto);
    }

    public static void main(String args[]) {
        JFrame obj = new Calculadora();
        obj.setVisible(true);
    }

    public void actionPerformed(ActionEvent acao) {
        if (acao.getSource() == bt0) {
            if (tfVisor.getText().equals("")) {
                return;
            } else {
                numDigi("0");
            }
        } else if (acao.getSource() == bt1) {
            numDigi("1");
        } else if (acao.getSource() == bt2) {
            numDigi("2");
        } else if (acao.getSource() == bt3) {
            numDigi("3");
        } else if (acao.getSource() == bt4) {
            numDigi("4");
        } else if (acao.getSource() == bt5) {
            numDigi("5");
        } else if (acao.getSource() == bt6) {
            numDigi("6");
        } else if (acao.getSource() == bt7) {
            numDigi("7");
        } else if (acao.getSource() == bt8) {
            numDigi("8");
        } else if (acao.getSource() == bt9) {
            numDigi("9");
        } else if (acao.getSource() == ponto) {
            decimal();
        }
        if (acao.getSource() == limpar) {
            tfVisor.setText("");
            operacao = ' ';
            segundo = true;
            utd = false;
            n1 = 0;
            n2 = 0;
        }
        if (acao.getSource() == voltar) {
            int tam = tfVisor.getText().length();
            if (tam > 0) {
                tfVisor.setText(tfVisor.getText().substring(0, tam - 1));
            } else {
                return;
            }
        }
        if (acao.getSource() == somar) {
            igual();
            calcular('+');
        }
        if (acao.getSource() == subtrair) {
            igual();
            calcular('-');
        }
        if (acao.getSource() == multiplicar) {
            igual();
            calcular('*');
        }
        if (acao.getSource() == dividir) {
            igual();
            calcular('/');
        }
        if (acao.getSource() == igual) {
            igual();
        }
    }

    private void calcular(char c) {
        if (!tfVisor.getText().equals("")) {
            operacao = c;
            segundo = false;
            utd = false;
            n1 = Double.parseDouble(tfVisor.getText());
        } else {
            return;
        }
    }

    private void numDigi(String n) {
        if (segundo == true) {
            tfVisor.setText(tfVisor.getText() + n);
        } else {
            tfVisor.setText("");
            tfVisor.setText(tfVisor.getText() + n);
            segundo = true;
        }
    }

    private void igual() {
        if (operacao == '+') {
            n2 = n1 + Double.parseDouble(tfVisor.getText());
            tfVisor.setText("" + n2);
            n1 = 0;
            n2 = 0;
            operacao = ' ';
            segundo = false;
        } else if (operacao == '-') {
            n2 = n1 - Double.parseDouble(tfVisor.getText());
            tfVisor.setText("" + n2);
            n1 = 0;
            n2 = 0;
            operacao = ' ';
        } else if (operacao == '*') {
            n2 = n1 * Double.parseDouble(tfVisor.getText());
            tfVisor.setText("" + n2);
            n1 = 0;
            n2 = 0;
            operacao = ' ';
        } else if (operacao == '/') {
            n2 = n1 / Double.parseDouble(tfVisor.getText());
            tfVisor.setText("" + n2);
            n1 = 0;
            n2 = 0;
            operacao = ' ';
        } else {
            return;
        }
    }

    private void decimal() {
        if (utd == false) {
            if (tfVisor.getText().length() < 1) {
                numDigi("0.");
            }
            else if (possuePonto() == true){
                    return;
                }
                else{
                numDigi(".");
                }
            }
            utd = true;
        
    }

    private boolean possuePonto(){
        String v = tfVisor.getText();
        boolean b = false;
        for (int i = 0; i<v.length();i++){
            if (v.substring(i, i).equals(".")){
                b = true;
            }
            else {
                b = false;
            }
        }
        return b;
    }
}
J

Veja o exemplo bem simples que eu estou anexando, da para você ter uma ideia de como fazer, o projeto foi feito no NetBeans.

M
Vini me surgiu umas duvidas danada agora, se puder responder. Para que serve isso? seria a mesma coisa que JButton ..... = new JButton(); ?
private BotaoNumericoAction acaoBotao1 = new BotaoNumericoAction(1);
E isso?  private JPanel getPnlPrincipal() {  
        if (pnlPrincipal != null)  
            return pnlPrincipal;  
          
        pnlPrincipal = new JPanel(new BorderLayout());  
        pnlPrincipal.add(getTxtVisor(), BorderLayout.NORTH);  
        pnlPrincipal.add(getPnlBotoes(), BorderLayout.CENTER);  
        registrarAcoesDoTeclado(pnlPrincipal);  
        return pnlPrincipal;  
    }  
  
    private JTextField getTxtVisor() {  
        if (display != null)  
            return display;
E isso
private JPanel getPnlBotoes() {  
        if (pnlBotoes != null)  
            return pnlBotoes;  
        pnlBotoes = new JPanel();  
        pnlBotoes.setLayout(new GridLayout(4,4,5,5));
M
O meu não está mais fácil de entender? só queria saber como dar ações para +, -, /, *; só isso.
package gui;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Calculadora extends JFrame implements ActionListener {
	
	JTextField display;
	JButton bt_7 = new JButton("7");
	JButton bt_8 = new JButton("8");
	JButton bt_9 = new JButton("9");
	JButton bt_dividir = new JButton("/");
	JButton bt_4 = new JButton("4");
	JButton bt_5 = new JButton("5");
	JButton bt_6 = new JButton("6");
	JButton bt_multiplicar = new JButton("*");
	JButton bt_1 = new JButton("1");
	JButton bt_2 = new JButton("2");
	JButton bt_3 = new JButton("3");
	JButton bt_subtrair = new JButton("-");
	JButton bt_0 = new JButton("0");
	JButton bt_ponto = new JButton(".");
	JButton bt_somar = new JButton("+");
	JButton bt_igual = new JButton("=");
	
	public Calculadora() {
		super("Calculadora");

		Container n = new JPanel();
		n.setLayout(new GridLayout(4,4, 5,5));
		n.add(bt_7);
		bt_7.addActionListener(this);
		n.add(bt_8);
		bt_8.addActionListener(this);
		n.add(bt_9);
		bt_9.addActionListener(this);
		n.add(bt_dividir);
		bt_dividir.addActionListener(this);
		n.add(bt_4);
		bt_4.addActionListener(this);
		n.add(bt_5);
		bt_5.addActionListener(this);
		n.add(bt_6);
		bt_6.addActionListener(this);
		n.add(bt_multiplicar);
		bt_multiplicar.addActionListener(this);
		n.add(bt_1);
		bt_1.addActionListener(this);
		n.add(bt_2);
		bt_2.addActionListener(this);
		n.add(bt_3);
		bt_3.addActionListener(this);
		n.add(bt_subtrair);
		n.add(bt_0);
		bt_0.addActionListener(this);
		n.add(bt_ponto);
		bt_ponto.addActionListener(this);
		n.add(bt_somar);
		bt_somar.addActionListener(this);
		n.add(bt_igual);
		bt_igual.addActionListener(this);
	
		display = new JTextField();
		display.setFont(new Font("Serif", Font.PLAIN, 26));
		display.setEditable(false);
		
		Container c = getContentPane();
		c.add(BorderLayout.NORTH, display);
		c.add(BorderLayout.CENTER, n);
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(300,300);
		setVisible(true);
	}
	
	public static void main(String[] args) {
		new Calculadora();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == bt_7) {
			display.setText(display.getText()+"7");
		} else if(e.getSource() == bt_8) {
			display.setText(display.getText()+"8");
		} else if(e.getSource() == bt_9) {
			display.setText(display.getText()+"9");
		} else if(e.getSource() == bt_dividir) {
			display.setText(display.getText());
		} else if(e.getSource() == bt_4) {
			display.setText(display.getText()+"4");
		} else if(e.getSource() == bt_5) {
			display.setText(display.getText()+"5");
		} else if(e.getSource() == bt_6) {
			display.setText(display.getText()+"6");
		} else if(e.getSource() == bt_multiplicar) {
			display.setText(display.getText());
		} else if(e.getSource() == bt_1) {
			display.setText(display.getText()+"1");
		} else if(e.getSource() == bt_2) {
			display.setText(display.getText()+"2");
		} else if(e.getSource() == bt_3) {
			display.setText(display.getText()+"3");
		} else if(e.getSource() == bt_subtrair) {
			display.setText(display.getText());
		} else if(e.getSource() == bt_0) {
			display.setText(display.getText()+"0");
		} else if(e.getSource() == bt_ponto) {
			display.setText(display.getText());
		} else if(e.getSource() == bt_ponto) {
			display.setText(display.getText());
		} else if(e.getSource() == bt_igual) {
			display.setText(display.getText()+" = ");
		}
	}

}
RiQuInHo_

public void actionPerformed(ActionEvent acao) para dar vida ao seu projeto

na moral, ja tem tudo pronto para fazer ou é voce é cego ou preguiçoso da pohha hein !!!

M

Não quer ajudar, não estrova, se está incomodado, só não responder.

RiQuInHo_

vc é uma anta leiga isso sim!!!

cabeçinha de jaca!!! :lol: :lol:

M

Hm. fiko no aguardo esperando ajuda.

M

Só quero saber como faço para pegar o valor 1 limpar a tela mostrar valor 2 e colocar o resultado

M

Com base na calculadora que me passaram fikei com algumas dúvidas.

if (acao.getSource() == limpar) { display.setText(""); operacao = ' '; segundo = true; utd = false; n1 = 0; n2 = 0;
Para que serve o utd e o segundo? E para que serve a operação? sem esses 3 funciona normalmente.

E a substring?} if (acao.getSource() == voltar) { int tam = display.getText().length(); if (tam > 0) { display.setText(display.getText().substring(0, tam - 1)); } else { return; }
E o else { return; para que serve?

Criado 25 de julho de 2012
Ultima resposta 27 de jul. de 2012
Respostas 14
Participantes 5