Calculadora

34 respostas
victorrgds

Fala galera, blz ?

Então, enfim me solicitaram a criação da calculadora na facul, porém estou tendo um pouco de dificuldade pra organizar os botões, campos e etc…segue o código:

import java.awt.GridLayout;
import java.awt.Container;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Calculadora extends JFrame implements ActionListener
{
	private JButton buttons[]; // array de botões
	private final String names[] = { "1","2","3","+","C","4","5","6","-","CE","7"
											  ,"8","9","*","RAIZ","+/-","0",".","/","="};
	private boolean toggle = true; // alterna entre dois layouts
	private Container container; // contêiner do frame
	private GridLayout gridLayout1; // primeiro gridlayout
	private GridLayout gridLayout2; // segundo gridlayout
	private JTextField texto;
	
	// construtor sem argumento
	public Calculadora()
	{
		super( "GridLayout Demo" );
		gridLayout1 = new GridLayout( 4, 5 , 2, 2); // 2 por 3; lacunas de 5
		container = getContentPane(); // obtém painel de conteúdo
		setLayout( gridLayout1 ); // configura o layout JFrame
		buttons = new JButton[ names.length ]; // cria array de JButtons
		texto = new JTextField(20);
		
		for ( int count = 0; count < names.length; count++ )
		{
			buttons[ count ] = new JButton( names[ count ] );
			buttons[ count ].addActionListener( this ); // registra o listener
			add( buttons[ count ] ); // adiciona o botão ao JFrame
		} // for final
	} // fim do construtor GridLayoutFrame

	// trata eventos de botão alternando entre layouts
	public void actionPerformed( ActionEvent event )
	{
		if ( toggle )
		container.setLayout( gridLayout1 ); // configura layout como segundo
		else
		container.setLayout( gridLayout1 ); // configura layout como primeiro
		toggle = !toggle; // alterna para valor oposto
		container.validate(); // refaz o layout do contêiner
	} // fim do método actionPerformed
} // fim da classe Calculadora

a dúvida é a seguinte, como eu coloco o JTextField na parte de cima da tela pra exibir somente os valores que serão calculados, pq colocando normalmente igual eu fiz no código, ele fica todo desordenado na telinha…

No aguardo,

Abs,

34 Respostas

victorrgds

postei sem o JLabel, mas ja está com o JLabel e setEditable(false)…agora só preciso saber como deixo ele no topo da tela…sem ficar ao lado dos botões…

digolipertte

Porque vc não usa todos usando o .setlocation()
Desse modo vc pode setar a localização de todos os seus componentes. é so colocar SeuFrame.setLayout(null);
e tem que dimensionar o tamanho do frame SeuFrame.setSize(700, 250); //aqui vc coloca o tamanho do seu frame
e quando for add botões ou qualquer outra coisa vc usa botao.setLocation(100,50);
Espero ter ajudado.
a outra coisa bacana seria tirar a opção de maximizar iria ficar bem bacana.

victorrgds

cara, esse setLocation eu nunca usei, no caso ele faria oq ue ?

victorrgds

testei aqui e não deu certo…

InicianteJavaHenriqu

digolipertte:
Porque vc não usa todos usando o .setlocation()
Desse modo vc pode setar a localização de todos os seus componentes. é so colocar SeuFrame.setLayout(null);
e tem que dimensionar o tamanho do frame SeuFrame.setSize(700, 250); //aqui vc coloca o tamanho do seu frame
e quando for add botões ou qualquer outra coisa vc usa botao.setLocation(100,50);
Espero ter ajudado.
a outra coisa bacana seria tirar a opção de maximizar iria ficar bem bacana.

Ficaria pior ainda.

