Search code examples
javauser-interfacenetbeansnetbeans-8

How do i get the input from TextField?


I'm trying to make a simple calculator GUI using Netbeans.

How do I input integer and String from angka1,angka2, and operator1 so it can be used in private void btnHitungMouseClicked(java.awt.event.MouseEvent evt)

private void angka1ActionPerformed(java.awt.event.ActionEvent evt) {                                       
            nilai1=Integer.parseInt(angka1.getText());
        }
private void angka2ActionPerformed(java.awt.event.ActionEvent evt) {                                       
                nilai2=Integer.parseInt(angka2.getText());
    }
private void operator1ActionPerformed(java.awt.event.ActionEvent evt) {                                          
       operator=operator1.getText();
    }




private void btnHitungMouseClicked(java.awt.event.MouseEvent evt) {                                       
        double jawaban=0;
        if(operator=="+")
            jawaban=nilai1+nilai2;
        else if(operator=="-")
            jawaban=nilai1-nilai2;
        else if(operator=="*")
            jawaban=nilai1*nilai2;
        else if(operator=="/")
            jawaban=nilai1/nilai2;            
        String hasil=Double.toString(jawaban);

        txtHasil.setText(hasil);

This is the GUI I'm trying to make:

The GUI I'm trying to make As you can see it doesn't seem to work.I expect the GUI to give the correct result in the TextField to work when i type a number and also an operator in the TextField above. Please help.


Solution

  • operator=='+' does not compare the string. it checks the object.
    Create a MouseClicked Event by RightClicking on Hitung Button Events>Mouse>MouseClicked

      private void HitungMouseClicked(java.awt.event.MouseEvent evt) {                                    
         nilai1 = Integer.parseInt(angka1.getText());
         nilai2=Integer.parseInt(angka2.getText());
         operator=operator1.getText();
    
         double jawaban=0;
        if(operator.equalsIgnoreCase("+"))
            jawaban=nilai1+nilai2;
        else if(operator.equalsIgnoreCase("-"))
            jawaban=nilai1-nilai2;
        else if(operator.equalsIgnoreCase("*"))
            jawaban=nilai1*nilai2;
        else if(operator.equalsIgnoreCase("/"))
            jawaban=nilai1/nilai2;            
        String hasil=Double.toString(jawaban);
    
        txtHasil.setText(hasil);
    
    }