How to prevent a certain key from being sent to the program several times

Asked

Viewed 114 times

4

I’m making a calculator for year-end activity, which even works normally, as long as it doesn’t exceed typing. For example, if you sum two fractional numbers, it performs the entire sum correctly, but if we unintentionally type more than one point on the button, it pushes the application, forcing the user to write after cleaning with the CE/C button.

example of correct typing:

1.5 + 1.9 = 3.4

example of incorrect typing:

1.5 + 1.. 9 = does not display result and hangs until clear display.

When I perform consecutive operations also not sure. Example:

15 -2 -1 = 1.0 ? (12) 58/2*9 = 18.0 (261)

I am using this code for the program to capture the '.' point by the display a standard form component.

// pega o caracterer . e exibe . no display;
txtDisplayResult.setText(txtDisplayResult.getText()+".");

This is a problem of my code, otherwise it works well the basic functions of calculator.

In short: problems with duplicate dot typing and performing consecutive operations.

Follows the code:

import java.awt.*;

/*   * @author Spencer    */
public class Formulario extends javax.swing.JFrame {

public Formulario() {
    initComponents();
    //setando icone
    /*Toolkit kit = this.getDefaultToolkit();
  Image icone = kit.getImage("/images/calc.png");
  this.setIconImage(icone);*/

    /* ImageIcon icone = new ImageIcon("/images/calc.png");
  this.setIconImage((Image)icone);*/
  /* this.setLocation(300, 100);
   intialize();
}  
private void intialize(){
        this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("calc.png")));*/
}




 Double operando1, operando2; // catch value
 String operador; //operator

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jButton0 = new javax.swing.JButton();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jButton4 = new javax.swing.JButton();
    jButton5 = new javax.swing.JButton();
    jButton6 = new javax.swing.JButton();
    jButton7 = new javax.swing.JButton();
    jButton8 = new javax.swing.JButton();
    jButton9 = new javax.swing.JButton();
    jButton30 = new javax.swing.JButton();
    jButton31 = new javax.swing.JButton();
    jButton33 = new javax.swing.JButton();
    jButton34 = new javax.swing.JButton();
    jButton35 = new javax.swing.JButton();
    jButton36 = new javax.swing.JButton();
    jButton37 = new javax.swing.JButton();
    jButton38 = new javax.swing.JButton();
    txtDisplayResult = new javax.swing.JTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Calculadora");
    setResizable(false);

    jButton0.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton0.setText("0");
    jButton0.setPreferredSize(new java.awt.Dimension(30, 50));
    jButton0.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton0ActionPerformed(evt);
        }
    });

    jButton1.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton1.setText("1");
    jButton1.setPreferredSize(new java.awt.Dimension(50, 50));
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jButton2.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton2.setText("2");
    jButton2.setPreferredSize(new java.awt.Dimension(50, 50));
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    jButton3.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton3.setText("3");
    jButton3.setPreferredSize(new java.awt.Dimension(50, 50));
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });

    jButton4.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton4.setText("4");
    jButton4.setPreferredSize(new java.awt.Dimension(50, 50));
    jButton4.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton4ActionPerformed(evt);
        }
    });

    jButton5.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton5.setText("5");
    jButton5.setPreferredSize(new java.awt.Dimension(50, 50));
    jButton5.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton5ActionPerformed(evt);
        }
    });

    jButton6.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton6.setText("6");
    jButton6.setPreferredSize(new java.awt.Dimension(50, 50));
    jButton6.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton6ActionPerformed(evt);
        }
    });

    jButton7.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton7.setText("7");
    jButton7.setPreferredSize(new java.awt.Dimension(50, 50));
    jButton7.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton7ActionPerformed(evt);
        }
    });

    jButton8.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton8.setText("8");
    jButton8.setPreferredSize(new java.awt.Dimension(50, 50));
    jButton8.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton8ActionPerformed(evt);
        }
    });

    jButton9.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton9.setText("9");
    jButton9.setPreferredSize(new java.awt.Dimension(50, 50));
    jButton9.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton93ActionPerformed(evt);
        }
    });

    jButton30.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton30.setText(".");
    jButton30.setPreferredSize(new java.awt.Dimension(50, 50));
    jButton30.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton30ActionPerformed(evt);
        }
    });

    jButton31.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton31.setText("=");
    jButton31.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton31ActionPerformed(evt);
        }
    });

    jButton33.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton33.setText("/");
    jButton33.setPreferredSize(new java.awt.Dimension(50, 50));
    jButton33.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton33ActionPerformed(evt);
        }
    });

    jButton34.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton34.setText("*");
    jButton34.setPreferredSize(new java.awt.Dimension(50, 50));
    jButton34.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton34ActionPerformed(evt);
        }
    });

    jButton35.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton35.setText("-");
    jButton35.setPreferredSize(new java.awt.Dimension(50, 50));
    jButton35.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton35ActionPerformed(evt);
        }
    });

    jButton36.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton36.setText("+");
    jButton36.setPreferredSize(new java.awt.Dimension(50, 50));
    jButton36.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton36ActionPerformed(evt);
        }
    });

    jButton37.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton37.setText("C");
    jButton37.setPreferredSize(new java.awt.Dimension(30, 50));
    jButton37.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton37ActionPerformed(evt);
        }
    });

    jButton38.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
    jButton38.setText("CE");
    jButton38.setPreferredSize(new java.awt.Dimension(30, 50));
    jButton38.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton38ActionPerformed(evt);
        }
    });

    txtDisplayResult.setEditable(false);
    txtDisplayResult.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            txtDisplayResultActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(txtDisplayResult)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jButton0, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jButton30, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jButton31, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jButton37, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jButton38, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButton36, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton35, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton34, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton33, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
            .addContainerGap(13, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(txtDisplayResult, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton38, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addComponent(jButton36, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(1, 1, 1)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton35, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton37, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(2, 2, 2)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jButton34, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton33, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton31, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton0, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton30, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
            .addContainerGap())
    );

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

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

private void jButton0ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    txtDisplayResult.setText(txtDisplayResult.getText()+"0"); // pega o número 0 e exibe 0 no display;


}                                        

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    txtDisplayResult.setText(txtDisplayResult.getText()+"1"); // pega o número 1 e exibe 1 no display;
}                                        

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    txtDisplayResult.setText(txtDisplayResult.getText()+"2"); // pega o número 2 e exibe 2 no display;
}                                        

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    txtDisplayResult.setText(txtDisplayResult.getText()+"3"); // pega o número 3 e exibe 3 no display;
}                                        

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    txtDisplayResult.setText(txtDisplayResult.getText()+"4"); // pega o número 4 e exibe 4 no display;
}                                        

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    txtDisplayResult.setText(txtDisplayResult.getText()+"5"); // pega o número 5 e exibe 5 no display;
}                                        

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    txtDisplayResult.setText(txtDisplayResult.getText()+"6"); // pega o número 6 e exibe 6 no display;
}                                        

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    txtDisplayResult.setText(txtDisplayResult.getText()+"7"); // pega o número 7 e exibe 7 no display;
}                                        

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    txtDisplayResult.setText(txtDisplayResult.getText()+"8"); // pega o número 8 e exibe 8 no display;
}                                        

