After getting an action from the KeyListener, using the event.getKeyCode() and later on the KeyEvent.getKeyText(keyCode), how would i check if the outcome of .getKeyText(keyCode) is a single character like 'a' and not a whole word like "Space" ?
How about this:
KeyEvent.getKeyText(keyCode).length == 1
You can use getKeyChar() of the KeyEvent, and then'll you be certain that what you get back is a single char.
E.g. something like this:
public void keyTyped(KeyEvent e) {
keyChar = e.getKeyChar();
...
}
Try this:-
if ((event.keyCode > 64 && event.keyCode < 91) || (event.keyCode > 96 && event.keyCode < 123) || event.keyCode == 8)
{
if(KeyEvent.getKeyText(keyCode).length == 1)
{
//Only one character is pressed.
}
}
This solution worked for everything except the delete key and numpad keys...
event.getKeyChar() != '\uFFFF'
Because any Java outputs that character for non-renderable keys, it works quite consistently.
To fix the delete key problem...
event.getKeyChar() != '\uFFFF' && event.getKeyCode() != KeyEvent.VK_DELETE
It will return true if the key is printable, and false if not.
Related
I am confused on how to use || and && in the same if statement.
What I am trying to do is have it print something if the string starts with an "D" or an "O", and if one is true check if the string has a character length of two.
Example: if the string is "DE" it will print something. However, if it is "SE" it will not print anything.
else if( (answer.startsWith("D") || answer.startsWith("O"))
&& (answer.length() == 2) ) {
//print something
}
Java is applying a "short circuit" to your logic. It does the first part (starts with "D" or "O") and if that's true it proceeds to the second part (length is 2). However if the first part evaluates to false then it never even bothers to execute the second part.
So your "SE" string will never go into the "print something" bit because it doesn't meet your first criteria of starting with D or O. And based on your description of what the logic should be, that is correct.
If you actually mean that if it starts with "D" or "O" OR is 2 characters long then your logic statement should have been:
else if( answer.startsWith("D") || answer.startsWith("O")
|| (answer.length() == 2 ) {
//print something
}
Edit: Oops, just pasted the original code in the first time...!
I would check first the length and after the two conditions e.g.
else if (answer.lenght()==2) {
if (answer.startsWith("D") || answer.startsWith("O"){
//print something that lenght is 2 and starts with D or O
}
}
}
In that case you have to check length first because && will true if left side and right side both true
else if( (answer.length() == 2)&&(answer.startsWith("D") || answer.startsWith("O"))
{
//your logic
}
This what I have done so far, even though I check all of them I get AlertDialog message.
private void validateCheckBoxes() {
if (toilets.isSelected() || wifi.isSelected() || trolleys.isSelected() || lifts.isSelected()
&& ticketMachine.isSelected() || stepFree.isSelected()) {
saveRecordsToDatabase();
} else {
AlertDialog.Builder facilitiesError = new AlertDialog.Builder(AddStation.this);
facilitiesError.setTitle("Station Facilities are not selected");
facilitiesError.setMessage("Please select at least one facility ");
facilitiesError.setNegativeButton("OK", null);
facilitiesError.create().show();
}
}
By "selected" do you mean "checked"?
if (toilets.isChecked() || wifi.isChecked() || trolleys.isChecked() || lifts.isChecked()
|| ticketMachine.isChecked() || stepFree.isChecked()) {
saveRecordsToDatabase();
}
modify your code:
if (toilets.isSelected() || wifi.isSelected() || trolleys.isSelected() || lifts.isSelected()
|| ticketMachine.isSelected() || stepFree.isSelected()) {
saveRecordsToDatabase();
}
Explanation: you are using all && operators in if statement, which means you get alert message only if all the check boxes are checked.
If you use all || (or) operator, it means you get alert message if at least one checkbox is checked.
I want to check whether there is something in my JButton. What would i insert into the equalsIgnoreCase() area?
if (jButton1.getText().equalsIgnoreCase("") &&
jButton2.getText().equalsIgnoreCase("") &&
jButton3.getText().equalsIgnoreCase("") &&
jButton4.getText().equalsIgnoreCase("") &&
jButton5.getText().equalsIgnoreCase("") &&
jButton6.getText().equalsIgnoreCase("") &&
jButton7.getText().equalsIgnoreCase("") &&
jButton8.getText().equalsIgnoreCase("") &&
jButton9.getText().equalsIgnoreCase(""))
To check that there is a text, you can do:
!jButton1.getText().isEmpty()
or, if you want to exclude a text that only contains spaces:
!jButton1.getText().trim().isEmpty()
You can use
jButton1.getText().isEmpty()
(use ! to negate if you want to know it's not empty...)
or you can check the length of the value
jButton1.getText().length > 0
you can use
bool somethingIn = !jButton1.getText().isEmpty();
Nothing, just what you did. But you should put exclamation symbols before conditions to negate them:
if (!jButton1.getText().equals("") &&
!jButton2.getText().equals("") &&
!jButton3.getText().equals("") &&
!jButton4.getText().equals("") &&
!jButton5.getText().equals("") &&
!jButton6.getText().equals("") &&
!jButton7.getText().equals("") &&
!jButton8.getText().equals("") &&
!jButton9.getText().equals(""))
In this case body of if will be executed if all your JButtons have some text. And ignoreCase is not necessary. Emptiness has no lower or upper case ))
i'd like to create JTextField with input characters limited to someting like
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYWZZ0123456789+&##/%?=~_-|!:,.;"
so i tried overriding
public class CustomJTextField extends JTextField {
String goodchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYWZZ0123456789+&##/%?=~_-|!:,.;";
//... my class body ...//
#Override
public void processKeyEvent(KeyEvent ev) {
if(c != '\b' && goodchars.indexOf(c) == -1 ) {
ev.consume();
return;
}
else
super.processKeyEvent(ev);}}
but it isn't what i want because user cannot ctrl-c ctrl-v ctrl-x any more... so i addeded
&& ev.getKeyCode() != 17 && ev.getKeyCode() !=67 && ev.getKeyCode() != 86 && ev.getKeyCode() !=0 &&
to the if condition, but now the user can paste inappropriate input, ie '(' or '<', without any problem...
what can i do?
maybe better would be use DocumentFilter with Pattern,
Try a JFormattedTextField and use
MaskFormatter mf = new MaskFormatter();
mf.setValidCharacters("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYWZZ0123456789+&##/%?=~_-|!:,.;");
JFormattedTextField textField = new JFormattedTextField(mf);
Edit: Sorry, that was the wrong code, here's the working one
I have a class I wrote in Java and one of the methods is getCommand()
The purpose of this method is to read in a string and see what the user typed in matches any of the acceptable commands.
This is how I wrote it initially:
public char getCommand(){
System.out.println("Input command: ");
command = input.nextLine();
while(command.length() != 1){
System.out.println("Please re-enter input as one character: ");
command = input.nextLine();
}
while( command.substring(0) != "e" ||
command.substring(0) != "c" ||
command.substring(0) != "s" ||
command.substring(0) != "r" ||
command.substring(0) != "l" ||
command.substring(0) != "u" ||
command.substring(0) != "d" ||
command.substring(0) != "k" ||
command.substring(0) != "f" ||
command.substring(0) != "t" ||
command.substring(0) != "p" ||
command.substring(0) != "m" ||
command.substring(0) != "q"){
System.out.println("Please enter a valid character: ");
command = input.nextLine();
}
fCommand = command.charAt(0);
return fCommand;
}
Now, I see the problem with this is that since I use the OR operator, it won't escape that loop because the character I type in will always not equal one of them. I tried changing it to the AND operator, but same problem. What would be the best way to only accept those specific characters?
Much appreciated.
Your logic is incorrect. You should be using logical ANDs and not ORs. Also I believe you want to use charAt() instead of substring() then compare characters.
i.e.,
while( command.charAt(0) != 'e' &&
command.charAt(0) != 'c' &&
command.charAt(0) != 's' &&
...)
Otherwise if you want to test for actual single-character string inputs, just check using string equality.
while( !command.equals("e") &&
!command.equals("c") &&
!command.equals("s") &&
...)
You should define your commands as constants (individually). Hard coding values like this makes it harder to update your code in the future.
If the program is simply proof of concept or homework I would use:
private static final String COMMANDS = "ecsrludkftpmq";
while(!COMMANDS.contains(command.getChar(0)) {
System.out.println("Please enter a valid character: ");
command = input.nextLine();
}
Otherwise, if this is production code I would consider making a simple Command(char) class and providing individual command constants as part of a collection (possibly a Map against the Character key), which can be tested to see if contains a matching command.