In: Computer Science
In java, Create a GUI which works as an accumulator
1. There is a textfield A which allows user to enter a number
2. There is also another textfield B with value start with 0.
3. When a user is done with entering the number in textfield A and press enter, calculate the sum of the number in textfield B and the number user just entered in textfield A, and display the updated number in textfield B
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SumGUI {
static JFrame frame = new JFrame("JFrame Example");
static JTextField B= new JTextField("0");
static JTextField A= new JTextField();
public static void main(String s[]) {
JPanel panel = new JPanel();
panel.setLayout(null);
JLabel label1 = new JLabel("A");
label1.setBounds(200, 50, 100, 30);
A.setBounds(320, 50, 100, 30);
JLabel label2 = new JLabel("B");
label2.setBounds(200, 100, 100, 30);
// password field
B.setBounds(320, 100, 100, 30);
A.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
// if typed code is Enter on textfield than reversing the string
if(e.getKeyCode()==KeyEvent.VK_ENTER){
Integer sum = Integer.parseInt(A.getText())+Integer.parseInt(B.getText());
B.setText(sum.toString());
}
}
});
panel.add(label1);
panel.add(label2);
panel.add(A);
panel.add(B);
frame.add(panel);
frame.setSize(600, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.
I AM HERE TO HELP YOU IF YOU LIKE MY ANSWER PLEASE RATE AND HELP ME IT IS VERY IMP FOR ME