How to ensure that a JTextField input meets requirements? - java

So I'm making a module that has three JTextField windows corresponding for 24 bit RGB color values "R", "G" and "B" with buttons for decrement/increment. The module is supposed to take these values and display the color. I did that and it works, but I need to ensure some details about the inputs and I don't know how to. These details are:
if you enter a value outside of 0 and 255 it will be treated as 0
if you click a decrement button when the value is 0 it won't drop it to -1
if you click an increment button when the value is 255 it won't rise to 256. I have no idea how to do it. I tried to google it but
I can't find what I need. I'd appreciate some guidance
EDIT:
I tried to add some if statements to the ActionPerformed method but all it does is returns a whole bunch of errors when I run the module and try the value out of range
EDIT2: for example, I had this but it doesn't work :
#Override
public void actionPerformed(ActionEvent e) {
String r,g,b;
if (e.getSource() == tf1) {
r = tf1.getText();
this.r =Integer.parseInt(r);
if (this.r < 0 && this.r > 255)
this.r =0;
color(); }
I have nothing for my buttons because I have completely no idea how to

This sounds like you might need some data validation from your input sources. We can't see your code, but one way to validate would be have your getters/setters generated for your variables. (Depending on the editor you have, these can be generated rather quickly). Within the values setter - you should be able to do some data validation.
If you post some code, you might get more meaningful feedback.
More on getters and setters in Java: https://www.codejava.net/coding/java-getter-and-setter-tutorial-from-basics-to-best-practices
EDIT:
Now that you've posted code. Change the && to || and that should take care of your issue.
It is still better to data validate this with a getter/setter.

Related

Restrict input in pair of EditText by applying InputFilters on-the-fly

INTRODUCTION:
I am having some trouble enforcing validation to a pair of EditText values in an Android project. The language is Java. android:inputType="number" is set. Both views are empty, by default.
For example, the validation rule is that editTextA and editTextB cannot both be zero. Ideally, the validation should be performed when the user finishes input in either view.
UPDATED QUESTION:
Here's another example. Values of editTextA and editTextB should sum up to 5 max.
Using TextWatcher seems to work okay but it's far from perfect. I think the best way would be to somehow be able to restrict user input on one control based on the current value of the other. Let's say that onCreate contains the following code:
editTextA.setFilters(new InputFilter[]{ new InputFilterMinMax("0", "5")});
editTextB.setFilters(new InputFilter[]{ new InputFilterMinMax("0", "5")});
where InputFilterMinMax is a class that implements InputFilter as per Is there a way to define a min and max value for EditText in Android?
Now let's assume value of editTextA becomes 3. The max filter value of editTextB should now be 2 instead of 5.
The question is can this be applied on-the-fly?
PART OF ORIGINAL QUESTION:
Problem 1: I tried to set a EditorActionListener but there are just too may ways a control can lose focus and I can't get the validation code to work on all cases. I've tried:
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT || actionId = EditorInfo.IME_ACTION_PREVIOUS) {
// get values of A and B
return (valueA+valueB>0);
}
return false;
but doesn't seem to work when the user clicks directly on another control, for example.
Problem 2: The above approach doesn't seem to work in a consistent way especially when I am trying to set an error, too. Where the setError() should be called in the action listener?
Overall, the above approach seems clumsy. Is there any other way to perform such validation?

Java KeyEvent confusion

I have a program which is a mock inventory system with quite a few JTextField's and some regular expressions which some of those fields must comply with. Also, some fields cannot be null(obviously) or an empty String. In order to assist the user to input data, I've added some ImageIcon's to show if the input data is valid or invalid. (a green check or red x) and I setVisibility() as the user types via KeyEvents.
With that said, here is the confusion. I have a block which I'm pretty sure doesn't have a bug in it, but I've found that there's some odd things happening:
I'm only calling my updateIcons() method in response to keyTyped() - my overrides for the others are empty. Now, when a key is typed, the text is printed on the screen before the key is released, so you would think that an input field that simply requires at least one character to NEVER fail the validity check because if keyTyped() is the only entry point to my updateIcons() method, there should always be at least one character by the time the key is released and thus registered as a "key typed". However, it seems to be firing an event before the key even gets registered to the System. Something which makes this even more odd is if I call my updateIcons() method twice in a row from the overridden keyTyped() method, the program STILL fails the check for empty string. BUT if I call it for keyPressed(), keyReleased(), and keyTyped() all for the same event, presto; valid data. Could this possibly be caused by the instability/bugginess of AWT?
Here is the updateIcons() method in case it is something I overlooked, but since I'm getting such odd results I don't think its a bug on my end.
//called from keyTyped
//formInputIcons is a 2D array[8][2] where the first dimension represents
//the form input field, and the second dimension is the ImageIcons for that field
//public final Pattern upcRegex = Pattern.compile("^\\d{12}$");
//public final Pattern anyNumRegex = Pattern.compile("^\\d+$");
public void updateIcons(KeyEvent e){
if(e.getSource() == formAddInputs[0]){
formInputIcons[0][0].setVisible( ! (upcRegex.matcher(
((JTextField)e.getSource()).getText()).matches()));
formInputIcons[0][1].setVisible(upcRegex.matcher(
((JTextField)e.getSource()).getText()).matches());
}else if(e.getSource() == formAddInputs[1]){
formInputIcons[1][0].setVisible(((JTextField)e.getSource()).getText().equals(""));
formInputIcons[1][1].setVisible( ! ((JTextField)e.getSource()).getText().equals(""));
}else if(e.getSource() == formAddInputs[3]){
formInputIcons[3][0].setVisible(((JTextField)e.getSource()).getText().equals(""));
formInputIcons[3][1].setVisible( ! ((JTextField)e.getSource()).getText().equals(""));
}else if(e.getSource() == formAddInputs[4]){
formInputIcons[4][0].setVisible(((JTextField)e.getSource()).getText().equals(""));
formInputIcons[4][1].setVisible( ! ((JTextField)e.getSource()).getText().equals(""));
}else if(e.getSource() == formAddInputs[6]){
formInputIcons[6][0].setVisible( ! (anyNumRegex.matcher(
((JTextField)e.getSource()).getText()).matches()));
formInputIcons[6][1].setVisible(anyNumRegex.matcher(
((JTextField)e.getSource()).getText()).matches());
}else if(e.getSource() == formAddInputs[7]){
formInputIcons[7][0].setVisible( ! (anyNumRegex.matcher(
((JTextField)e.getSource()).getText()).matches()));
formInputIcons[7][1].setVisible(anyNumRegex.matcher(
((JTextField)e.getSource()).getText()).matches());
}
}
UPDATE: I'm an idiot - it works fine if I only call updateIcons() once from keyReleased() and leave keyPressed() and keyTyped() empty. I like to learn things though; could someone explain why keyTyped() is buggy in this usage but keyReleased() works fine or post a link please?
You need to be calling your update method from keyReleased(). I've made a simple JTextField which outputs the key and its getText() each time a key is pressed, and watch what happens:
keyPressed:c
text:
keyTyped:c
text:
keyReleased:c
text:c
keyPressed:a
text:c
keyTyped:a
text:c
keyReleased:a
text:ca
keyPressed:t
text:ca
keyTyped:t
text:ca
keyReleased:t
text:cat
You can see that the actual text of the JTextField is not updated by the keyTyped() or keyPressed() events.

Getting the sum from gwt table element

I have a table written in GWT from a List list. What i want it is to obtain the sum of a certain group of elements.
The problem with this, it is that the value I want to do the sum with its calculated, and thus not obtainable unless you calculate it before generating the List.
I was wondering if it was somehow possible to achieve this through DOM manipulation. And if so, how?.
I will show you an example:
DataA DataB DataC DataD
---------------------------------
aaaaa bbbbb ccccc 12
aaaa1 bbbb1 cccc1 15
aaa11 bbb11 ccc11 17
I want to get the sum of "DataD" column, but i dont know how can i do it.
Thank you in advance for your time,
Kind regards,
Elaborate: DataD column value it is calculated and the value comes from another system and its placed into the table through a third party program; thus i cannot get its value and use it into a sum to get the value i want.
You should be able to add some event handler to the table's widget so that whenever data is added/changed in the widget, you adjust the total. Please give more information about what widgets you are using to represent the table.
EDIT:
now that we know you are using an HTMLLayoutContainer, I assume DataD is being poopulated at a place beyond your controll in code. What you can do is add event handlers to handle the add remove etc events. For example, you could do something like below:
//Your container
HtmlLayoutContainer c = new HtmlLayoutContainer(templates.getTemplate());
c.addAddHandler(new AddEvent.AddHandler() {
#Override
public void onAdd(AddEvent event) {
//Do proper exception handling, check if it is the right widget for dataD, do the needed calculations etc
sum += Double.parseDouble(((HTML)event.getWidget()).getHTML());
}
});
c.addRemoveHandler(new RemoveEvent.RemoveHandler() {
#Override
public void onRemove(RemoveEvent event) {
//handle all conditions like in onAdd in AddHandler above
sum -= Double.parseDouble(((HTML)event.getWidget()).getHTML());
}
});
You can look into the API to see what exactl events match your needs best (http://dev.sencha.com/deploy/gxt-3.0.0/javadoc/gxt/com/sencha/gxt/widget/core/client/container/HtmlLayoutContainer.html)

Checking JTextField Characters

I have a program I've written for my kids to practice basic arithmetic. There is a JTextField on a JFrame where the student keys in the answer to a given math problem (like 8+8, they key in 16, Enter). This field accepts only integer values as entries by way of a DocumentFilter.
That part works just fine. What I want to do with this is to avoid having the user have to hit the enter key. Ideally, when the user keys in the first number (1), a check is done to see if 1 == 16. If not, nothing happens. When they subsequently type the 6, the text field displays the number 16. I want to run a check to verify if 16 == 16, and then handle the entry as if the user had also hit the Enter key.
txtAnswer.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
respondToAnswer(isTimed);
} else {
/* Check if the correct answer has been entered */
System.out.println(txtAnswer.getText());
//int userAnswer = Integer.parseInt(txtAnswer.getText());
//if (userAnswer == correctAnswer {
// respondToAnswer(isTimed);
//}
}
};
});
This code isn't quite working. It's as if it is one character behind. What I mean by that is when the user hits the '1' key (in my 8+8=16 example), the console output is an empty string. When they hit the '6' key, the output is '1'. If they then hit another integer key, the output is '16'. It's always one digit behind. Because of this, I cannot capture the entire contents of the text field to see if it matches the correct answer.
Anyone see what I am missing?
Thanks!
Use a DocumentListener for that instead of a KeyListener. In all three events, you will have access to the actual text content.
To listen for the Enter on JTextField, us an ActionListener
Side note: you should almost never need a KeyListener. On JTextComponent, always rely on a DocumentListener. For all the others, use appropriate Swing Key bindings. KeyListener is really a low level API.
You should use DocumentListener for this purpose. keyPressed is probably fired before the text in the field is updated.
See How to Write a Document Listener for details and examples.

User input validation for JOptionPane.showInputDialog

I'm just learning JAVA and having a bit of trouble with this particular part of my code. I searched several sites and have tried many different methods but can't seem to figure out how to implement one that works for the different possibilities.
int playerChoice = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number for corresponding selection:\n"
+ " (1) - ROCK\n (2) - PAPER\n (3) - SCISSORS\n")) - 1;
I imagine I need to have some type of validation even for when the user has no input as well as an input that is not 1, 2 or 3. Anyone have suggestions on how I can accomplish this?
I tried a while loop, an if statement to check for null before converting the input to an integer, as well as a few different types of if else if methods.
Thanks in advance!
You need to do something like this to handle bad input:
boolean inputAccepted = false;
while(!inputAccepted) {
try {
int playerChoice = Integer.parseInt(JOption....
// do some other validation checks
if (playerChoice < 1 || playerChoice > 3) {
// tell user still a bad number
} else {
// hooray - a good value
inputAccepted = true;
}
} catch(NumberFormatException e) {
// input is bad. Good idea to popup
// a dialog here (or some other communication)
// saying what you expect the
// user to enter.
}
... do stuff with good input value
}
Read the section from the Swing tutorial on How to Make Dialogs, which actually shows you how to use JOptionPane easily so you don't need to validate the input.
There are different approaches your could use. You could use a combo box to display the choices or maybe multiple buttons to select a choice.
The tutorial also shows you how to "Stopping Automatic Dialog Closing" so you can validate the users input.

Categories

Resources