What's new

Help JAVA GUI Calculator

Fersonlante

Addict
Established
Joined
Sep 1, 2022
Posts
74
Reaction
22
Points
64
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package GUIProject;
import javax.swing.JOptionPane;
/**
*
* @author joopa30
*/
public class SimpleCalculator extends javax.swing.JFrame {

/**
* Creates new form SimpleCalculator
*/
public SimpleCalculator() {
initComponents();
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
a = new javax.swing.JTextField();
b = new javax.swing.JTextField();
c = new javax.swing.JTextField();
jPanel2 = new javax.swing.JPanel();
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();

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

jPanel1.setBackground(new java.awt.Color(204, 204, 255));

jLabel1.setFont(new java.awt.Font("Sitka Subheading", 0, 12)); // NOI18N
jLabel1.setText("First integer");

jLabel2.setFont(new java.awt.Font("Sitka Subheading", 0, 12)); // NOI18N
jLabel2.setText("Second integer");

jLabel3.setFont(new java.awt.Font("Sitka Subheading", 0, 12)); // NOI18N
jLabel3.setText("Result");

a.setBackground(new java.awt.Color(204, 255, 255));

b.setBackground(new java.awt.Color(204, 255, 255));

c.setEditable(false);
c.setBackground(new java.awt.Color(204, 255, 255));
c.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cActionPerformed(evt);
}
});

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(38, 38, 38)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addGap(65, 65, 65)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(a)
.addComponent(b)
.addComponent(c, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(a, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(b, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(c, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(20, 20, 20))
);

jPanel2.setBackground(new java.awt.Color(255, 204, 204));

jButton1.setBackground(new java.awt.Color(204, 255, 255));
jButton1.setText("+");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});

jButton2.setBackground(new java.awt.Color(204, 255, 255));
jButton2.setText("-");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});

jButton3.setBackground(new java.awt.Color(204, 255, 255));
jButton3.setText("*");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});

jButton4.setBackground(new java.awt.Color(204, 255, 255));
jButton4.setText("/");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});

jButton5.setBackground(new java.awt.Color(204, 255, 255));
jButton5.setText("Clear");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});

jButton6.setBackground(new java.awt.Color(204, 255, 255));
jButton6.setText("Exit");
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});

javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(89, 89, 89)
.addComponent(jButton5)
.addGap(77, 77, 77)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(68, 68, 68)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(36, 36, 36)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(80, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(22, Short.MAX_VALUE))
);

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(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);

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

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
int num1 = Integer.parseInt(a.getText());
int num2 = Integer.parseInt(b.getText());
int sum = num1 + num2;
c.setText(Integer.toString(sum));
} catch (NumberFormatException e) {
c.setText("");
JOptionPane.showMessageDialog(null, "Invalid input");
} // TODO add your handling code here:
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
int num1 = Integer.parseInt(a.getText());
int num2 = Integer.parseInt(b.getText());
int diff = num1 - num2;
c.setText(Integer.toString(diff));
} catch (NumberFormatException e) {
c.setText("");
JOptionPane.showMessageDialog(null, "Invalid input");
} // TODO add your handling code here:
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try {
int num1 = Integer.parseInt(a.getText());
int num2 = Integer.parseInt(b.getText());
int product = num1 * num2;
c.setText(Integer.toString(product));
} catch (NumberFormatException e) {
c.setText("");
JOptionPane.showMessageDialog(null, "Invalid input");
} // TODO add your handling code here:
}

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
try {
float num1 = Float.parseFloat(a.getText());
float num2 = Float.parseFloat(b.getText());

if (num2 != 0) {
float result = num1 / num2;
c.setText(Float.toString(result));
} else {
c.setText("");
JOptionPane.showMessageDialog(null, "Cannot divide by zero");
}
} catch (NumberFormatException e) {
c.setText("");
JOptionPane.showMessageDialog(null, "Invalid input");
}
// TODO add your handling code here:
}

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
a.setText("");
b.setText("");
c.setText(""); // TODO add your handling code here:
}

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0); // TODO add your handling code here:
}

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

/**
* @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 You do not have permission to view the full content of this post. Log in or register now.
*/
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(SimpleCalculator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SimpleCalculator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SimpleCalculator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SimpleCalculator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

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

// Variables declaration - do not modify
private javax.swing.JTextField a;
private javax.swing.JTextField b;
private javax.swing.JTextField c;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
// End of variables declaration
}

using this code when I tried to run in this
First Integer: 2.5
Second Integer: 2.5
Result: 1.0

our prof told me to use
int in First Integer
int in Second Integer
float on Result and the result should be 1
and typecast after
 
