As a part of an assignment I'm trying to retrieve a value from a JTextField. What I'm trying to get is the interest rate for an account. It should be greater than zero & user should be asked that until he/she gives something greater than zero. Also if the input is something other than a number, like a string of text, there should be an error as well and it should ask the user again.
I've done some of the part but I'm having issues completing the task.
The following is the method that calls the GUI:
//getting the interest rate
protected void getInterest() {
if( this instanceof flexibleAccount ) {
}
else {
GetInterest getInterest = new GetInterest();
getInterest.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
getInterest.setSize( 350, 100 );
getInterest.setVisible(true);
}//end else
}//end getInterest
It goes to here:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.util.InputMismatchException;
public class GetInterest extends JFrame {
private JTextField textField;
private double interestRate;
public GetInterest() {
super("Banking Application");
setLayout( new FlowLayout() );
textField = new JTextField("Enter interest rate",10);
add(textField);
TextFieldHandler handler = new TextFieldHandler();
textField.addActionListener( handler );
}//end GetInterest
private class TextFieldHandler implements ActionListener {
@Override
public void actionPerformed( ActionEvent event ) {
try {
String string;
string = textField.getText();
//string = String.format("%s", event.getActionCommand());
interestRate = Double.parseDouble(string);
if( interestRate <= 0 )
JOptionPane.showMessageDialog( null, "Interest rate should be greater than zero" );
else if( interestRate > 0 ) {
JOptionPane.showMessageDialog( null, interestRate );
}
//else
//throw new InputMismatchException;
}
catch(InputMismatchException exception) {
System.out.println(accountTest.getStackTrace(exception));
}
}//end actionPerformed
}//end TextFieldHandler
}//end GetInterest
As you can see I'm getting the value and user is asked again if he/she enters something smaller than or equal to zero.
But the following are missing:
- returning it to the getInterest method,
- window disappearing after completion,
- displaying an error if the user enters a text.
How can I achieve those.