How to get the result of addition from jTextField1 and jTextField2 by pressing the jButton1 button and display the result in jTextField3 ?

PS do not judge strictly

 private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: vesSportsmena = Double.parseDouble(jTextField1.getText()); //читаем с текстового поля текст, преобразуем в Double } private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: vesSportsmena = Double.parseDouble(jTextField2.getText()); //читаем с текстового поля текст, преобразуем в Double } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: result = vesSportsmena + vremyaProbejki; } private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: String str = Double.toString(result); jTextField3.setText(str); //вывожу обратно результат в текстовое поле } 
  • one
    You need an object - an event handler that implements the ActionListener interface; this object implements the public void actionPerformed (ActionEvent e) {} method, then you need the Button b button itself = new Button ("Click me"); You must add a listener to this button. b.addActionListener (object that implements ActionListener); Tutorial - ( docs.oracle.com/javase/tutorial/uiswing/events/… ) - Ilya Shashilov
  • @ Ilya Shashilov can correctly reformulate my question - Joks
  • it seems your question is formulated by you already, let's better understand further. You now have 4 different ActionPerformed, especially with your prefixes, this will not work. One ActionPerformed method is enough in which all the logic for handling a button press event can be produced. Say these are your 4 different ActionPerformed, is it your class method? And the second button and the text box somewhere there? - Ilya Shashilov

1 answer 1

To do this, you need to add a listener to your click button, where f1 , f2 are jTextField text fields with numbers, and f3 is jTextField where you want to write the answer:

 click.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Integer s = Integer.parseInt(f1.getText()) + Integer.parseInt(f2.getText()); f3.setText(s.toString()); } }); 

enter image description hereenter image description here


Because in f1 and f2 text is of the String type, then adding the numbers f1.getText() + f2.getText() is indispensable (will give out "1123"), so a conversion to the type Int via Integer.ParseInt() is needed to accomplish the addition, and then to the String type.