private void jButton93ActionPerformed(java.awt.event.ActionEvent evt) {                                          
    txtDisplayResult.setText(txtDisplayResult.getText()+"9"); // pega o número 9 e exibe 9 no display;
}                                         

private void jButton30ActionPerformed(java.awt.event.ActionEvent evt) {                                          
    txtDisplayResult.setText(txtDisplayResult.getText()+"."); // pega o caracterer . e exibe . no display;
    //break;
}                                         

private void jButton38ActionPerformed(java.awt.event.ActionEvent evt) {                                          
    txtDisplayResult.setText("");// Limpa o visor
}                                         

private void jButton36ActionPerformed(java.awt.event.ActionEvent evt) {                                          

operando1 = Double.parseDouble(txtDisplayResult.getText());
txtDisplayResult.setText("");
operador ="adic";
// TODO add your handling code here:
}                                         

private void jButton35ActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    //txtDisplayResult.setText(txtDisplayResult.getText()+"-");
    operando1 = Double.parseDouble(txtDisplayResult.getText());
    txtDisplayResult.setText("");
    operador ="subtr";

}                                         

private void jButton31ActionPerformed(java.awt.event.ActionEvent evt) {                                          


   // TODO add your handling code here:
  operando2 = Double.parseDouble(txtDisplayResult.getText());
  if (operador =="adic"){
  txtDisplayResult.setText(String.valueOf(operando1+operando2));
  }
  if(operador =="subtr"){
  txtDisplayResult.setText(String.valueOf(operando1-operando2));
  }
  if(operador =="multpl"){
  txtDisplayResult.setText(String.valueOf(operando1*operando2));
  }
  if(operador =="div"){
  txtDisplayResult.setText(String.valueOf(operando1/operando2));
  }

  }                                         

  private void jButton34ActionPerformed(java.awt.event.ActionEvent evt) {                                          
  // TODO add your handling code here:
  operando1 = Double.parseDouble(txtDisplayResult.getText());
  txtDisplayResult.setText("");
  operador ="multpl";

  }                                         

  private void jButton33ActionPerformed(java.awt.event.ActionEvent evt) {                                          

  operando1 = Double.parseDouble(txtDisplayResult.getText());
  txtDisplayResult.setText("");
  operador ="div";
  }                                         

  private void jButton37ActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
     operando1=null;
     operando2=null;
     txtDisplayResult.setText("");

}                                         

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<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(Formulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Formulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Formulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Formulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>
 // Ou JFrame frame = new JFrame("Calculadora");
 //Formulario.setTitle("Novo Título");

    //URL url = this.getClass().getResource("imagem.png");
 //Image imagemTitulo = Toolkit.getDefaultToolkit().getImage(url);
 //this.setIconImage(imagemTitulo);

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Formulario().setVisible(true);
        }
    });

}

