Question

I am writing an tip calculator app in java applet with GUI, my question is how I make sure the error message will pop up if users enter letter instead of number

it is my first time asking question, please be easy on me! Thanks!!!

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

// Typing in the text field and hitting return adds text to text area.
// Clicking on button erases the text area.
public class TextApplet extends Controller implements ActionListener 
{
    private static final int ROWS = 1; // rows in TextArea
    private static final int COLS = 10; // cols in text field & area

    private String amount;
    private float number;
    private JTextField inField, output;         // Input field

    private JButton clear, calc;     
         // button to clear output


    public void begin() 
    {

        Container contentPane = getContentPane();
        JPanel topPanel = new JPanel();       // prepare text field & label
        JLabel inLabel = new JLabel("Bill Cost: ");
        inField = new JTextField(COLS);

        inField.addActionListener(this);
        JLabel topTitle = new JLabel("Tip Calculator", JLabel.CENTER);
        JPanel combinePanel = new JPanel();

        combinePanel.add ( inLabel );
        combinePanel.add ( inField );
        JPanel combinePanel1 = new JPanel();
        combinePanel1.add ( topTitle );

        topPanel.add ( combinePanel1 );
        topPanel.add ( combinePanel );


        topPanel.setLayout ( new GridLayout ( 3,1) );
        contentPane.add(topPanel,BorderLayout.NORTH);

        JPanel centerPanel = new JPanel();     // prepare text area & label
        JLabel outLabel = new JLabel("Bill + Tip:");
        output = new JTextField(COLS);
        output.setEditable(false);        // Prevent user from wrting in output
        centerPanel.add(outLabel);
        centerPanel.add(output);
        contentPane.add(centerPanel,BorderLayout.CENTER);

        JPanel bottomPanel = new JPanel(); 

        // create button
        clear = new JButton("  Clear  ");
        calc = new JButton("Calculate");
        calc.addActionListener(this);
        clear.addActionListener(this);
        bottomPanel.add(calc);
        bottomPanel.add(clear);

        contentPane.add(bottomPanel,BorderLayout.SOUTH);
        validate();
    }

    // add text to area if user hits return, else erase text area
    public void actionPerformed(ActionEvent evt) 
    {
        if (evt.getSource() == calc )
        { 
            amount = inField.getText();
            number = ( Float.parseFloat( amount ) );
            number = (15*number/100);

            output.setText ( Float.toString ( number ) + '$' );
        }

        else if (evt.getSource() == clear )
        {
            output.setText("$");
            inField.setText("");
        }
     }
 }
Was it helpful?

Solution 4

Hello Friend I will give a suggestion

please add validation when call actionPerformed method

 public void actionPerformed(ActionEvent evt) 
{
    if (evt.getSource() == calc )
    { 
       if(validate()){
        amount = inField.getText();
        number = ( Float.parseFloat( amount ) );
        number = (15*number/100);

        output.setText ( Float.toString ( number ) + '$' );

        }
     else{
   // show message for inter valid number or any other
       }
     }

    else if (evt.getSource() == clear )
    {
        output.setText("$");
        inField.setText("");
    }
 }
  boolean validate(){  

   try{
    amount = inField.getText();
        number = ( Float.parseFloat( amount ) );
      return true;

  }
   catch(Exception e){
   return false;

 }




 }

OTHER TIPS

There are any number of ways you might achieve this, you could use

Take a look at javax.swing.InputVerifier. That can be easily attached to a JTextField

JTextField inputField = new JTextField();
inputField.setInputVerifier(new NumericInputVerifier());

private class NumericInputVerifier extends InputVerifier
{
    @Override
    public boolean verify(JComponent input)
    {
        if (((JTextField) input).getText().matches("[0-9]+"))
        {
            return true;
        }
        else
        {
            JOptionPane.showMessageDialog(input, "Only numbers are allowed", "Warning", JOptionPane.WARNING_MESSAGE);
            return false;
        }
    }
}

A complete example can be found here.

Edit Added an example of how to use InputVerifier to limit to numeric input. You'll want to double check the regex, but the basic idea is there...

Use a JFormattedTextField or a DocumentFilter. Then the user won't even be able to enter a non-numeric digit. See:

  1. How to Use Formatted Text Fields
  2. Implementing a Document Filter

For the document filter you will need to check each chraacter as it is entered to make sure it is a digit.

It is always better to do simple edits like that as the user types, rather than wait until you click on a button to do processing.

If you try to call Float.parseFloat on a String that cannot be converted to a float, it will throw a NumberFormatException. You need to catch this exception.

try {        
number = ( Float.parseFloat( amount ) );
number = (15*number/100);

output.setText ( Float.toString ( number ) + '$' );
} catch(NumberFormatException e) {
//code to show error message here
}

Well considering, you'd have to turn the string into an integer to do the math, you could do this:

try {
 int number = Ineger.parseInt(inField.getText());
} catch (NumberFormatException e) {
//SHOW WARNING
}
if (Label1.getText().matches("[0-9]+"))
// does Label1 containts numbers.
{
    // do math
}
else
{
    // warning
    Lavbel1.setText("");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top