Events
Validate Swing input data
Validate multiple entries
How to validate multiple entries
- When more than one field needs to be validated, it is best to put all the validation logic in a separate method that returns a boolean value to indicate whether or not the data is valid.
Code that validates multiple entries with a series of if statements
public boolean isValidData() { // validate investmentTextField if (!SwingValidator.isPresent(investmentTextField, "Monthly Investment")) return false; if (!SwingValidator.isDouble(investmentTextField, "Monthly Investment")) return false; // validate rateTextField if (!SwingValidator.isPresent(rateTextField, "Interest Rate")) return false; if (!SwingValidator.isDouble(rateTextField, "Interest Rate")) return false; // validate yearsTextField if (!SwingValidator.isPresent(yearsTextField, "Number of Years")) return false; if (!SwingValidator.isInteger(yearsTextField, "Number of Years")) return false; return true; }
Code that validates multiple entries with a compound condition
public boolean isValidData() { return SwingValidator.isPresent(investmentTextField, "Monthly Investment") && SwingValidator.isDouble(investmentTextField, "Monthly Investment") && SwingValidator.isPresent(rateTextField, "Interest Rate") && SwingValidator.isDouble(rateTextField, "Interest Rate") && SwingValidator.isPresent(yearsTextField, "Number of Years") && SwingValidator.isInteger(yearsTextField, "Number of Years"); }
Code that calls the isValidData method from an action event listener
public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == calculateButton) { if (isValidData()) { // code that processes the data } } }