Faça o seguinte: set o layout de seu JFrame para BorderLayout e adicione seu JTextField na posição NORT (jframe.add(jtextfield, BorderLayout.NORT), depois adicione um JPanel na posição CENTER do seu JFrame (jframe.add(jpanel, BorderLayout.CENTER) e set o layout do JPanel para GridLayout(qt de linhas desejadas, qt de colunas desejadas) e adicione os botões neste JPanel (jpanel.add(jbutton).

:thumbup:

victorrgds

farei as alterações e postarei aqui o resultado Henrique, obrigado! :smiley:

InicianteJavaHenriqu

De nada :smiley:

:thumbup:

victorrgds

Henrique, deu certo cara…só me explica essa parte pq eu não entendi direito e acabei fazendo bosta…

"e set o layout do JPanel para GridLayout(qt de linhas desejadas, qt de colunas desejadas) e adicione os botões neste JPanel (jpanel.add(jbutton). "

como ficaria isso ?

pra utilizar o border e o grid na mesma tela eu vou ter que criar 2 classes e fazer um extend ?

confundiu tudo agora…rsrs

abs

InicianteJavaHenriqu

Não. Cada contêiner Swing aceita um gerenciador de layout diferente, assim você pode “combinar” vários layout em uma tela.

Segue um exemplo, só a montagem da tela, os eventos e funcionalidades ficaram por sua conta :smiley:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 *
 * @author Henrique Ferreira da Silva
 */
public class Calculadora extends JFrame {

    private final String names[] = {"1", "2", "3", "+", "C", "4", "5", "6", "-", "CE", "7", "8", "9", "*", "RAIZ", "+/-", "0", ".", "/", "="};

    public Calculadora() {
        /*
         * Por padrão, o gerenciador de layout do JFrame é BorderLayout.
         * Adicionamos um novo JTextField na posição norte do JFrame.
         */
        add(new JTextField(), BorderLayout.NORTH);
        /*
         * Por padrão, o gerenciador de layout do JPanel é FlowLayout. Porém,
         * adicionamos um novo JPanel e alteramos seu gerenciador de layout para
         * GridLayout, com 4 linhas, 6 colunas, 5 em espaçamento horizontal e 5
         * em espaçamento vertical entre os componentes.
         */
        JPanel painel = new JPanel(new GridLayout(4, 6, 5, 5));
        for (byte i = 0; i < 20; i++) {
            /**
             * Adicionamos 1 botão em cada célula do GridLayout do painel, da
             * seguinte maneira: 1º botão na 1º linha da 1º coluna, 2º botão na
             * 1º linha da 2º coluna, 3º botão na 1º linha da 3º coluna, e assim
             * por diante, até completar todas as colunas de cada linha.
             */
            painel.add(new JButton(names[i]));
        }
        /**
         * Adicionamos o painel no JFrame, este painel irá preencher todos os
         * espaços restantes do BorderLayout, são eles BorderLayout.CENTER,
         * BorderLayout.EAST, BorderLayout.WEST e BorderLayout.SOUTH.
         */
        add(painel);
        setTitle("Calculadora");
        setSize(400, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setLocationRelativeTo(null);
    }

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

:thumbup:

victorrgds

Obrigado mais uma vez Henrique, pude perceber que nessa linha

add(new JTextField(), BorderLayout.NORTH); vc não deu um nome ao JText, na minha concepção era necessário fazer isso…tipo

texto = new JTextField, borde…ou posso fazer desse jeito tbm ?

InicianteJavaHenriqu

Sim, eu instanciei e adicionei o JTextField de uma fez (pq era só um exemplo), mas você terá que declara-lo lá em cima:

private JTextField texto = new JTextField();

E terá que fazer isto também com os JButtons.

:thumbup:

victorrgds

Outra coisa, como eu vou ter que dar uma função para cada botão, tenho que criar eles individualmente, ao invés de criar um array de botões ?

InicianteJavaHenriqu

Tanto faz se será um array de botão ou não, você precisará adicionar eventos em cada um deles.

:thumbup:

victorrgds

Henrique, vc pode me dar um exemplo de como criar a função de um botão cara, pq eu até segui uns exemplos aqui do guj msm, pesquisei um pouco e não deram certo…

qual a maneira mais fácil de fazer isso ?

abs,

victorrgds

na verdade eu não to sabendo como declaro a posição do array no actionPerformed…por exemplo, eu fiz assim:

public void actionPerformed(ActionEvent evento)
		{
			//JOptionPane.showMessageDialog(null, getSize());
			if(buttons[0].getSource() == buttons[0])
			{
				int valor;
				valor = Integer.parseInt(texto.getText());
				valor = buttons[0];
				texto.setText(""+valor);
			}
		} // Fecha o método actionPerformed
digolipertte
botao.addActionListener(new ActionListener() {    
            
            @Override    
            public void actionPerformed(ActionEvent arg0) {    
                   
            	   
                  //Aqui vc coloca oque vc quer que o botão faça......
            }    
        });
Não esqueça de colocar os imports que pode ter sido o erro dos outros exeplos.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;

Se não der posta seu codigo ai pra ficar mais facil a explicação.

victorrgds

Opa, então digo…o código ficou assim:

import java.awt.BorderLayout;  
import java.awt.GridLayout;  
import javax.swing.JButton;  
import javax.swing.JFrame;  
import javax.swing.JPanel;  
import javax.swing.JTextField;  
import java.awt.event.ActionEvent;  
import java.awt.event.ActionListener;  
import java.awt.*;   

 
public class Calculadora extends JFrame {  
  
    private final String names[] = {"1", "2", "3", "+", "C", "4", "5", "6", "-", "CE", "7", "8", "9", "*", "RAIZ", "+/-", "0", ".", "/", "="};  
  	 JTextField texto;	 
	 
    public Calculadora() 
	 {
                
			buttons = new JButton[ names.length ];
			texto = new JTextField(20);
			add(new JTextField(), BorderLayout.NORTH);  
			JPanel painel = new JPanel(new GridLayout(4, 6, 5, 5));  
					 
        
		  for (int i = 0; i < 20; i++) 
		  {          
            painel.add(new JButton(names[i]));  
        }  
       
        add(painel);  
        setTitle("Calculadora");  
        setSize(400, 400);  
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        setResizable(false);  
        setLocationRelativeTo(null);  
    }  
  
  		buttons[i].addActionListener(new ActionListener() {      
              
        @Override      
        public void actionPerformed(ActionEvent arg0) 
				{      
      	      if(buttons[0].getSource == buttons[0])
					{
						int valor;
						valor = Integer.parseInt(texto.getText());
						valor = buttons[0];  
                	texto.setText(""+valor);       
               }      
                
            }      
        }
		);  
  					
			
			  
	 
	 public static void main(String[] args) {  
        new Calculadora().setVisible(true);  
    }  
}

A minha dúvida é:

buttons[i].addActionListener(new ActionListener() {      
              
        @Override      
        public void actionPerformed(ActionEvent arg0) 
				{      
      	      if(buttons[0].getSource == buttons[0])
					{
						int valor;
						valor = Integer.parseInt(texto.getText());
						valor = buttons[0];  
                	texto.setText(""+valor);       
               }      
                
            }      
        }
		);

Como eu criei um array de botões, como eu defino esse botão ali no ActionListener, pois no caso acima coloquei buttons[0] que no caso é o meu array, mas não deu certo…pode ser uma duvida idiota, porém eu não to conseguindo :S

abs,

RiQuInHo_

olha cara fiz essa como exemplo mas usei o NB para a interface

//Calculadora Simples em Java para iniciantes, desenvolvida no NetBeans 7.0 


public class Calculadora extends javax.swing.JFrame {

    public Calculadora() {
        initComponents();
    }
/*Variaveis booleanas, todas estão sendo iniciadas como "false", quando pressionar o botão "=", 
  elas irão identificar qual operação será realizada*/
boolean clickSomar=false, clickSubtrair=false, clickMultiplicar=false, clickDividir=false;
//Variáveis double, armazenarão os valores digitados e o resultado da operação
double primeiroValor, segundoValor, resultado;
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        tf_exibir = new javax.swing.JTextField();
        bt_8 = new javax.swing.JButton();
        bt_7 = new javax.swing.JButton();
        bt_9 = new javax.swing.JButton();
        bt_somar = new javax.swing.JButton();
        bt_4 = new javax.swing.JButton();
        bt_5 = new javax.swing.JButton();
        bt_6 = new javax.swing.JButton();
        bt_subtrair = new javax.swing.JButton();
        bt_1 = new javax.swing.JButton();
        bt_2 = new javax.swing.JButton();
        bt_3 = new javax.swing.JButton();
        bt_multiplicar = new javax.swing.JButton();
        bt_zero = new javax.swing.JButton();
        bt_decimal = new javax.swing.JButton();
        bt_igual = new javax.swing.JButton();
        bt_dividir = new javax.swing.JButton();
        bt_limpar = new javax.swing.JButton();
        bt_sair = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tf_exibir.setEditable(false);
        tf_exibir.setFont(new java.awt.Font("Digital Readout Upright", 0, 36)); // NOI18N
        tf_exibir.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        tf_exibir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tf_exibirActionPerformed(evt);
            }
        });

        bt_8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bt_8.setText("8");
        bt_8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_8ActionPerformed(evt);
            }
        });

        bt_7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bt_7.setText("7");
        bt_7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_7ActionPerformed(evt);
            }
        });

        bt_9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bt_9.setText("9");
        bt_9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_9ActionPerformed(evt);
            }
        });

        bt_somar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bt_somar.setText("+");
        bt_somar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_somarActionPerformed(evt);
            }
        });

        bt_4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bt_4.setText("4");
        bt_4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_4ActionPerformed(evt);
            }
        });

        bt_5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bt_5.setText("5");
        bt_5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_5ActionPerformed(evt);
            }
        });

        bt_6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bt_6.setText("6");
        bt_6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_6ActionPerformed(evt);
            }
        });

        bt_subtrair.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bt_subtrair.setText("-");
        bt_subtrair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_subtrairActionPerformed(evt);
            }
        });

        bt_1.setFont(new java.awt.Font("Tahoma", 0, 14));
        bt_1.setText("1");
        bt_1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_1ActionPerformed(evt);
            }
        });

        bt_2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bt_2.setText("2");
        bt_2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_2ActionPerformed(evt);
            }
        });

        bt_3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bt_3.setText("3");
        bt_3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_3ActionPerformed(evt);
            }
        });

        bt_multiplicar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bt_multiplicar.setText("x");
        bt_multiplicar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_multiplicarActionPerformed(evt);
            }
        });

        bt_zero.setFont(new java.awt.Font("Tahoma", 0, 14));
        bt_zero.setText("0");
        bt_zero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_zeroActionPerformed(evt);
            }
        });

        bt_decimal.setFont(new java.awt.Font("Tahoma", 0, 14));
        bt_decimal.setText(".");
        bt_decimal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_decimalActionPerformed(evt);
            }
        });

        bt_igual.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bt_igual.setText("=");
        bt_igual.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_igualActionPerformed(evt);
            }
        });

        bt_dividir.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bt_dividir.setText("/");
        bt_dividir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_dividirActionPerformed(evt);
            }
        });

        bt_limpar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bt_limpar.setText("C");
        bt_limpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_limparActionPerformed(evt);
            }
        });

        bt_sair.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        bt_sair.setText("SAIR");
        bt_sair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_sairActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(tf_exibir, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(bt_7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bt_8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bt_9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bt_somar, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(bt_4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bt_5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bt_6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bt_subtrair, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(bt_limpar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 92, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(bt_zero)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(bt_decimal, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(bt_1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(bt_2, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(bt_sair, javax.swing.GroupLayout.DEFAULT_SIZE, 92, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(bt_3)
                                    .addComponent(bt_igual))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(bt_dividir, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(bt_multiplicar))))))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {bt_1, bt_2, bt_3, bt_4, bt_5, bt_6, bt_7, bt_8, bt_9, bt_decimal, bt_dividir, bt_igual, bt_multiplicar, bt_somar, bt_subtrair, bt_zero});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(tf_exibir, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bt_7)
                    .addComponent(bt_8)
                    .addComponent(bt_9)
                    .addComponent(bt_somar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bt_4)
                    .addComponent(bt_5)
                    .addComponent(bt_6)
                    .addComponent(bt_subtrair))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bt_1)
                    .addComponent(bt_2)
                    .addComponent(bt_3)
                    .addComponent(bt_multiplicar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bt_zero)
                    .addComponent(bt_decimal)
                    .addComponent(bt_igual)
                    .addComponent(bt_dividir))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bt_limpar)
                    .addComponent(bt_sair))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {bt_1, bt_2, bt_3, bt_4, bt_5, bt_6, bt_7, bt_8, bt_9, bt_decimal, bt_dividir, bt_igual, bt_multiplicar, bt_somar, bt_subtrair, bt_zero});

        pack();
    }// </editor-fold>                        

