
add two integer variables and display the sum of them using java swing

Hi Friend,
You can use the following code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.regex.*;
class Calculate extends JFrame {
JButton ADD;
JPanel panel;
JLabel label1,label2;
final JTextField text1,text2;
int cal;
Calculate() {
label1 = new JLabel();
label1.setText("Enter First Number:");
text1 = new JTextField(20);
label2 = new JLabel();
label2.setText("Enter Second Number:");
text2 = new JTextField(20);
ADD=new JButton("Add");
panel=new JPanel(new GridLayout(3,2));
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(ADD);
add(panel);
setVisible(true);
pack();
setTitle("Calculate");
ADD.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
String value1=text1.getText();
String value2=text2.getText();
Pattern p = Pattern.compile("[A-Z,a-z,&%$#@!()*^]");
Matcher m1 = p.matcher(value1);
Matcher m2 = p.matcher(value2);
if(value1.length()==0){
JOptionPane.showMessageDialog(null,"Enter first number","Error",JOptionPane.ERROR_MESSAGE);
}
else if (m1.find()){
JOptionPane.showMessageDialog(null,"Enter only number!","Error",JOptionPane.ERROR_MESSAGE);
text1.setText("");
}
else if(value2.length()==0){
JOptionPane.showMessageDialog(null,"Enter second number","Error",JOptionPane.ERROR_MESSAGE);
}
else if (m2.find()){
JOptionPane.showMessageDialog(null,"Enter only number!","Error",JOptionPane.ERROR_MESSAGE);
text2.setText("");
}
else{
int n1=Integer.parseInt(value1);
int n2=Integer.parseInt(value2);
cal=n1+n2;
JOptionPane.showMessageDialog(null,"Addition of two numbers is: "+Integer.toString(cal));
}
}
});
}
public static void main(String arg[]){
new Calculate();
}
}
It will be helpful for you. Thanks
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.