How to validate Regular Expression in real time on jtextbox? - java

I'm trying to validate/filter my jtextbox wwith this Regex:
^(([A-za-z]+[\s]{1}[A-za-z]+)|([A-Za-z]+))$
I want to filter two names with one space.
Tried using keytyped and keyreleased, but it just does not work (won't let me write anything on the textbox) and e.consume() does not work.
boolean StrCheck(String Exp,String str) {
return Pattern.matches(Exp,str);
}
#Override
public void keyTyped(KeyEvent e) {
if (e.getSource() == jTextField) {
String regexp = "^(([A-za-z]+[\s]{1}[A-za-z]+)|([A-Za-z]+))$";
if (jTextField.getText().length() == 25) {
e.consume();
} if (StrCheck(regexp,jTextField.getText())){
}else {
e.consume();
}
I've been searching, but the only possible answer I got, was to create a Documentlistene BUT can't find any example or how actually do it and make it work.

Neither KeylListener, neither DocumentListener will work. In most of this kind of cases you would need to use a DocumentFilter. Before you do though, take a look on how to use formatted textfields. It might be enough for you. If it does not, this answer is what you are looking for.

Related

How do I check if the left angle bracket key is pressed?

In Java, I have checked the list of Virtual Key Codes, and there is not a VK for '<'. I have tried "VK_LESS" with my program (which sounds like it could be '<'), but that did not work either.
I am wondering if I have to check to see if the Shift key is pressed down, and then check to see if the Comma key is also pressed down, but I am not sure how to do that in a KeyHandler class, using a switch statement for the keyPressed method.
The KeyHandler keyPressed method will receive a KeyEvent. You can call isShiftDown() on that KeyEvent to see if the shift key is currently pressed.
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_COMMA && e.isShiftDown()) {
// do your thing!
}
}
You could also try doing:
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == '<') {
...
}
}
Note the use of keyTyped rather than keyPressed. keyTyped triggers only when a key press outputs a character, rather than on every key press. This method would be more likely to work for other types of keyboard. But I haven't tried it, so I don't know if it would work at all.
I believe you'd want to use VK_LESS and VK_GREATER for "<" and ">", respectively.
You can use KeyEvents.getKeyChar() method
public void keyPressed(KeyEvent e) {
if (evt.getKeyChar().equals("<")) {
/*your code*/
}
}

Should I avoid using "!" in if statement in Java?