Based on the code you provided, the calculation functionality of the calculator only accepts integer inputs for the first and second integers. If you enter decimal values, such as 2.5, it will be parsed as an integer and the decimal part will be ignored.

To modify the code to accept decimal values and perform the calculation correctly, you need to make the following changes:

1. Change the data type of the variables num1 and num2 in the calculation methods (jButton1ActionPerformed, jButton2ActionPerformed, jButton3ActionPerformed, jButton4ActionPerformed) from int to float.

2. Modify the parsing logic in the calculation methods to parse the input values as float instead of int.

3. In the division calculation method (jButton4ActionPerformed), remove the check for division by zero since it's already handled by the NumberFormatException catch block.

4. Typecast the result of the calculation to int before setting it in the c text field.

Here's the modified code with the changes mentioned above:

Java:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        float num1 = Float.parseFloat(a.getText());
        float num2 = Float.parseFloat(b.getText());
        int sum = (int) (num1 + num2);
        c.setText(Integer.toString(sum));
    } catch (NumberFormatException e) {
        c.setText(""); 
        JOptionPane.showMessageDialog(null, "Invalid input");
    }
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        float num1 = Float.parseFloat(a.getText());
        float num2 = Float.parseFloat(b.getText());
        int diff = (int) (num1 - num2);
        c.setText(Integer.toString(diff));
    } catch (NumberFormatException e) {
        c.setText(""); 
        JOptionPane.showMessageDialog(null, "Invalid input");
    }
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        float num1 = Float.parseFloat(a.getText());
        float num2 = Float.parseFloat(b.getText());
        int product = (int) (num1 * num2);
        c.setText(Integer.toString(product));
    } catch (NumberFormatException e) {
        c.setText(""); 
        JOptionPane.showMessageDialog(null, "Invalid input");
    }
}

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        float num1 = Float.parseFloat(a.getText());
        float num2 = Float.parseFloat(b.getText());
        float result = num1 / num2;
        c.setText(Integer.toString((int) result));
    } catch (NumberFormatException e) {
        c.setText(""); 
        JOptionPane.showMessageDialog(null, "Invalid input");
    }
}

With these changes, the calculator will accept decimal values for the first and second integers, perform the calculation correctly, and display the result as an integer.
 
Based on the code you provided, the calculation functionality of the calculator only accepts integer inputs for the first and second integers. If you enter decimal values, such as 2.5, it will be parsed as an integer and the decimal part will be ignored.

To modify the code to accept decimal values and perform the calculation correctly, you need to make the following changes:

1. Change the data type of the variables num1 and num2 in the calculation methods (jButton1ActionPerformed, jButton2ActionPerformed, jButton3ActionPerformed, jButton4ActionPerformed) from int to float.

2. Modify the parsing logic in the calculation methods to parse the input values as float instead of int.

3. In the division calculation method (jButton4ActionPerformed), remove the check for division by zero since it's already handled by the NumberFormatException catch block.

4. Typecast the result of the calculation to int before setting it in the c text field.

Here's the modified code with the changes mentioned above:

Java:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    try {
        float num1 = Float.parseFloat(a.getText());
        float num2 = Float.parseFloat(b.getText());
        int sum = (int) (num1 + num2);
        c.setText(Integer.toString(sum));
    } catch (NumberFormatException e) {
        c.setText("");
        JOptionPane.showMessageDialog(null, "Invalid input");
    }
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    try {
        float num1 = Float.parseFloat(a.getText());
        float num2 = Float.parseFloat(b.getText());
        int diff = (int) (num1 - num2);
        c.setText(Integer.toString(diff));
    } catch (NumberFormatException e) {
        c.setText("");
        JOptionPane.showMessageDialog(null, "Invalid input");
    }
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    try {
        float num1 = Float.parseFloat(a.getText());
        float num2 = Float.parseFloat(b.getText());
        int product = (int) (num1 * num2);
        c.setText(Integer.toString(product));
    } catch (NumberFormatException e) {
        c.setText("");
        JOptionPane.showMessageDialog(null, "Invalid input");
    }
}

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    try {
        float num1 = Float.parseFloat(a.getText());
        float num2 = Float.parseFloat(b.getText());
        float result = num1 / num2;
        c.setText(Integer.toString((int) result));
    } catch (NumberFormatException e) {
        c.setText("");
        JOptionPane.showMessageDialog(null, "Invalid input");
    }
}

With these changes, the calculator will accept decimal values for the first and second integers, perform the calculation correctly, and display the result as an integer.
he said that in Sum, Subtraction and Multiplication to use only int and in division to use int in first and second and float on result in First Inter and Second Integer it indicates in code First Integer Second Integer
 

Similar threads

Back
Top