Search code examples
javanetbeansnulljtextfield

How to make default value for a jTextField if it is empty


how to create a simple interest calculator in Netbeans in which if rate textfield is empty, the rate automatically sets for 8.5 and similary time for 1 year?


Solution

  • There at least two scenarios to be concerned with.

    1. Nothing was entered
    2. A non-number was entered

    You also have two different field types

    1. Interest: Decimal type (e.g. float)
    2. Year: Integer type (e.g. int)

    I've written some helper functions to assist in parsing a "blank" value. These helper functions are the solution, but there's a runnable example provided below.

    // Parses a JTextField for a float
    public static float parseFloat(JTextField f, float defaultVal, float failureVal) {
        if (f == null || f.getText().trim().isEmpty()) {
            return defaultVal;
        } else {
            try {
                return Float.parseFloat(f.getText());
            } catch (NumberFormatException e) {
                return failureVal;
            }
        }
    }
    
    // Parses a JTextField for an integer
    public static int parseInt(JTextField f, int defaultVal, int failureVal) {
            if (f == null || f.getText().trim().isEmpty()) {
                return defaultVal;
            } else {
                try {
                    return Integer.parseInt(f.getText());
                } catch (NumberFormatException e) {
                    return failureVal;
                }
            }
    }
    

    The functions are pretty self-explanatory, but the purpose is to allow both a "default" value of 8.5 for interest as well as an error value incase you want to catch this problem and warn the user.

    To use these functions, you'd simply call them with all three parameters:

    System.out.println(parseFloat(rateField, 8.5f, 8.5f));
    System.out.println(parseFloat(yearField, 1, 1));
    

    The year input processing is identical to the interest input processing except Java uses explicit number types, so it's a copy and paste with float changed to int.

    Here's the full, working example:

    import javax.swing.*;
    import java.awt.*;
    
    public class Main {
        public static void main(String ... args) {
            JLabel rateLabel = new JLabel("Rate:");
            JTextField rateField = new JTextField(10);
    
            JLabel yearLabel = new JLabel("Year:");
            JTextField yearField = new JTextField(10);
    
            // Use modal to wait for user input for proof of concept
            JDialog dialog = new JDialog();
            dialog.setModal(true);
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.setLayout(new FlowLayout());
            dialog.getContentPane().add(rateLabel);
            dialog.getContentPane().add(rateField);
            dialog.getContentPane().add(yearLabel);
            dialog.getContentPane().add(yearField);
            dialog.pack();
    
            dialog.setVisible(true);
    
            float rateValue = parseFloat(rateField, 8.5f, 8.5f);
            int yearValue = parseInt(yearField, 1, 1);
    
            JOptionPane.showMessageDialog(null, rateLabel.getText() + rateValue);
            JOptionPane.showMessageDialog(null, yearLabel.getText() + yearValue);
    
        }
    
        // Parses a JTextField for a float
        public static float parseFloat(JTextField f, float defaultVal, float failureVal) {
            if (f == null || f.getText().trim().isEmpty()) {
                return defaultVal;
            } else {
                try {
                    return Float.parseFloat(f.getText());
                } catch (NumberFormatException e) {
                    return failureVal;
                }
            }
        }
    
        // Parses a JTextField for an integer
        public static int parseInt(JTextField f, int defaultVal, int failureVal) {
                if (f == null || f.getText().trim().isEmpty()) {
                    return defaultVal;
                } else {
                    try {
                        return Integer.parseInt(f.getText());
                    } catch (NumberFormatException e) {
                        return failureVal;
                    }
                }
        }
    }