I am to build a simple swing UI application to get input from user from separate JTextField and then finally click on a Button to perform addition to display on a JTextField below the JButton.
The input field(JTextField) is to receive integer values.
package com.APPOne_G5;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AppOne_G5 {
private JPanel calculatorFrame;
private JTextField inputField1;
private JTextField inputField2;
private JButton calculateButton;
private JTextField outputField;
private JLabel inputFieldLabel1;
private JLabel inputFieldLabel2;
private JLabel outputFieldLabel;
private int number1, number2;
private int calc = number1 + number2;
public AppOne_G5() {
inputField1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
number1 = Integer.parseInt(inputField1.getText());
}
});
inputField2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
number2 = Integer.parseInt(inputField2.getText());
}
});
calculateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
calc = number1 + number2;
outputField.setText(String.valueOf(number1+number2));
}
});
outputField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
outputField.setEditable(false);
outputField.setText(String.valueOf(calc));
}
});
}
public static void main(String[] args) {
JFrame app = new JFrame("Group 5 AppOne");
app.setDefaultCloseOperation(app.EXIT_ON_CLOSE);
app.setContentPane(new AppOne_G5().calculatorFrame);
app.setLocationRelativeTo(null);
app.setVisible(true);
app.pack();
}
}
I get Zero after i enter values to be added.
Further to my comment, you only need one action listener that activates when you click the button. Here is a complete working example of how it might work:
To debug why you are not getting the expected outupt you can use
System.out.println("...");. For example if you were to use the following then you could see if the issue is beacause calc is wrong, or if numebr1 or number2 were already zero:Once you know where the issue is you can go further back in the code and work out why the value is zero.