//Ações dos botões    
private void bt_zeroActionPerformed(java.awt.event.ActionEvent evt) {                                        
tf_exibir.setText(tf_exibir.getText()+bt_zero.getText());
/*tf_exibir=nome do JTextField
  bt_zero=nome do Jbutton
  .setText=comando para exibir conteúdo no JTextField
  .getText=comando que captura o texto do componente ("bt_zero" o texto está como 0)*/
}                                       

private void bt_decimalActionPerformed(java.awt.event.ActionEvent evt) {                                           
tf_exibir.setText(tf_exibir.getText()+bt_decimal.getText()); /*Para operações decimais deve-se usar o ponto ".",
                                                               atenção para não confundir com a vírgula ",", 
                                                               pois as operações não irão funcionar*/
}                                          

private void bt_1ActionPerformed(java.awt.event.ActionEvent evt) {                                     
tf_exibir.setText(tf_exibir.getText()+bt_1.getText());
}                                    

private void tf_exibirActionPerformed(java.awt.event.ActionEvent evt) {                                          
// TODO add your handling code here:
}                                         

private void bt_2ActionPerformed(java.awt.event.ActionEvent evt) {                                     
tf_exibir.setText(tf_exibir.getText()+bt_2.getText());
}                                    

private void bt_3ActionPerformed(java.awt.event.ActionEvent evt) {                                     
tf_exibir.setText(tf_exibir.getText()+bt_3.getText());
}                                    

