Java Swing simple program

I’m a new Java programmer, and I’ve been trying to setup a simple Swing program that allows a user to input two integers into JTextFields and when an “add” JButton is clicked the two numbers are added together and the sum is output in a JLabel.

This I can handle, however, where I’m running into difficulty is being able to setup the two JTextFields to consider invalid numbers as zero. For instance, if the character(s) “x” or “xxx” were entered this would cause the value of that JTextField to be 0 for the purposes of the addition. So far I have used try/catch and if/else statements without any success. I have also scoured the Internet for hours over the past two days looking for some solutions for this problem with no results.

Any help would be greatly appreciated! The code I have so far is listed below…

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


public class Adder extends JPanel implements ActionListener {

   JButton addBut = new JButton("Add");
   JTextField field1 = new JTextField("Number 1"),
   field2 = new JTextField("Number 2");
   JLabel numSum = new JLabel("=");

       Adder() {
             this.setPreferredSize(new Dimension(299, 43));
             addBut.addActionListener(this);
             setLayout(new FlowLayout());
             add(field1);
             add(field2);
             add(numSum);
             add(addBut);            
       }

        public void actionPerformed(ActionEvent ae) {
           if(ae.getSource().equals(addBut)){

             try {
                double one = Double.parseDouble(field1.getText());
                double two = Double.parseDouble(field2.getText());
                numSum.setText("" + (one + two));
             }           

                catch(Exception ex) {
             }
        } 

                else {
                    field1.setText(" ");
                    field2.setText(" ");
                    numSum.setText("");
             }
        }

                public static void main(String[] args){
                   JFrame jf=new JFrame();
                   jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   Adder x = new Adder();
                   jf.add(x);
                   jf.pack();
                   jf.setVisible(true);
              }
        }

Answer

Try

double one = 0.0;
double two = 0.0;
 try {
   one = Double.parseDouble(field1.getText());
 }
 catch(Exception ex) {
    field1.setText("0");
 }

 try {
    two = Double.parseDouble(field2.getText());
 }
 catch(Exception ex) {
   field2.setText("0");
 }

numSum.setText("" + (one + two));

Leave a Reply

Your email address will not be published. Required fields are marked *