这是我的计划的样子,我试图找出如何验证我的计划的每月付款和年度利率字段。如果用户单击“输入”并且未按月付款,利率或两者输入任何内容,我希望程序提示用户这些是必填字段。
这是输出数据并处理数据的代码的一部分。我试图创建一个idValidData类来检查有效数据,但我不知道如何处理它。
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
DefaultListModel futureValueListModel = new DefaultListModel();
if (source == exitButton)
{
System.exit(0);
}
else if (source == calculateButton)
{
try
{
double payment = Double.parseDouble(paymentTextField.getText());
double rate = Double.parseDouble(rateTextField.getText());
int years = (yearsComboBox.getSelectedIndex()) + 1;
NumberFormat currency = NumberFormat.getCurrencyInstance();
for(int i = 1; i <= years; i++)
{
double futureValue = FinancialCalculations.calculateFutureValue(payment, rate, i);
futureValueListModel.addElement("Year " + i + ": " + currency.format(futureValue));
}
futureValueList.setModel(futureValueListModel);
}
catch(Exception ee)
{
System.out.println("This program ended because you didn't enter any data."); //when the user doesn't input data and clicks enter, the program will throw this exception
}
}
}
//END OF ACTION PERFORMED METHOD
public boolean isValidData() //VALIDATES THE DATA
{
SwingValidator sv = new SwingValidator();
if (sv != null)
{
return sv.isPresent(paymentTextField, "Monthly Payment")
&& sv.isPresent(rateTextField, "Yearly Interest Rate");
}
else{
return sv.isPresent(rateTextField, "Yearly Interest Rate");
}
}
我还有一个swing验证器类,它会在检查数据输入和数据类型时返回布尔值。我的代码是:
import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.math.BigDecimal;
public class SwingValidator
{
public static boolean isPresent(JTextComponent c, String title)
{
if (c.getText().length() == 0)
{
showMessage(c, title + " is a required field.\n"+ "Please re-enter.");
c.requestFocusInWindow();
return false;
}
return true;
}
public static boolean isInteger(JTextComponent c, String title)
{
try
{
int i = Integer.parseInt(c.getText());
return true;
}
catch (NumberFormatException e)
{
showMessage(c, title + " must be an integer.\n"+ "Please re-enter.");
c.requestFocusInWindow();
return false;
}
}
public static boolean isDouble(JTextComponent c, String title)
{
try
{
double d = Double.parseDouble(c.getText());
return true;
}
catch (NumberFormatException e)
{
showMessage(c, title + " must be a valid number number.\n"+ "Please re-enter.");
c.requestFocusInWindow();
return false;
}
}
private static void showMessage(JTextComponent c, String message)
{
JOptionPane.showMessageDialog(c, message, "Invalid Entry",JOptionPane.ERROR_MESSAGE);
}
}