Our team's Java Coding Guideline says:
Avoid using "!" in if statement as much as possible.
I have asked other colleagues, but no one gave me clear ideas why, because the guideline was created a long time ago and the author might have left our company.
Do you have any idea?
With the information provided, this calls for some speculation. One possible reason is that the intent was not for an if-statement by itself but for an if-else statement. In that case, I can see where you might say that you should reverse the cases so that you don't have the extra operation of the negation. Instead of
if (! boolVar) {
// Something
} else {
// Something else
}
you might prefer
if (boolVar) {
// Something else
} else {
// Something
}
Whether this is worth it or not is probably more a matter of taste and standardization than anything else.
The rule is likely an adaptation from Robert Martin's Clean Code, page 302:
Negatives are just a bit harder to understand than positives. So, when possible, conditionals should be expressed as positives. For example:
if(buffer.shouldCompact())
is preferable to
if(!buffer.shouldNotCompact())
As an example, suppose you're creating a validator that requires two things to be false for the entity to be valid:
The entity must not have been created within the last 12 hours, and
The entity's bank account total sum must not exceed $50,000.
Naturally the idea would be to write two methods for this:
boolean isCreatedWithinLastTwelveHours(BankAccount account)
boolean hasMoreThanTotalSumCap(BankAccount account)
...at which point, you then invoke these as:
boolean newAccount = isCreatedWithinTheLastTwelveHours(account);
boolean highEndAccount = hasMoreThanTotalSumCap(account);
if(!newAccount && !highEndAccount) { // ... other logic
// The more astute would use DeMorgan's law in an effort to make this more readable
if(!(newAccount || highEndAccount)) { // other logic
Well...wouldn't it be nicer if you just said what they weren't instead?
boolean isNotCreatedWithinLastTwelveHours(BankAccount account)
boolean hasLessThanTotalSumCap(BankAccount account)
That'd make the expression a bit more concise:
if(notNewAccount && notHighEndAccount) { // .. carry on!
Of course "!" can be used when you like. There is no "unless" in java and you have no other choices in some conditions.
Looks like yet-another-useless-rule. Generally speaking, there are no absolute terms in this scenario, true that if you are in a if-else clause then possibly it is better to write
if(myCondition) {
doThis()
} else {
doSomethingElse()
}
Instead of
if(!myCondition) {
doSomethingElse()
} else {
doThis()
}
However, that said, in some scenarios is actually quite ok to use the negation operator, particularly if no else clause is provided, example
if (!tokenDoesCompute()) {
throw InvalidTockenException("Whatever")
}
And actually in that scenario, using "!" makes quite a bit of sense for me.
Finally, if no one can really explain WHY the rule is there, maybe it is time to remove it, the only good reason I could find for it would be to provide consistency regarding the code style.
Okay, I answer my own question.
As other say, maybe this is written for the readability.
In The Art of Readable Code (p. 72) says:
Prefer dealing with the positive case first instead of the negative-e.g., if(debug) instead of if(!debug)
I found below post as well:
Readable Code - Remove Checking null
bool func(String name)
{
if ( (name != null) && (name.equals("true") ) {
//...
} else {
//...
}
}
bool func(String name)
{
if ( "true".equals(name) ) {
//...
} else {
//...
}
}
Ofcourse you can use the negation operator ! whenever you like.
However, if you have a situation where you have to write some actions in both if and else block then the following is more readable :
if(status){
//do something
}
else{
//do something else
}
than
if(!status){
//do something
}
else{
//do something else
}
But if you have situation where you only need to perform certain actions based on just one condition, i.e. if you have only an if block & no else block, then it is reasonably fine to use ! in if
I haven't seen anyone else suggest this, which is probably because they hate it as much as I do, but I'm showing it for completeness.
// Using not operator (preferred)
if (! someTest) { ... }
// Using compact not operator (kind of hides it)
if (!someTest) { ... }
// Comparing to false (ok, explicitly states what you want)
if (someTest == false) { ... }
// Comparing to true (a bit obscure)
if (someTest != true) { ... }
They all do the same, but please keep using !, just make sure you add a space after it, so it's easier to see.

Comparing strings in a Textbox

I would like to compare the string in a textbox if it contains "per/kg" and use that to disable a button. I have tried several methods but it did not work please kindly help out.
if (productDescTextBox.getText().equals("per/kg"))
{
buttonDot.setEnabled(true);
}
else buttonDot.setEnabled(false);
and this
if ("per/kg".equals(productDescTextBox.getText().toString()))
{
buttonDot.setEnabled(true);
}
else buttonDot.setEnabled(false);
use String.contains(CharSequence)
if (productDescTextBox.getText().contains("per/kg"))
Use string.contains.
if (productDescTextBox.getText().contains("per/kg")){
//Whatever you want
}
Note the method is case sensitive

How to disabled a combobox according to the selection in another combobox?

I have this block of code that is giving me results for a combo box, I would like it to ignore the combo box and disable it when the value "SDO/OD" is selected in the one above under the combo box for ROLE aka fcbRole. The following enables the box from the first part, but the second part does not fire off. And it gives me a warning: "This field is required"...Have you seen something like this before?
I have been tinkering with:
fcbRole.addSelectionChangedListener(new SelectionChangedListener<ModelData>()
{
#Override
public void selectionChanged(SelectionChangedEvent<ModelData> se)
{
if ("SDO/OD".equals(this.toString()))
{
fcbOfficeRegion.enable();
} else
{
fcbOfficeRegion.disable();
}
}
});
Don't use == and != to compare Strings, instead use:
if("SDO/OD".equals(this.getStringName()) // or make sure you override toString()
// enable
else
// disable
For String value equality, use equals() method and not operators. Operators does reference equality check.
So, change your code to:
if ("SDO/OD".equals(this.toString()))
{
fcbOfficeRegion.enable();
} else
{
fcbOfficeRegion.disable();
}

Java Swing - KeyListener

How can I know when the key typed change my text? Or if the key is a char?
The interface KeyListener contain three methods:
void keyTyped(KeyEvent)
void keyPressed(KeyEvent)
void keyReleased(KeyEvent)
So, if you get the char in the KeyEvent object like:
if ("a".equals(KeyEvent.getKeyChar()))
System.out.println("It's a letter")
i guess you want to know wether typing a specific key actually prints a char or is some "invisible" control character or something:
in this case you can check the typed key in the KeyEvent which gets passed into the implemented methods of the KeyListener:
this quick example should work, although i didnt test it. It constructs a new String on the char returned by the KeyEvent, than invokes the length() method to chekc if the char created a readable character in the String. kinda hacky but i hope you get the gist of it
public void keyReleased(KeyEvent ke){
if (new String(ke.getKeyChar()).length() == 0){
// do something important...
}
}
alternativley you can use ke.getKeyCode() and check vs the static fields in KeyEvent (VK_F12,VK_ENTER...)
check here:
http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html
You need a document listener. See the oracle docs for more information: How to Write a Document Listener

Categories