Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
My problem is whene i put the two number in the TextField , after clicking on the "Result" button it won't give me the total of two numbers !
and i m not sure about the Scanner that i add into the event, it s just my opinion about reading numbers in the JFrame .
here is my Code :





package calculator.addition;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;



public class CalculatorAddition {
public static int a ;
public static int b ;//globale var
public static int s ;

public CalculatorAddition(){

JFrame f = new JFrame();
JTextField t1 = new JTextField(" ");
JTextField t2 = new JTextField(" ");
JTextField t3 = new JTextField(" ");
JButton b3 = new JButton("result");

f.setSize(150,150);
t1.addActionListener((ActionEvent arg0) ->
{Scanner in = new Scanner(System.in);//i add Scanner method to read the numbers from user
a = in.nextInt();
t3.setText(Integer.toString(a));});



t2.addActionListener((ActionEvent arg0) -> //event
{Scanner in = new Scanner(System.in);
b = in.nextInt();
});


b3.addActionListener((ActionEvent) ->
{s = a+b ;
t3.setText(Integer.toString(s));
});




JPanel p = new JPanel();
p.add(t1);
p.add(t2);
p.add(t3);
p.add(b3);
f.getContentPane().add(p,BorderLayout.CENTER);
f.show();
}
public static void main(String...arg)
{ CalculatorAddition p = new CalculatorAddition();
}}

What I have tried:

i was change the event to new class but it keep doesn t work !
Posted
Updated 12-Apr-17 16:00pm
Comments
[no name] 12-Apr-17 20:55pm    
You really need to learn java, or any programming language, the correct way instead of just guessing. If you can't get a book, start with https://docs.oracle.com/javase/tutorial/
wseng 15-Apr-17 1:55am    
Please format your code .

1 solution

Scanner sc = new Scanner(System.in);
This line is used for scanner to read an input from the console. How would you expect it to read from the JTextField ?

To retrieve value from JTextField, it should be something like
int a = t1.getText();


If you want to increase the width of the JTextField, use JTextField(5) instead, don't use JTextField(" ").
 
Share this answer
 
v6

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900