private void bt_4ActionPerformed(java.awt.event.ActionEvent evt) {                                     
tf_exibir.setText(tf_exibir.getText()+bt_4.getText());
}                                    

private void bt_5ActionPerformed(java.awt.event.ActionEvent evt) {                                     
tf_exibir.setText(tf_exibir.getText()+bt_5.getText());
}                                    

private void bt_6ActionPerformed(java.awt.event.ActionEvent evt) {                                     
tf_exibir.setText(tf_exibir.getText()+bt_6.getText());
}                                    

private void bt_7ActionPerformed(java.awt.event.ActionEvent evt) {                                     
tf_exibir.setText(tf_exibir.getText()+bt_7.getText());
}                                    

private void bt_8ActionPerformed(java.awt.event.ActionEvent evt) {                                     
tf_exibir.setText(tf_exibir.getText()+bt_8.getText());
}                                    

private void bt_9ActionPerformed(java.awt.event.ActionEvent evt) {                                     
tf_exibir.setText(tf_exibir.getText()+bt_9.getText());
}                                    

private void bt_somarActionPerformed(java.awt.event.ActionEvent evt) {                                         
capturar(); //executa o método capturar, POO, ver método abaixo
tf_exibir.setText(""); //no JTextField será exibido um valor vazio (""), para melhor visualização
clickSomar=true;/* a variavel do tipo booleana recebe o valor "true" (verdadeiro), então identificamos
                   a operação como sendo uma soma.*/
}                                        

private void bt_subtrairActionPerformed(java.awt.event.ActionEvent evt) {                                            
capturar();
tf_exibir.setText("");
clickSubtrair=true;
}                                           

private void bt_multiplicarActionPerformed(java.awt.event.ActionEvent evt) {                                               
capturar();
tf_exibir.setText("");
clickMultiplicar=true;
}                                              

private void bt_dividirActionPerformed(java.awt.event.ActionEvent evt) {                                           
capturar();
tf_exibir.setText("");
clickDividir=true;
}                                          

private void bt_igualActionPerformed(java.awt.event.ActionEvent evt) {                                         
segundoValor=(Double.parseDouble(tf_exibir.getText()));/*a variável do tipo double recebe o valor do JTextField, 
                                                         como o valor é do tipo string, é necessário converter
                                                         para double (Double.parseDouble("insira aqui o que você 
                                                         irá converter de string para double"))*/

/*Identifica qual operação será realizada, a variável boolena é responsável por essa identificação*/
if(clickSomar)
{
  resultado=primeiroValor+segundoValor; //Executa a respectiva operação, neste caso, será uma soma.
  exibirResultado();//Executa o método, POO, ver detalhes abaixo.
  clickSomar=false;/*A variável recebe novamento o valor "false", deixando a calculadora livre para receber outra
                     operaçao*/
}
else if(clickSubtrair)
  {
  resultado=primeiroValor-segundoValor;
  exibirResultado();
  clickSubtrair=false;
  }
  
else if(clickMultiplicar)
    {
    resultado=primeiroValor*segundoValor;
    exibirResultado();
    clickMultiplicar=false;
    }
    
     //Tratamento de erro de divisões por zero, impossíveis. 
     else
    {
      if(segundoValor==0) //se o segundo valor for igual a zero
      {
      tf_exibir.setText("ERRO");//Exibir "ERRO", pois a operação não é possível
      }
      else // caso o segundo valor for diferente de zero
        {
          resultado=primeiroValor/segundoValor; //Executa a operação como os exemplos acima.
          exibirResultado();
        }
      clickDividir=false;
    }

}                                        

private void bt_limparActionPerformed(java.awt.event.ActionEvent evt) {                                          
tf_exibir.setText("");//Limpa o JTextField (tf_exibir), inserindo um valor vazio "".
}                                         

private void bt_sairActionPerformed(java.awt.event.ActionEvent evt) {                                        
System.exit(0);//Comando para fechar a aplicação
}                                       

void capturar()
{
primeiroValor=(Double.parseDouble(tf_exibir.getText()));
//a variável do tipo double recebe o valor do JTextField, como o valor é do tipo string, é necessário converter
// para double (Double.parseDouble("insira aqui o que você irá converter de string para double"))
}

