Calculadora Simples em Java para iniciantes [código comentado]

3 respostas
A

Olá Pessoal,

Estou iniciando em Java e desenvolvi está calculadora bem básica em JFrame, com o NetBeans 7.0, comentei todo o código para que algum dia seja útil aos interessados.

Abraço.

//Calculadora Simples em Java para iniciantes, desenvolvida no NetBeans 7.0 - 12/09/2011
//Author Adriano A. Aquino

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                   
}

3 Respostas

Giulliano

Código gerado no NetBeans nunca é reutilizado…

se vc se aprofunda na linguagem Java vai descobrir isso.

Renatosantos

Parabéns cara Aqui funfou legal! :wink:

drsmachado

Não gosto de ser chato, tampouco por água no chopp alheio, mas, considero isto uma ação contra os princípios do guj.
É sabido que exercícios como calculadoras são comuns em cursos relacionados ao desenvolvimento.
Logo, disponibilizar o código completo (ainda que gerado pelo NB) é algo que torna os novatos mais preguiçosos.
Sei que a intenção foi boa, mas o inferno tá cheio de boas intenções.

O GUJ tem como principal função distribuir conhecimento (aquela história de ensinar a pescar) e não distribuir códigos prontos (dar o peixe).

Criado 12 de setembro de 2011
Ultima resposta 13 de set. de 2011
Respostas 3
Participantes 4