1 answer

5

As the code displayed is not a Minimum, Complete and Verifiable Example, therefore, can not run, and by the context presented in the question, I suggest you to change your approach around the calculator. In this answer i explain step-by-step how to make a basic calculator, similar to windows.

She gets like this:

inserir a descrição da imagem aqui

The differential is to control what is typed by using specific keys for each function, just as most calculators do. This way, it is easier to avoid this type of problem that you are facing, because you will be restricting what is typed before the user even types. Even in this example of the answer, there is a method only for floating point, to prevent it from being typed more than once:

 this.btnPontoSeparador.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        //pega outros valores digitados pelo usuario
        String strValorAtual = fieldValorAtual.getText();
        //pega o ponto(.)
        String strpontoFlutuante = ((JButton) e.getSource()).getText();
        //checa se o usuario não adicionou um ponto 
        //e se não foi digitado nenhum valor
        if (!strValorAtual.contains(".") && strValorAtual.isEmpty()) {
             //adiciona 0. na exibicao
            strValorAtual = "0" + strpontoFlutuante;
        //checa se o usuario não adicionou um ponto 
        //e se já foi digitado algum valor
        } else if (!strValorAtual.contains(".") && !strValorAtual.isEmpty()) {
           //concatena o valor já digitado com o ponto 
           strValorAtual += strpontoFlutuante;
        }
        //altera o valor do campo que exibe a operacao
        fieldValorAtual.setText(strValorAtual);
    }
});

Note that the condition to add a floating point is that the current value has no other point. If the value is empty, a "0" is added next to the point.

The basic logic to control the addition of the point can start from this code above (if you do not want to follow the model), has to be controlled before the operation is performed.

Another tip is to always try to name the variables that reference what they represent in the code, netbeans is a great tool with the screen builder, but it’s important to have this notation correct, even for maintenance, if you don’t have the IDE to change something in the code.

  • It would be possible to post your code again commenting on what I see just explained as you did in another post without more details; ???

  • @Spencerekroth which code?

  • this.btnPontoSeparador.addActionListener(new ActionListener() {&#xA; @Override&#xA; public void actionPerformed(ActionEvent e) {&#xA; String strValorAtual = fieldValorAtual.getText();&#xA; String strpontoFlutuante = ((JButton) e.getSource()). gettext(); if (!strValorAtual.contains("." ) && strValorAtual.isEmpty()) { strValorAtual = "0" + strpontoFlutuant; } Else if (!strValorAtual.contains("." ) && ! strValorAtual.isEmpty()) { strValorAtual += strpontoFlutuante; } fieldValorAtual.setText(strValorAtual); } });

  • for example, I will have to create n variables to register value1, value2 and Valor3 and so on

  • @Spencerekroth what is the specific doubt? It is more you talk than comment line by line. Maybe reading the other linked answer will make it easier to understand this part better.

  • would be basically how I use the code, need to adapt or just paste in place of my stitch button?

  • Okay, I’ll search to find out what it means to create listeners! Thank you!

  • @Spencerekroth good, that I do not know answer you, because as I commented at the beginning of the answer, was not presented a [mcve] to be tested. But the premise is, initially, to work with only values in strings, and only when doing the operation, transform into integers or floats. I can comment on the lines, but I don’t know how to explain you how to adapt to your code, because I can’t test on it.

  • @Spencerekroth commented on the code. Try to run the calculator, the full code is at this link, maybe by running you can understand better.

  • I’m still in doubt if you really understood my question. with the code I posted so you can’t know what to do? Strange because sometimes I solve equations that saw programs? which data would you need the most @diegofm ?

  • @Spencerekroth as I said in the reply, without a [mcve] Your code is not executable. The tips I passed in the answer solve the problem otherwise, you can implement in the presented way or adapt, but if you have doubts, you need to provide an executable code, otherwise it will be difficult to help you solve within your code.

  • I posted the whole code and still not fit for Diego pray that others see.. pray! your calculator bugged before typing anything Diego (didn’t check it anymore, deleted the account?) @diegofm your example didn’t fit me, nor ran in netbeans, alias the above code runs in netbeans so it’s complete for it.

  • @Spencerekroth if you are talking about the calculator of the other answer, it is probably you who is not able to use, because not only with me but several other people tested, thanked me for the full example and made use for you. Only in your IDE she bugged, which is no surprise to me, as the question code also only runs on your IDE ;)

  • I tried to apply it to my code but it didn’t work out, all right, I’ll try it another way.

  • @Spencerekroth, how’s your code these days? The question is not executable because it does not have the initialization of the components (buttons, panels, etc), you can copy the code of the question and execute the part in a new class and see that it does not execute. If you present the full code I can see his problem.

Show 10 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.