void exibirResultado()
{
tf_exibir.setText(String.valueOf(resultado));/*Exibe o resultado da operação;
                                               como a variável "resultado" é do tipo double, deveremos converte-la
                                               para string, pois o JTextField (tf_exibir) aceita apenas string; 
                                               o comando utilizado será o "String.valueOf("insira a variável que
                                               será convertida de double para string")"*/
}

    public static void main(String args[]) {
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Calculadora().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton bt_1;
    private javax.swing.JButton bt_2;
    private javax.swing.JButton bt_3;
    private javax.swing.JButton bt_4;
    private javax.swing.JButton bt_5;
    private javax.swing.JButton bt_6;
    private javax.swing.JButton bt_7;
    private javax.swing.JButton bt_8;
    private javax.swing.JButton bt_9;
    private javax.swing.JButton bt_decimal;
    private javax.swing.JButton bt_dividir;
    private javax.swing.JButton bt_igual;
    private javax.swing.JButton bt_limpar;
    private javax.swing.JButton bt_multiplicar;
    private javax.swing.JButton bt_sair;
    private javax.swing.JButton bt_somar;
    private javax.swing.JButton bt_subtrair;
    private javax.swing.JButton bt_zero;
    private javax.swing.JTextField tf_exibir;
    // End of variables declaration                   
}
victorrgds

Riquinho, agradeço a tentativa de ajudar, só que…como eu to utilizando o Jgrasp pra desenvolver essa calculadora, esse seu código me deixo ainda mais confuso…pq no caso,

