Reputation: 11
i'm making a simple gui where the user has to enter 2 random strings of numbers and when the "done" button is pushed it will output those 2 strings. But how do I do this with try-catch method so that the user only can use numbers otherwise it will catch exceptions?
This is my code:
import java.awt.event.*;
import javax.swing.*;
public class Panel extends JPanel
{
private JTextField field1;
private JTextField field2;
private JButton button1;
private JLabel label1;
private JLabel label2;
public Panel()
{
label1 = new JLabel("first string: ");
label2 = new JLabel("second string: ");
field1 = new JTextField(38);
field2 = new JTextField(3);
button1 = new JButton("done");
ButtonP buttonP = new ButtonP();
button1.addActionListener(buttonP);
this.add(label1);
this.add(field1);
this.add(label2);
this.add(field2);
this.add(button1);
}
private class ButtonP implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("String 1 " + field1.getText() + " and string 2 " + field2.getText());
}
}
}
Thanks in advance
Upvotes: 1
Views: 2085
Reputation: 6818
You have two options here. The first and the recommended one, is to use a JFormattedTextField in order to eliminate the chance of getting NumberFormatException
. Plus, it is more user-friendly.
The second option is to catch the NumberFormatException
, and when you catch it, to add a kind of an "error" message to the user (not so much user-friendly) and tell him to give correct input. Then, he miss-clicks a letter, and we are back to the error message.
Upvotes: 0
Reputation: 11
//You save yor recieved string from textfield and try to convert it to an integer
//If is not convertable, it throws an exception and prints in console the error
String string1 = field1.getText();
int myInteger = 0;
try {
myInteger = Integer.parseInt(string1);
} catch(Exception e){
System.out.println("Invalid input. Not an integer");
e.printStackTrace();
}
Hope that helps. Greetings.
Upvotes: 1