What's "inside" the TextField - validation

I have the following JavaFX code:
final TextField textField = new TextField();
and anEventHandler<ActionEvent>with checking textField wether it's empty or not. The problem is that textField.getText() == null or textField.getText() == "" both returns false, but i didn't print anything in that field, so it should return true.
final TextField textField = new TextField();
browse.setOnAction(new EventHandler() {
#Override
public void handle(ActionEvent actionEvent) {
FileChooser fileChooser = new FileChooser();
File chFile = fileChooser.showOpenDialog(stage);
if (chFile != null) {
// some code
if (textField.getText() != null && textField.getText() != "") {
// some code
}
}
}
});

The textField.getText() returns a java String. Java String is an Object so you should use equals() method instead of == to compare Strings. == operator is used for comparing primitive types in Java. To understand this better, please look this How do I compare strings in Java? Q/A for string comparison in Java.
As I said you can use textField.getText().equals("") for checking the String emptiness but the common usage for it is:
if (textField.getText() != null && ! textField.getText().trim().isEmpty()) {
// some code
}
where ! is a boolean NOT operator. Also not the trim() method. This is for checking if the user entered whitespaces only then treat them as an empty value. Otherwise checking the whitespaces with equals("") will fail.

if(textfield.getText().trim().length>0)
//do Something
else
//can't be blank

Related

Spring is converting String values to false for #queryparam Boolean

I have this as queryparam in my requestmapping:
#QueryParam("isBenchmark") boolean isBenchmark
Now if am passing any String value also it is defaulting it to false. How can I avoid this and throw error if it is anything other than true/false.
Is there any annotations with which I can throw such validations
It is a known issue.
It is converted to boolean using the new Boolean(isBenchmark) So when isBenchmark is true it converts to true, in all other cases it converts to false.
Unfortunately you have to handle it by your self
public void YourMethod(#QueryParam("isBenchmark") String isBenchmark) {
boolean val
if (isBenchmark != null && isBenchmark.equals("true")){
val = true;
} else if (isBenchmark != null && isBenchmark.equals("false")) {
val = false;
} else {
Throw Exception or return a bad request
}
}

How to reduce the if-else depth?

I have this example code
public static ActionProcessable getActionProcessor(TaskType currentTaskType, UserAction userAction){
String actionKey;
if(userAction != null){
if(currentTaskType != null){
actionKey = buildKey(currentTaskType, userAction);
if(dossierActions.containsKey(actionKey)){
return dossierActions.get(actionKey);
}
}
actionKey = buildKey(anyTaskType(), userAction);
if(dossierActions.containsKey(actionKey)){
return dossierActions.get(actionKey);
}
}
return new NullActionProcessor();
}
In this logic i have a map to store the ActionProcessable by combined-key TaskType and UserAction. This method will return ActionProcessable with input taskType and action. TaskType can be null so in that case we only need to get by userAction.
When i check this code by sonar, it say the third if is "Nested if-else depth is 2 (max allowed is 1)"
But i don't know how to make it better.
Does anyone suggest me something?
You can move "if containsKey" part out of condition to remove code duplication:
public static ActionProcessable getActionProcessor(TaskType currentTaskType, UserAction userAction){
if (userAction != null) {
String actionKey = currentTaskType != null
? buildKey(currentTaskType, userAction)
: buildKey(anyTaskType(), userAction);
if (dossierActions.containsKey(actionKey)){
return dossierActions.get(actionKey);
}
}
return new NullActionProcessor();
}
Now, intent of the code looks more clear (at least, for me).
You can also make the first condition short-circuit and\or use ternary if for containsKey, it will remove even more ifs, but can make code more complex for some people.
public static ActionProcessable getActionProcessor(TaskType currentTaskType, UserAction userAction){
if (userAction == null) {
return new NullActionProcessor();
}
String actionKey = currentTaskType != null
? buildKey(currentTaskType, userAction)
: buildKey(anyTaskType(), userAction);
return dossierActions.containsKey(actionKey)
? dossierActions.get(actionKey);
: new NullActionProcessor();
}
Choose the one you like, they are technically similar.
Since you haven't specified specific programming language, one more thing to say: your code is a good example of use case of null-coalsecing operator. Sadly, AFAIK, there is none in Java. In C#, the code could look like this:
public static ActionProcessable GetActionProcessor(TaskType currentTaskType, UserAction userAction) {
if (userAction == null) {
return new NullActionProcessor();
}
var actionKey = BuildKey(currentTaskType ?? anyTaskType(), userAction);
return dossierActions[actionKey] ?? new NullActionProcessor();
}

Backspace while entering filename in JFileChooser makes directory go one level back

