Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Swing simple program
    primarykey
    data
    text
    <p>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. </p> <p>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. </p> <p>Any help would be greatly appreciated! The code I have so far is listed below... </p> <pre><code>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); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload