Basically I have created an applet that has three textfields one for each of the RGB values. I then created a try catch block to show a dialogue message if the user inputs a string. However, now I want it to find which textfield it was that had a string in it and set only that textfield to null so then they can type an integer, whilst also keeping the values of the two correct textfields.
So for example:
[255] [150] [cat]
step 2: [255] [150] [] (the string textfield should become null)
Code:
try{
if (e.getSource().equals (bttn))
{
as=T1.getText();
ag=T2.getText();
ab=T3.getText();
as=as.trim();
ag=ag.trim();
ab=ab.trim();
redColor= Integer.parseInt(as);
greenColor= Integer.parseInt(ag);
blueColor= Integer.parseInt(ab);
}
}
catch (NumberFormatException exception){
JOptionPane.showMessageDialog(null,"Integers Only","ERROR!",JOptionPane.WARNING_MESSAGE);
}
You have to split your code into tree parts, one for each field.
But this would result in redundant code. To avoid this, you should put the conversion part into a separate function which is called for each field.
Related
I need to create a program to store all words in an array list. Then check the user input from the textfield to see if it starts with anything other than numbers and punctuation. Otherwise it will need to display an error and prvent the string to be added to the arraylist and display an appropriate error.
https://pastebin.com/8UwDm4nE
Heres the ActionEvent listener that contins the code to check that. Im not really sure how to get it working.
#Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < 1; i++) {
String str = tf.getText(); // MUST BE STORED ON AN ARRAY LIST
ta.append(str + "\n"); // Append the text on new line each
if(str.startsWith(String.valueOf(nums))) { // Check input for a number at the start
error.setText("Error: Word starts a number. Please try again!");
error.setForeground(Color.RED);
ta.append("");
} else if (str.startsWith(String.valueOf(punct))) { // Check if input contains a punctuation at the start
error.setText("Error: Word starts with an illegal character. Please try again!");
error.setForeground(Color.RED);
ta.append("");
}
}
}
I'm going to rephrase your problem a bit as clarification, please correct me if I'm misunderstanding.
You have a text field and a text area. You want a user to type a word into the text field and submit it. If that word starts with a number or punctuation, then indicate an error to the user. Otherwise, add it to the text area (on a new line) and the inner ArrayList.
To solve this problem, there are a couple things you'll need:
An ArrayList<String> that is a class member variable where you can store your words
An event handler that handles the button click.
The event handler should:
Parse the string from the text field (using getText(), as you already are).
Do the error checks you're already doing.
If neither of the error conditions are hit (so add an else clause for this), add the word to the text area (which you're already doing) and add it to the ArrayList.
Hopefully this helps you get a clearer idea of how to approach the problem. If not, please post a code sample of what you tried and what error you're specifically running into.
EDIT:
Here is some pseudocode for your if-else error-handling block of code, assuming you declare a new ArrayList to hold your words as a class member:
// as class member variable
List<String> wordList = new ArrayList<>();
// word handler code
if (str starts with a number) {
// handle error
} else if (str starts with punctuation) {
// handle error
} else {
ta.append(str + "\n");
wordList.add(str);
}
I am trying to retrieve the values from a JTextField on a keypress to do something if the values are integers and to clear the field if the values are not integers. Every time I try to retrieve the value, I am getting the value entered before that(if I enter 12 I get 1 back then if I enter 123 I get 12 back) and when I try to clear the field on an invalid character everything but the invalid character gets cleared?
public void setUpListeners()
{
JTextField jT [] = myV.getTextFields();
jT[0].addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e){
int id = e.getID();
if (id == KeyEvent.KEY_TYPED)
{
char c = e.getKeyChar();
try
{
//check if chars entered are numbers
int temp = Integer.parseInt(String.valueOf(c));
String tempS = jT[0].getText();
System.out.println(tempS);
}
catch(Exception ex)
{
jT[0].setText("");
System.out.println("Not an integer");
}
}
}
});
}
You could do the following:
public static boolean validateNumber(char num){
return (num >= '0' && num <='9');
}
And then use parameter KeyEvent "e":
if(!validateNumber(e.getKeyChar()))
e.consume();
And instead of using
public void keyTyped(KeyEvent e){
use
public void keyReleased(KeyEvent e){
I think you will get what you need, I hope I have helped you ;)
Swing components use Model-View-Controller (MVC) [software] design pattern / architecture. The model holds the data. For a JTextField the data is the text it displays. The default model for JTextField is PlainDocument, however JTextField code actually refers to the Document interface which PlainDocument implements.
Look at the code for method getText() in class JTextComponent (which is the superclass for JTextField) and you will see that it retrieves the text from the Document.
When you type a key in JTextField, the character gets passed to the Document. It would appear that your keyTyped() method is invoked before the character you typed reaches the Document, hence when you call getText() in your keyTyped() method, you're getting all the text apart from the last character you typed.
That's one of the reasons not to use a KeyListener in order to validate the text entered into a JTextField. The correct way is detailed in the question that tenorsax provided a link to in his comment to your question.
Apart from DocumentFilter or JFormattedTextField (or even InputVerifier), you can add an ActionListener to JTextField which will execute when you hit Enter in the JTextField. You will find many on-line examples of how to implement each one of these options, including the link provided in tenorsax comment.
Note: I have asked this question when I was a newbie to programming in java. I have got the solution for the same; back then itself. Editing to make it clear for other readers.
Input Format: Input is in string format. In our case we assume to convert the strings that contains only digits to BigDecimal, rest of them can be ignored.
Eg: We expect 1e4 -> BigDecimal value to be passed as "10000". So, the inputs which
contains alphabets or any other special characters can be be ignored to convert.
Reason for the requirement: We need to search few columns in the DB based on the search text and retrieve rows on matching criteria. Lets say columns name(VarChar column), price(Decimal column), type (VarChar column). So, if the search text can be converted to BigDecimal we will search if text matches any of the columns else if it can't be converted to BigDecimal we will search if the text matches other two columns.
Without analysing the input further I have blindly converted the search text to BigDecimal.
Example: if the name in DB is 1e3 and price is 10000 and if search text is 1e4, then the converted BigDecimal value of 1e4 will be matched to 10000 and will fetch the row.
Initial Code of converting to BigDecimal:
BigDecimal textToBigDecimal = null;
try
{
textToBigDecimal = new BigDecimal(searchText);
}
catch (NumberFormatException ignored)
{
}
if (textToBigDecimal == null)
{
//criteria handling code.
}
else
{
//criteria handling code.
}
Skipped the criteria constructed code. Added try-catch because, the input can be a pure string also. Based on that criteria construction differs.
Modified Code:
BigDecimal textToBigDecimal = null;
try
{
if (!searchText.contains("e") && !searchText.contains("E"))
{
textToBigDecimal = new BigDecimal(searchText);
}
}
catch (NumberFormatException ignored)
{
}
if (textToBigDecimal == null)
{
//criteria handling code.
}
else
{
//criteria handling code.
}
Note: If any further doubts pls comment on the question. I have posted this question expecting to find a default java method that converts only the strings that contains digits only to BigDecimal and throws exception for rest of the strings.
If you want exception to be thrown for strings like '45e57', you can use for example Long.parseLong("43e57") before constructing BigDecimal. It will throw NumberFormatException
my application will have a text box which the user will edit with numbers (hopefully)
I am using Integer.parseInt() to convert the string into a integer, however, there's always the chance the user will not pass in numbers which will throw an exception during parseInt(). I am not sure what the convention is for error handling in GWT. Does this work?
int number = -1;
try {
number = Interger.parseInt(inputFromUser);
} catch (Exception e) {
// error handling like telling user to try again
}
If you want number-only boxes, use IntegerBox, LongBox, or DoubleBox. They already support rendering and parsing of, respectively, integer, long or double values using locale-aware renderers/parsers (based on NumberFormat).
You are on the right track. Just change Exception to NumberFormatException and you should be fine.
I am currently creating this java GUI that will ask the user to input 10 entries, then use the values to execte the next action.
I want only numbers or decimal point to be inputted inside such that it can only be a float value.
If it is not number or decimal point, it should prompt the user to input that specific entry again before the next action is executed.
How should I do it?
Wong,
not sure whether you are using Swing or not...
Ages ago I had the same problem and I solved it with creating a class RestrictedTextField extending JTextField. In the constructor I added a key listener (addKeyListener(new RestrictedKeyAdapter());)
private class RestrictedKeyAdapter extends KeyAdapter {
#Override
public void keyReleased(KeyEvent e) {
if (getText().equals("")) {
oldString = "";
return;
} else {
// if you cannot parse the string as an int, or float,
// then change the text to the text before (means: ignore
// the user input)
try {
if (type.equals("int")) {
int i = Integer.parseInt(getText());
oldString = getText();
} else if (type.equals("float")) {
float f = Float.parseFloat(getText());
oldString = getText();
} else {
// do nothing
}
} catch (NumberFormatException el) {
setText(oldString);
}
// if the text is identical to the initial text of this
// textfield paint it yellow. If the text was changed
// paint it red.
if (initialString.equals(getText())) {
setForeground(Color.YELLOW);
} else {
setForeground(Color.RED);
}
}
}
}
The idea is, that every time the user presses a key in the textfield (and releases it then), the text in the textfield is parsed. If the component should accept only floats for example then the component tries to parse it as an float (Float.parseFloat(..)). If this parsing is successful everything is fine. If the parsing fails (an NumberFormatException is thrown) then the old text is written back into the textfield (literally ignoring the user input).
I think you can add the KeyAdapter directly to the JTextField without creating a dedicated class for that, but with this solution you can remember the initial string and the old string.
you can play around with the code.. you can change the colour of the textfield if the input is valid or not (or like in my code snippet if the text is identical to the initial string).
one additional comment: I set the 'type' of the textfield in a variable with the name 'type', which is simply a String with the values "int", "float", etc.... a better solution would be here for example an enum of course...
I hope this is helpful...
timo
There are various options for what you would like to do. You can check here for one example of doing so. Another example could be to use Formatted TextFields, as shown here.
On the other hand, upon submission, you can try to parse the value to a float or double. If you get any exceptions, then, the value is not a number.
Lastly, you can use Regular Expressions. An expression such as ^\\d+(\\.\\d+)?$ should match any integer or floating point number.