I am pretty new to Java Swing development and is encountering the following issue and not certain how to resolve it.
While providing a file name to save a file using JFileChooser, entering a backspace(in the filename field), makes a directory go up 1 level. This problem is encountered only on Windows and not on Linux.
Can somebody shed some light on why this may happening and an approach to fix this issue.
Thanks.
I had this problem too.
My solution - is to override the processKeyBinding method , and in the specific case stop the method , see below:
#Override
protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
int condition, boolean pressed) {
if (KeyEvent.VK_BACK_SPACE == e.getKeyChar()){
if (jTextField!= null && jTextField.hasFocus())
return false;
}
return super.processKeyBinding (ks,e,condition,pressed);
}
the jTextField is the filename field that , was calculated in the contractor of my FileChooser class
the method to calculate is -
private Component getTextFieldInJFileChooser(Component [] c )
{
if (c == null)
return null;
for(Component k: c)
{
if( k instanceof JTextField) {
return k;
}
else if(k instanceof JPanel) {
JPanel jp=(JPanel)k;
Component jTextField = getTextFieldInJFileChooser(jp.getComponents());
if (jTextField != null)
return jTextField;
}
}
return null;
}
Success & Regards!

GWT - setText and setValue not working for TextBox on initial load

I have a couple of text-boxes on a page where the user can enter some numeric values; however, try as I might, I can't fill those text-boxes with default values - specifically I would like 0.0 displayed in both upon page load.
Here is how I create them and what I have tried -
GroupSection engineering_group = new GroupSection();
KSTextBox engrDesignTextBox = new KSTextBox();
engrDesignTextBox.setWidth("2.875em");
//engrDesignTextBox.setWatermarkText("0.0"); ==> this works, but not what I need
//engrDesignTextBox.setText("0.0"); ==> this doesn't work
engrDesignTextBox.setValue("0.0"); // doesn't work either
KSTextBox engrScienceTextBox = new KSTextBox();
engrScienceTextBox.setWidth("2.875em");
//engrScienceTextBox.setWatermarkText("0.0"); ==> this works, but not what I need
//engrScienceTextBox.setText("0.0"); ==> this doesn't work
engrScienceTextBox.setValue("0.0"); // doesn't work either
I'm thinking that I need to attach an "onload" event listener and then try the setText in there? That seems overkill for something that should be rather simple.
Incidentally, I have attached onBlurHandlers for both these text boxes and they work as expected (see code below)
The following code will simply insert0.0 if the user clicks or tabs out of the text-box while it is EMPTY.
engrDesignTextBox.addBlurHandler(new BlurHandler() {
#Override
public void onBlur(BlurEvent blurEvent) {
if(((KSTextBox)blurEvent.getSource()).getText().length() < 1) {
((KSTextBox)blurEvent.getSource()).setText("0.0");
}
}
});
engrScienceTextBox.addBlurHandler(new BlurHandler() {
#Override
public void onBlur(BlurEvent blurEvent) {
if(((KSTextBox)blurEvent.getSource()).getText().length() < 1) {
((KSTextBox)blurEvent.getSource()).setText("0.0");
}
}
});
EDIT : As requested here is how I have defined the setText and setValue methods in KSTextBox
public class KSTextBox extends TextBox implements HasWatermark {
.
.
.
#Override
public void setText(String text) {
String oldValue = super.getText();
if(hasWatermark) {
if(text == null || (text != null && text.isEmpty())){
super.setText(watermarkText);
addStyleName("watermark-text");
watermarkShowing = true;
}
else{
super.setText(text);
removeStyleName("watermark-text");
watermarkShowing = false;
}
}
else{
super.setText(text);
}
ValueChangeEvent.fireIfNotEqual(this, oldValue, text);
}
#Override
public void setValue(String value) {
if(hasWatermark) {
if(value == null || (value != null && value.isEmpty())){
super.setValue(watermarkText);
addStyleName("watermark-text");
watermarkShowing = true;
}
else{
super.setValue(value);
removeStyleName("watermark-text");
watermarkShowing = false;
}
}
else{
super.setValue(value);
}
}
So, getting back to the original question, how I do I initially set the values for these textboxes to 0.0?
That should have worked.Its very suprising. Is there a possibility that some other code is resetting the value after you did a setText or a setValue? Try debugging it in hosted mode.Put a breakpoint in setText and see when and how many times it is getting invoked

How to add a numeric textbox in WP7 which can take a float value?

I am developing WP7 application. I am new to the WP7. I am also new to the silverlight. I have a textbox in my application. In this textbox user enters the amount. I want to give the facility in my application so that user can enter the float amount ( for e.g. 1000.50 or 499.9999). The user should be able to enter either two digit or four digit after the '.' .My code for the textbox is as follows.
<TextBox InputScope="Number" Height="68" HorizontalAlignment="Left" Margin="-12,0,0,141" Name="AmountTextBox" Text="" VerticalAlignment="Bottom" Width="187" LostFocus="AmountTextBox_LostFocus" BorderBrush="Gray" MaxLength="10"/>
I have done the following validations for the above textbox.
public void AmountTextBox_LostFocus(object sender, RoutedEventArgs e)
{
foreach (char c in AmountTextBox.Text)
{
if (!char.IsDigit(c))
{
MessageBox.Show("Only numeric values are allowed");
AmountTextBox.Focus();
return;
}
}
}
How to resolve the above issue. Can you please provide me any code or link through which I can resolve the above issue. If I am doing anything wrong then please guide me.
Download the free book Programming Windows Phone 7 by Charles Petzold. On page 380, in section TextBox Binding Updates, under Chapter 12: Data Bindings, he has an excellent example on validating floating point input.
For limiting the user input to 2 or 4 decimal places you'll have to add some logic to TextBox's TextChanged callback. For instance, you could convert the float to a string, search for the decimal and then figure out the length of the string to the right of the decimal.
On the other hand, if you just want to round the user input to 2 or 4 digits, take a look at the Fixed-Point ("F") Format Specifier section on this page.
I do the validation this way as shown in the code below.
No need for checking char by char and user culture is respected!
namespace Your_App_Namespace
{
public static class Globals
{
public static double safeval = 0; // variable to save former value!
public static bool isPositiveNumeric(string strval, System.Globalization.NumberStyles NumberStyle)
// checking if string strval contains positive number in USER CULTURE NUMBER FORMAT!
{
double result;
boolean test;
if (strval.Contains("-")) test = false;
else test = Double.TryParse(strval, NumberStyle, System.Globalization.CultureInfo.CurrentCulture, out result);
// if (test == false) MessageBox.Show("Not positive number!");
return test;
}
public static string numstr2string(string strval, string nofdec)
// conversion from numeric string into string in USER CULTURE NUMBER FORMAT!
// call example numstr2string("12.3456", "0.00") returns "12.34"
{
string retstr = "";
if (Globals.isPositiveNumeric(strval, System.Globalization.NumberStyles.Number)) retstr = double.Parse(strval).ToString(nofdec);
else retstr = Globals.safeval.ToString(nofdec);
return retstr;
}
public static string number2string(double numval, string nofdec)
// conversion from numeric value into string in USER CULTURE NUMBER FORMAT!
// call example number2string(12.3456, "0.00") returns "12.34"
{
string retstr = "";
if (Globals.isPositiveNumeric(numval.ToString(), System.Globalization.NumberStyles.Number)) retstr = numval.ToString(nofdec);
else retstr = Globals.safeval.ToString(nofdec);
return retstr;
}
}
// Other Your_App_Namespace content
}
// This the way how to use those functions in any of your app pages
// function to call when TextBox GotFocus
private void textbox_clear(object sender, System.Windows.RoutedEventArgs e)
{
TextBox txtbox = e.OriginalSource as TextBox;
// save original value
Globals.safeval = double.Parse(txtbox.Text);
txtbox.Text = "";
}
// function to call when TextBox LostFocus
private void textbox_change(object sender, System.Windows.RoutedEventArgs e)
{
TextBox txtbox = e.OriginalSource as TextBox;
// text from textbox into sting with checking and string format
txtbox.Text = Globals.numstr2string(txtbox.Text, "0.00");
}
You can always use this regex [-+]?[0-9].?[0-9] to determine if its a floating number.
public void AmountTextBox_LostFocus(object sender, RoutedEventArgs e)
{
Regex myRange = new Regex(#"[-+]?[0-9]*\.?[0-9]");
if (myRange.IsMatch(textBox1.Text))
// Match do whatever
else
// No match do whatever
}
The following code is working fine for me. I have tested it in my application. In the following code by adding some validations we can treat our general textbox as a numeric textbox which can accept the float values.
public void AmountTextBox_LostFocus(object sender, RoutedEventArgs e)
{
foreach (char c in AmountTextBox.Text)
{
if (!char.IsDigit(c) && !(c == '.'))
{
if (c == '-')
{
MessageBox.Show("Only positive values are allowed");
AmountTextBox.Focus();
return;
}
MessageBox.Show("Only numeric values are allowed");
AmountTextBox.Focus();
return;
}
}
string [] AmountArr = AmountTextBox.Text.Split('.');
if (AmountArr.Count() > 2)
{
MessageBox.Show("Only one decimal point are allowed");
AmountTextBox.Focus();
return;
}
if (AmountArr.Count() > 1)
{
int Digits = AmountArr[1].Count();
if (Digits > 2)
{
MessageBox.Show("Only two digits are allowed after decimal point");
AmountTextBox.Focus();
return;
}
}
}

Resources