Calculadora

4 respostas
E

Bem galera estou fazendo uma calculadora que usa a estrutura de dados pilha mais estou usando parte gráfica do java a qual eu nunca tinha usando antes… Já consegui criar a tela os botões e a saida de texto mais como eu faço para da ação aos botão tipo se o usuário clicar no botão 1 ai vai aparecer no campo texto 1 e por ai vai… estou usando o JButton,JFrame e JTextField alguém pode me ajudar a dar ação nesses componentes vo deixar as classes que eu estou fazendo logo abaixo, quem souber por favor me explique com detalhes pois sou leigo ou então implemente o código pra min ficarei grato!
classe main

import javax.swing.JFrame;
public class textnaim 
{
         public static void main(String args[])
         {
        	 Text p = new Text();
        	 p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        	 p.setSize(200,250);
        	 p.setVisible(true);
         }
}
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;


public class  Text extends JFrame
{
	private JTextField texto1;
;
	private JButton botao;
	private JButton botao1;
	private JButton botao2;
	private JButton botao3;
	private JButton botao4;
	private JButton botao5;
	private JButton botao6;
	private JButton botao7;
	private JButton botao8;
	private JButton botao9;
	
	public Text()
	{
		super("Calculadora");
		setLayout(new FlowLayout());
			
		
		texto1 = new JTextField("                                                      ");
		add(texto1);
		
		
		botao=new JButton("0");
		add(botao);
		  
		botao1=new JButton("1");
		add(botao1);
		
		botao2=new JButton("2");
		add(botao2);
		
		botao3=new JButton("3");
		add(botao3);
		
		botao4=new JButton("4");
		add(botao4);
		
		botao5=new JButton("5");
		add(botao5);
		
		botao6=new JButton("6");
		add(botao6);
		
		botao7=new JButton("7");
		add(botao7);
		
		botao8=new JButton("8");
		add(botao8);
		
		botao9=new JButton("9");
		add(botao9);
		
		
	}
	

}

4 Respostas

P

pesquisa sobre ActionListeiner e KeyListeiner…

E

no cara olhei lá mais entedi nada

N

Na Classe que você vai tratar dos eventos você deve importar:

import java.awt.event.*;

E também deve implementar ActionListener:

SuaClasse implements ActionListener

Agora cada botão seu deve adicionar essa Interface:

seuBotao1.addActionListener(this);
seuBotao2.addActionListener(this);
// etc...

Por último você deve sobrescrever o método actionPerformed:

public void actionPerformed(ActionEvent ae) {
   if(ae.getSource() == seuBotao1) {
      suaCaixaDeTexto.setText(suaCaixaDeTexto.getText() + "1");
   }
   if(ae.getSource() == seuBotao2) {
      suaCaixaDeTexto.setText(suaCaixaDeTexto.getText() + "2");
   }
   // etc...
}

Espero ter ajudado.

M

bom…
tenho uma calculadora pronta aki…
eu peguei o código mas tb não o entendi muito…
Veja:

[color=“red”]

import java.awt.<em>;

import javax.swing.</em>;

import java.awt.event.*;
public class Calculadora extends JFrame implements ActionListener {

JTextField visor;

double argumento = 0;

char op = =;

boolean nova = true;

JButton igual;

public Calculadora() {

visor = new JTextField("0"); 
visor.setEditable(false);  
JPanel centro = new JPanel(new GridLayout(4,4)); 
String botoes = "789/456*123-0.=+";
for (int i = 0; i &lt; botoes.length(); ++i) {
  char simbolo = botoes.charAt(i);
  JButton botao = new JButton(String.valueOf(simbolo));    
  if (simbolo &gt;= '0' &amp;&amp; simbolo &lt;= '9') 
  if (simbolo == '=') igual = botao;
  centro.add(botao);
  botao.addActionListener(this);
}

Container c = getContentPane();
c.setLayout(new BorderLayout(0,20));
c.add(visor,BorderLayout.NORTH);    
c.add(centro,BorderLayout.CENTER);
setSize(250,300);
setTitle("Calculadora");
setResizable(false);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {

char c = e.getActionCommand().charAt(0);

if (c >= 0 && c <= 9 || c == .) {

if (nova) visor.setText(String.valueOf©);

else {

String estado = visor.getText();

if (c != . || estado.indexOf(.) < 0)

visor.setText(estado + c);

}

nova = false;

}

else {

if (nova)

if (c == -) {

visor.setText("-");

nova = false;

}

else op = c;

else {

double x = Double.parseDouble(visor.getText());

calcular(x);

op = c;

nova = true;

}

}

}

private void calcular(double n) {

if (op == +) argumento += n;

else if (op == -) argumento -= n;

else if (op == *) argumento *= n;

else if (op == /) argumento /= n;

else if (op == =) argumento = n;

visor.setText(String.valueOf(argumento));

}

public static void main(String[] s) {

Calculadora app = new Calculadora();

app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}
[/color]
funciona normalmete…mas algumas coisas no código eu não entendi…
:slight_smile:

Criado 22 de setembro de 2006
Ultima resposta 26 de set. de 2006
Respostas 4
Participantes 4