eu estou com dúvida somente naquela parte que postei anteriormente, como eu faço pra dar função a cada botão…;(

victorrgds

Alguem pode me ajudar ?

InicianteJavaHenriqu

É só usar o código que o digolipertte e RiQuInHo_$_$ postaram:

botao[i].addActionListener(new ActionListener() {//Por exemplo, este botão é o 8      
              
            @Override      
            public void actionPerformed(ActionEvent evt) {                          
                  //Aqui vc coloca o que vc quer que o botão faça..... neste caso chamamos o método bt_8();
                  bt_8();
            }      
        });  


private void bt_8() {                                       
           //Aqui vc guarda o valor 8 para depois realizar o calculo desejado, por exemplo:
           primeiroValor = 8;           
}

Os demais botões segue este mesmo esquema.

O código do RiQuInHo_$_$ pode ser extenso, mas a maneira mais fácil de aprender (pelo menos foi assim para mim) é pegar estes códigos e comentar o que não se sabe, linha por linha e aprender usando uma IDE de verdade como o NetBeans ou Eclipse.

RiQuInHo_

cara se vc pegar o codigo e degugar vc vai saber aonde estão as chamadas dos botões.

é tão simples.

victorrgds

Testarei…o problema é que somos obrigado a utilizar a IDE JGrasp e é um LIXO…

RiQuInHo_

manda seu professor à merda isso sim…

na facul eu uso a IDE 7 do NB muito simples e o eclipse.

victorrgds

RiQuInHo_$_$:
cara se vc pegar o codigo e degugar vc vai saber aonde estão as chamadas dos botões.

é tão simples.

é que no meu caso eu criei um vetor de botões, não declarei botão por botão, mas acho que vou fazer isso pra facilitar mais agora…

victorrgds

Aqui o método do botão na posição 0 do vetor no caso, eu só posso ta cego ou realmente ta errado, mas não ta funcionando galera…

buttons[i].addActionListener(new ActionListener() 
		  {        
        		public void actionPerformed(ActionEvent evt) 
				{                            
             	if(buttons[i].getSource() == buttons[0])
     				{
      				int valor;
      				valor = Integer.parseInt(texto.getText());
      				valor = buttons[0]; 
                 texto.setText(""+valor);       
               }      
                
        }      
       
  );}  
  
  private void buttons() 
  {                                         
           		                 
         primeiroValor = 1;             
  }

Desculpa incomodar tanto mas é que realmente essa parte ta me deixando puto da vida…

InicianteJavaHenriqu

victorrgds:
Aqui o método do botão na posição 0 do vetor no caso, eu só posso ta cego ou realmente ta errado, mas não ta funcionando galera…

buttons[i].addActionListener(new ActionListener() 
		  {        
        		public void actionPerformed(ActionEvent evt) 
				{                            
             	if(buttons[i].getSource() == buttons[0])
     				{
      				int valor;
      				valor = Integer.parseInt(texto.getText());
      				valor = buttons[0]; 
                 texto.setText(""+valor);       
               }      
                
        }      
       
  );}  
  
  private void buttons() 
  {                                         
           		                 
         primeiroValor = 1;             
  }

Desculpa incomodar tanto mas é que realmente essa parte ta me deixando puto da vida…

Pra que você continua testando qual botão acionou o evento :?: Eu já não mostrei lá em cima como se faz :!: :?:

Isto não é um trabalho de casa :?: seu profº não precisa saber em qual IDE foi feito.

:thumbup:

victorrgds

Negativo Henrique, é pra ser entregue…por isso não posso utilizar outra IDE…:S

InicianteJavaHenriqu

Sim, mas se você fizer em outra IDE (no conforto do lar) e abrir (na frente do profº na instituição de ensino) neste JGrasp :wink:

Isto na verdade é o de menos, código Java pode ser feito até em um editor de texto qualquer. IDE ajuda mas não influencia no código.

:thumbup:

victorrgds

É que na minha facul, eles meio que proibem de utilizar o NB, no máximo o Eclipse…

InicianteJavaHenriqu

:lol: Me passa o nome desta instituição, para mim não correr o perigo de estudar lá :smiley:

Enfim…

victorrgds já estamos na 3ª página só para fazer uma calculadora, nem uma científica demoraria tanto :wink:

Releia as páginas anteriores, e observe as dicas do pessoal que você consegue fazer e qualquer dúvida nova você posta.

:thumbup:

RiQuInHo_

:lol: Me passa o nome desta instituição, para mim não correr o perigo de estudar lá :smiley:

Enfim…

victorrgds já estamos na 3ª página só para fazer uma calculadora, nem uma científica demoraria tanto :wink:

Releia as páginas anteriores, e observe as dicas do pessoal que você consegue fazer e qualquer dúvida nova você posta.

:thumbup:

idem ++

se for cientifica coitado !!! rsrs

mas cara ta embassado o voce quer…vc ta fazendo HARDCODE certo! mesmo dessa forma da para se usar as formas das postagem anteriores…

RiQuInHo_

acabei fazendo essa por exemplo testa ai a bagaça

só espero que vc saiba o que são Imports :roll:

public class CalculadoraTeste 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 CalculadoraTeste() {
        //Ajuste do formulário
        setTitle("Calculadora");
        setSize(245, 260);
        setLocation(WIDTH, WIDTH);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        getContentPane().setLayout(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 CalculadoraTeste();
        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;
    }
}
G

Achei essa na internet e me ajudou a montar uma

/**
 * importando os pacotes necessários
 */
 
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 * @(#)Calculadora.java
 *
 * Calculadora application
 *
 * @author Carlos Coelho
 * @version 1.00 2010/10/02
 */
 
public class Calculadora extends JFrame implements ActionListener
{

    /**
     * variáveis do tipo JButton
     */
    
     // criando os botões para os cálculos
     private JButton bt_somar;
     private JButton bt_subtrair;
     private JButton bt_multiplicar;
     private JButton bt_dividir;
     private JButton bt_ce;
     private JButton bt_back;
     private JButton bt_igual;
     private JButton bt_ponto;
     
     // criando os botões numéricos 
     private JButton bt_1;
     private JButton bt_2;
     private JButton bt_3;
     private JButton bt_4;
     private JButton bt_5;
     private JButton bt_6;
     private JButton bt_7;
     private JButton bt_8;
     private JButton bt_9;
     private JButton bt_0;

    /**
     * variável do tipo JLabel
     * @access private
     */
    
    // criando o campo onde será inserido o nome do desenvolvedor  
    private JLabel l_author;
         
    /**
     * variável do tipo JTextField
     * @access private
     */
    
    // criando o campo onde será inserido os valores clicados  
    private JTextField tf_calculadora;

    /**
     * variável do tipo JMenuBar
     * @access private
     */
    
    // criando a barra de menu onde será inserido o nome da nossa aplicação
    private JMenuBar barra_menu;
   
    /**
     * variável do tipo JMenu
     * @access private
     */
    
    // criando menu onde será inserido o nome "Calculadora"  
    private JMenu menu_calculadora;

    /**
     * variável do tipo double
     * @access private
     */
    
    // criando as variáveis que receberão os valore clicados e calculados   
    private double num       = 0;
    private double resultado = 0;

    /**
     * variável do tipo char
     * @access private
     */
    
    // criando a variável que receberá o comando clicado      
    private char tecla_pressionada;
   
    /**
     * variável do tipo boolean
     * @access private
     */
    
    // criando uma variável para verificar se um botão foi clicado
    private boolean click = false;
   
   
    /**
     * método construtor da classe Calculadora
     * @access public
     */
          
     public Calculadora()
     {
       
           setTitle("Calculadora"); // seta um título para a janela
           setSize(280,280); // seta uma dimensão
           setLocationRelativeTo(null); // seta a posição
           setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // define que a execução será finalizada quando a janela for fechada
           setResizable(false); // seta para não ser possível redimensionar a janela
       
           // getContentPane() é um método da classe JFrame que retorna um JPanel, que é o painel principal da janela
           getContentPane().setLayout(null); //informa que não vai usar Gerenciador de Layout

           // instancia os botões e atribuindo os seus nomes
           bt_somar       = new JButton("+");
           bt_multiplicar = new JButton("*");
           bt_dividir     = new JButton("/");
           bt_subtrair    = new JButton("-");
           bt_ponto       = new JButton(".");    
           bt_1           = new JButton("1");
           bt_2           = new JButton("2");
           bt_3           = new JButton("3");
           bt_4           = new JButton("4");
           bt_5           = new JButton("5");
           bt_6           = new JButton("6");
           bt_7           = new JButton("7");
           bt_8           = new JButton("8");
           bt_9           = new JButton("9");
           bt_0           = new JButton("0");
           bt_back        = new JButton("Backspace");
           bt_ce          = new JButton("ce");
           bt_igual       = new JButton("=");
           tf_calculadora = new JTextField(100);
     
           barra_menu = new JMenuBar(); // instancia a barra de menu       
           setJMenuBar(barra_menu); // seta a barra de menu na janela
           menu_calculadora   = new JMenu("Calculadora"); // instancia o menu e dá um nome
           menu_calculadora.setEnabled(false); // desativa para click
           barra_menu.add(menu_calculadora); // insere o menu na barra de menu
          
           // formatando o campo JTextField
           tf_calculadora.setHorizontalAlignment(tf_calculadora.RIGHT); // seta o texto para a direita
           tf_calculadora.setText("0"); // setamos o valor zero(0), como padrão
           tf_calculadora.setCaretPosition(1); // seta o cursor na posição um(1)
           tf_calculadora.setEditable(false); // evita a edição pelo teclado
           tf_calculadora.setBackground(Color.white); // seta um fundo branco

           // setando cores para os textos nos botões
           bt_1            .setForeground(Color.blue);
           bt_2            .setForeground(Color.blue);
           bt_3            .setForeground(Color.blue);
           bt_4            .setForeground(Color.blue);
           bt_5            .setForeground(Color.blue);
           bt_6            .setForeground(Color.blue);
           bt_7            .setForeground(Color.blue);
           bt_8            .setForeground(Color.blue);
           bt_9            .setForeground(Color.blue);
           bt_0            .setForeground(Color.blue);
           bt_back         .setForeground(Color.red);
           bt_ce           .setForeground(Color.red);
           bt_somar        .setForeground(Color.red);
           bt_multiplicar  .setForeground(Color.red);
           bt_subtrair     .setForeground(Color.red);
           bt_dividir      .setForeground(Color.red);
           bt_ponto        .setForeground(Color.red);
           bt_igual        .setForeground(Color.red);       

           //Posicionando os componentes na Tela
           //objeto.setBounds (posicaoColuna,posicaoLinha,comprimentodalinha,alturadalinha);    
           tf_calculadora.setBounds(20,  10,  230, 25);
           bt_back       .setBounds(20,  45,  110, 30);
           bt_ce         .setBounds(140, 45,  110, 30);      
           bt_7          .setBounds(20,  80,  50,  30);             
           bt_8          .setBounds(80,  80,  50,  30);                    
           bt_9          .setBounds(140, 80,  50,  30);             
           bt_dividir    .setBounds(200, 80,  50,  30);
           bt_4          .setBounds(20,  115, 50,  30);             
           bt_5          .setBounds(80,  115, 50,  30);                    
           bt_6          .setBounds(140, 115, 50,  30);             
           bt_multiplicar.setBounds(200, 115, 50,  30);
           bt_1          .setBounds(20,  150, 50,  30);             
           bt_2          .setBounds(80,  150, 50,  30);                    
           bt_3          .setBounds(140, 150, 50,  30);
           bt_subtrair   .setBounds(200, 150, 50,  30);
           bt_0          .setBounds(20,  185, 50,  30);
           bt_ponto      .setBounds(80,  185, 50,  30);                    
           bt_igual      .setBounds(140, 185, 50,  30);
           bt_somar      .setBounds(200, 185, 50,  30);

           // registra os botões ao Listener
           bt_somar      .addActionListener(this);
           bt_multiplicar.addActionListener(this);
           bt_subtrair   .addActionListener(this);
           bt_dividir    .addActionListener(this);
           bt_ponto      .addActionListener(this);
           bt_0          .addActionListener(this);
           bt_1          .addActionListener(this);      
           bt_2          .addActionListener(this);
           bt_3          .addActionListener(this);
           bt_4          .addActionListener(this);
           bt_5          .addActionListener(this);
           bt_6          .addActionListener(this);
           bt_7          .addActionListener(this);
           bt_8          .addActionListener(this);
           bt_9          .addActionListener(this);
           bt_igual      .addActionListener(this);
           bt_back       .addActionListener(this);
           bt_ce         .addActionListener(this);
       
       
           // adiciona os botões ao JPanel
           // getContentPane() é um método da classe JFrame que retorna um JPanel, que é o painel principal da janela
           getContentPane().add(tf_calculadora);
           getContentPane().add(bt_back);
           getContentPane().add(bt_ce);
           getContentPane().add(bt_7);
           getContentPane().add(bt_8);
           getContentPane().add(bt_9);
           getContentPane().add(bt_4);
           getContentPane().add(bt_5);
           getContentPane().add(bt_6);      
           getContentPane().add(bt_1);
           getContentPane().add(bt_2);
           getContentPane().add(bt_3);        
           getContentPane().add(bt_0);
           getContentPane().add(bt_igual);        
           getContentPane().add(bt_multiplicar);
           getContentPane().add(bt_subtrair);
           getContentPane().add(bt_dividir);
           getContentPane().add(bt_somar);
           getContentPane().add(bt_ponto);
          
    }

    /**
     * método para tratar eventos de click de botão
     * @access public
     */
    
    public void actionPerformed(ActionEvent acao)
    {
          
        // o primeiro número é zero(0) e o segundo não é ponto ?
        if((tf_calculadora.getText().length() == 1) && (tf_calculadora.getText() .substring(0,1).equals("0")) && (!tf_calculadora.getText().substring(1,1).equals(".")))
        {
            tf_calculadora.setText(tf_calculadora.getText().replace("0",""));
        }
          
        // pressionou o botão ponto ?
        if(acao.getSource() == bt_ponto)
        {
            // é o segundo valor ?
            if(click)
            {
                tf_calculadora.setText(null);
               
                // tem ponto ?
                if(tf_calculadora.getText().indexOf(".") < 0)
                {
                    // é o primeiro caracter ?
                    if(tf_calculadora.getText().length() < 1)
                    {
                        tf_calculadora.setText("0.");
                    }
                    else
                    {
                        tf_calculadora.setText(".");
                    }
                }
               
            }            
            else
            {
                // tem ponto ?
                if(tf_calculadora.getText().indexOf(".") < 0)
                {
                    // é o primeiro caracter ?
                    if(tf_calculadora.getText().length() < 1)
                    {
                        tf_calculadora.setText("0.");
                    }
                    else
                    {
                        tf_calculadora.setText(tf_calculadora.getText()+".");
                    }
                }
            }
           
            click = false;
        }
          
        // pressionou o botão número 0 ?
        if(acao.getSource() == bt_0)
        {
            // é o segundo valor ?
            if(click)
            {
                tf_calculadora.setText("0");    
            }            
            else
            {
                // o primeiro caracter é 0 ?
                if((tf_calculadora.getText().length() == 1) && (tf_calculadora.getText().equals("0")))
                {
                    tf_calculadora.setText("0");
                }
                else
                {
                    tf_calculadora.setText(tf_calculadora.getText()+"0");
                }
            }
           
            click = false;
        }
       
        // pressionou o botão número 1 ?
        if(acao.getSource() == bt_1)
        {
            // é o segundo valor ?
            if(click)
            {
                tf_calculadora.setText("1");
            }            
            else
            {
                tf_calculadora.setText(tf_calculadora.getText()+"1");
            }
           
            click = false;
        }
       
        // pressionou o botão número 2 ?
        if(acao.getSource() == bt_2)
        {
            // é o segundo valor ?
            if(click)
            {
                tf_calculadora.setText("2");
            }            
            else
            {
                tf_calculadora.setText(tf_calculadora.getText()+"2");
            }
           
            click = false;
        }
       
        // pressionou o botão número 3 ?
        if(acao.getSource() == bt_3)
        {
            // é o segundo valor ?
            if(click)
            {
                tf_calculadora.setText("3");
            }            
            else
            {
                tf_calculadora.setText(tf_calculadora.getText()+"3");
            }
           
            click = false;
        }
       
        // pressionou o botão número 4 ?        
        if(acao.getSource() == bt_4)
        {
            // é o segundo valor ?
            if(click)
            {
                tf_calculadora.setText("4");
            }            
            else
            {
                tf_calculadora.setText(tf_calculadora.getText()+"4");
            }
           
            click = false;
        }
       
        // pressionou o botão número 5 ?
        if(acao.getSource() == bt_5)
        {
            // é o segundo valor ?
            if(click)
            {
                tf_calculadora.setText("5");
            }            
            else
            {
                tf_calculadora.setText(tf_calculadora.getText()+"5");
            }
           
            click = false;
        }
       
        // pressionou o botão número 6 ?
        if(acao.getSource() == bt_6)
        {
            // é o segundo valor ?
            if(click)
            {
                tf_calculadora.setText("6");
            }            
            else
            {
                tf_calculadora.setText(tf_calculadora.getText()+"6");
            }
           
            click = false;
        }
       
        // pressionou o botão número 7 ?
        if(acao.getSource() == bt_7)
        {
            // é o segundo valor ?
            if(click)
            {
                tf_calculadora.setText("7");
            }            
            else
            {
                tf_calculadora.setText(tf_calculadora.getText()+"7");
            }
           
            click = false;
        }
       
        // pressionou o botão número 8 ?
        if(acao.getSource() == bt_8)
        {
            // é o segundo valor ?
            if(click)
            {
                tf_calculadora.setText("8");
            }            
            else
            {
                tf_calculadora.setText(tf_calculadora.getText()+"8");
            }
           
            click = false;
        }
       
        // pressionou o botão número 9 ?
        if(acao.getSource() == bt_9)
        {
            // é o segundo valor ?
            if(click)
            {
                tf_calculadora.setText("9");
            }            
            else
            {
                tf_calculadora.setText(tf_calculadora.getText()+"9");
            }
           
            click = false;
        }
       
        // pressionou o botão + ?
        if(acao.getSource() == bt_somar)
           {
            click = true;
               tecla_pressionada = '+';
               num = Double.parseDouble(tf_calculadora.getText());
        }
       
        // pressionou o botão - ?
        if(acao.getSource() == bt_subtrair)
           {
            click = true;
               tecla_pressionada = '-';
               num = Double.parseDouble(tf_calculadora.getText());
        }
        
        // pressionou o botão * ?
        if(acao.getSource() == bt_multiplicar)
           {
            click = true;
               tecla_pressionada = '*';
               num = Double.parseDouble(tf_calculadora.getText());
        }
        
        // pressionou o botão número / ?
        if(acao.getSource() == bt_dividir)
           {
            click = true;
               tecla_pressionada = '/';
               num = Double.parseDouble(tf_calculadora.getText());          
        }
        
        // pressionou o botão ce ?
        if(acao.getSource() == bt_ce)
        {
            num = 0;
            resultado = 0;
            click = false;
            tecla_pressionada = ' ';
            tf_calculadora.setText("0");
        }
        
        // pressionou o botão back ?
        if(acao.getSource() == bt_back)
        {
            // o tamanho da string é maior que zero ?
            if(tf_calculadora.getText().length() > 0)
            {
                tf_calculadora.setText(tf_calculadora.getText() .substring(0,tf_calculadora.getText().length()-1));
            }
           
            // o tamanho da string é igual a zero ?    
            if(tf_calculadora.getText().length() == 0)
            {
                tf_calculadora.setText("0");
            }
           
        }
                 
        // pressionou o botão = ?
           if(acao.getSource() == bt_igual)
           {  
              
            // foi o + ?
            if(tecla_pressionada == '+')
            {
                  resultado = num + Double.parseDouble(tf_calculadora.getText());
            }
           
            // foi o - ?
            if(tecla_pressionada == '-')
            {
                  resultado = num - Double.parseDouble(tf_calculadora.getText());
            }
           
            // foi o * ?
            if(tecla_pressionada == '*')
            {
                  resultado = num * Double.parseDouble(tf_calculadora.getText());
            }
           
            // foi o / ?
            if(tecla_pressionada == '/')
            {
                resultado = num / Double.parseDouble(tf_calculadora.getText());
            }
           
            // converte para string e seta o texto
               tf_calculadora.setText(String.valueOf(resultado));
            
               click = true;
           
           }
          
     }
      
     /**
      * método principal da classe Calculadora
      * @access public
      */
                
     public static void main(String[] args)
     {
    
           JFrame Calc = new Calculadora(); // cria uma variável do tipo Calculadora e instancia
        
           Calc.setVisible(true); // mostra a Calculadora
     }
    
}
Criado 30 de abril de 2012
Ultima resposta 4 de mai. de 2012
Respostas 34
Participantes 5