I am working on a game that relies on the player's keyboard input.
The current implementation registers whether a key is currently pressed or not.
However, I would like to implement a system in which the player has to do a full key press in order to increment the game state. For example, they'd have to press and release 'A' in order to move to the next position. Then press and release the button to move on again, and so forth. Holding the button down should not result in moving forward.
Here is a very simplified version of what I've got right now:
int velocityX = 0;
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A) {ActiveA = true;}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A) {ActiveA = false;}
}
public void tick() {
x += velocityX;
if (ActiveA){velocityX = 5; }
else if (!ActiveA){velocityX = 0; }
}
The game class calls tick() at about 60 times a second, so X constantly increments while the key is pressed but not while the key is released.
By adding another variable that is set TRUE only when the player releases the key, we can set velocity to 5 for one tick, then set that variable false so it doesn't keep repeating.
int velocityX = 0;
boolean ActiveA = false;
boolean didFullPress = false;
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A) {
ActiveA = true;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A && ActiveA) {
ActiveA = false;
didFullPress = true;
}
}
public void tick() {
x += velocityX;
if (didFullPress){
velocityX = 5
didFullPress = false;
}
else {velocityX = 0 }
}
I'm writing a CashRegister program and I'm currently working on the CashierView where I have added an option for the Cashier to input the amount of cash received by the customer. I now formatted it so that the user only can input numbers and 1 period. I now want to limit the numbers you can input after the period to two. I'm struggling to make this work.
I commented out one of the codes that I tried, but didn't work, incase it might be interesting.
Appreciate all the help!
Br,
Victor
private void jCashReceivedKeyTyped(java.awt.event.KeyEvent evt) {
char c = evt.getKeyChar(); //Allows input of only Numbers and periods in the textfield
//boolean tail = false;
if ((Character.isDigit(c) || (c == KeyEvent.VK_BACKSPACE) || c == KeyEvent.VK_PERIOD)) {
int period = 0;
if (c == KeyEvent.VK_PERIOD) { //Allows only one period to be added to the textfield
//tail = false;
String s = getTextFieldCash();
int dot = s.indexOf(".");
period = dot;
if (dot != -1) {
evt.consume();
}
}
//. if (tail=true){ //This is the code that I tried to use to limit input after the period to two
// String x = getTextFieldCashTail();
// if (x.length()>1){
// evt.consume();
// }
// }
}
else {
evt.consume();
}
}
If you're dead set on doing this with a KeyEvent, here's one possible method:
private void jCashReceivedKeyTyped(java.awt.event.KeyEvent evt) {
char c = evt.getKeyChar(); //Allows input of only Numbers and periods in the textfield
if ((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || c == KeyEvent.VK_PERIOD)) {
String s = getTextFieldCash();
int dot = s.indexOf(".");
if(dot != -1 && c == KeyEvent.VK_PERIOD) {
evt.consume();
} else if(dot != -1 && c != KeyEvent.VK_BACK_SPACE){
String afterDecimal = s.substring(dot + 1);
if (afterDecimal.length() > 2) {
evt.consume();
}
}
}
}
Hope this helps. Just keep in mind that by listening to a KeyEvent, if someone copies and pastes values into your JTextField, this won't catch that. If you want to catch any possible type of input, you'll want to use a DocumentListener. If you're wondering how to use a DocumentListener, here is some code that shows how to use it on a JTextField.
I have Android soft keyboard which switch between two languages. Each language has it's own layout (xml). The English language is working but Arabic language has bug. When I enter Arabic letters and immediate after pressing number or symbol remove the letters.
private void handleCharacter(int primaryCode, int[] keyCodes) {
if (isInputViewShown()) {
if (mInputView.isShifted()) {
primaryCode = Character.toUpperCase(primaryCode);
}
}
if (isAlphabet(primaryCode) && mPredictionOn) {
mComposing.append((char) primaryCode);
getCurrentInputConnection().setComposingText(mComposing, 1);
updateShiftKeyState(getCurrentInputEditorInfo());
updateCandidates();
}
getCurrentInputConnection().commitText(
String.valueOf((char) primaryCode), 1);
}
#Override public void onFinishInput() {
super.onFinishInput();
// Clear current composing text and candidates.
mComposing.setLength(0);
updateCandidates();
// We only hide the candidates window when finishing input on
// a particular editor, to avoid popping the underlying application
// up and down if the user is entering text into the bottom of
// its window.
setCandidatesViewShown(false);
mCurKeyboard = mQwertyKeyboard;
if (mInputView != null) {
mInputView.closing();
}
}
#Override public void onUpdateSelection(int oldSelStart, int oldSelEnd,
int newSelStart, int newSelEnd,
int candidatesStart, int candidatesEnd) {
super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd,
candidatesStart, candidatesEnd);
// If the current selection in the text view changes, we should
// clear whatever candidate text we have.
if (mComposing.length() > 0 && (newSelStart != candidatesEnd
|| newSelEnd != candidatesEnd)) {
mComposing.setLength(0);
updateCandidates();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.finishComposingText();
}
}
}
private void commitTyped(InputConnection inputConnection) {
if (mComposing.length() > 0) {
inputConnection.commitText(mComposing, mComposing.length());
mComposing.setLength(0);
updateCandidates();
}
}
/**
* Helper to update the shift state of our keyboard based on the initial
* editor state.
*/
private void updateShiftKeyState(EditorInfo attr) {
if (attr != null
&& mInputView != null && mQwertyKeyboard == mInputView.getKeyboard()) {
int caps = 0;
EditorInfo ei = getCurrentInputEditorInfo();
if (ei != null && ei.inputType != InputType.TYPE_NULL) {
caps = getCurrentInputConnection().getCursorCapsMode(attr.inputType);
}
mInputView.setShifted(mCapsLock || caps != 0);
}
}
/**
* Helper to determine if a given character code is alphabetic.
*/
private boolean isAlphabet(int code) {
if (Character.isLetter(code)) {
return true;
} else {
return false;
}
}
Let me know if more code is required. I also checked the related question on stackoverflow regarding this question and it only helped to fix the English language.
The Arabic is RTL, and it works fine when typing English and Arabic, but has problem with numbers and symbols.
I solved the problem by replacing the handlerCharacter method with the following:
private void handleCharacter(int primaryCode, int[] keyCodes) {
if (isInputViewShown()) {
if (mInputView.isShifted()) {
primaryCode = Character.toUpperCase(primaryCode);
}
}
if (isAlphabet(primaryCode) && mPredictionOn) {
mComposing.append((char) primaryCode);
getCurrentInputConnection().setComposingText(mComposing, 1);
updateShiftKeyState(getCurrentInputEditorInfo());
updateCandidates();
}
else {
mComposing.append((char) primaryCode);
getCurrentInputConnection().setComposingText(mComposing, 1);
}
}
I've got one textField where I only accept numbers from the keyboard, but now I have to change it as it's a "price textField" and I would also need to accept a dot "." for any kind of prices.
How can I change this in order to get what I need?
ptoMinimoField = new JTextField();
ptoMinimoField.setBounds(348, 177, 167, 20);
contentPanel.add(ptoMinimoField);
ptoMinimoField.setColumns(10);
ptoMinimoField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char caracter = e.getKeyChar();
if (((caracter < '0') || (caracter > '9'))
&& (caracter != '\b')) {
e.consume();
}
}
});
As suggested by Oracle ,Use Formatted Text Fields
Formatted text fields provide a way for developers to specify the valid set of characters that can be typed in a text field.
amountFormat = NumberFormat.getNumberInstance();
...
amountField = new JFormattedTextField(amountFormat);
amountField.setValue(new Double(amount));
amountField.setColumns(10);
amountField.addPropertyChangeListener("value", this);
I just use a try-catch block:
try {// if is number
Integer.parseInt(String);
} catch (NumberFormatException e) {
// else then do blah
}
JTextField txField = new DoubleJTextField();
Create a file DoubleJTextField.java and be happy
public class DoubleJTextField extends JTextField {
public DoubleJTextField(){
addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char ch = e.getKeyChar();
if (!isNumber(ch) && !isValidSignal(ch) && !validatePoint(ch) && ch != '\b') {
e.consume();
}
}
});
}
private boolean isNumber(char ch){
return ch >= '0' && ch <= '9';
}
private boolean isValidSignal(char ch){
if( (getText() == null || "".equals(getText().trim()) ) && ch == '-'){
return true;
}
return false;
}
private boolean validatePoint(char ch){
if(ch != '.'){
return false;
}
if(getText() == null || "".equals(getText().trim())){
setText("0.");
return false;
}else if("-".equals(getText())){
setText("-0.");
}
return true;
}
}
Don't ever use a KeyListener for this. Your code above has two serious bugs, both caused by the use of a KeyListener. First, it will miss any text that gets pasted in. Whenever I find a field that filters out non-digits, I always try to paste in some text, just for fun. Nine times out of ten, the text gets accepted, because they used a key listener.
Second, you didn't filter out modifiers. If the user tries to save their work by typing control-s while they're in this field, your key listener will consume the event. And if your application assigns, say, a control-5 or alt-5 shortcut to some action, this KeyListener will add a 5 to the field when they type it, even though the user wasn't trying to type a character. You did figure out that you needed to pass the backspace key, but that's not all you need to pass. Your arrow keys won't work. Neither will your function keys. You can fix all these problems, but it starts to be a lot of work.
There's a third disadvantage, but it only shows up if you adapt your application to a foreign alphabet, particularly one that takes multiple keystrokes to generate a single character, like Chinese. These alphabets make KeyListeners useless.
The trouble is this. You need to filter characters, but KeyListeners aren't about characters, they're about keystrokes, which are not the same thing: Not all keystrokes generate characters, and not all characters are generated by keystrokes. You need an approach that looks at characters after they've been generated, and after modified keystrokes have already been filtered out.
The simplest approach is to use a JFormattedTextField, but I've never liked that approach, because it doesn't format or filter as you type. So instead, I will use a DocumentFilter. DocumentFilters don't operate on keystrokes, they operate on the text strings as they get inserted to your JTextField's data model. Hence, all the control-keys, arrow and function keys and such don't even reach the DocumentFilter. All pasted text goes through the DocumentFilter, too. And, for languages that take three keystrokes to generate a single character, the DocumentFilter doesn't get invoked until the character is generated. Here's what it looks like:
ptoMinimoField = new JTextField();
ptoMinimoField.setBounds(348, 177, 167, 20); // Don't do this! See below.
contentPanel.add(ptoMinimoField);
ptoMinimoField.setColumns(10);
PlainDocument document = (PlainDocument) ptoMinimoField.getDocument();
document.setDocumentFilter(new DigitFilter());
}
The DigitFilter class looks like this:
public class DigitFilter extends DocumentFilter {
#Override
public void insertString(FilterBypass fb, int offset, String text,
AttributeSet attr) throws BadLocationException {
super.insertString(fb, offset, revise(text), attr);
}
#Override
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
super.replace(fb, offset, length, revise(text), attrs);
}
private String revise(String text) {
StringBuilder builder = new StringBuilder(text);
int index = 0;
while (index < builder.length()) {
if (accept(builder.charAt(index))) {
index++;
} else {
// Don't increment index here, or you'll skip the next character!
builder.deleteCharAt(index);
}
}
return builder.toString();
}
/**
* Determine if the character should remain in the String. You may
* override this to get any matching criteria you want.
* #param c The character in question
* #return true if it's valid, false if it should be removed.
*/
public boolean accept(final char c) {
return Character.isDigit(c) || c == '.';
}
}
You could write this as an inner class, but I created a separate class so you can override the accept() method to use any criteria you want. You may also notice that I don't test for digits by writing this:
(c < '0') || (c > '9')
Instead, I do this:
Character.isDigit()
This is faster, cleaner, and works with foreign numbering systems. I also don't need your test for the backspace character, '\b'. I'm guessing that your first KeyListener was filtering out the backspace key, which was your first clue that it was the wrong approach.
And on an unrelated note, don't hard code your component positions. Learn how to use the LayoutManagers. They're easy to use, and they'll make your code much easier to maintain.
Have you looked at a JFormattedTextField? It would seem it does what you want.
Enter the double number of JTextField in java
private boolean dot = false;
private void txtMarkKeyTyped(java.awt.event.KeyEvent evt) {
char vChar = evt.getKeyChar();
if (txtMark.getText().equals(""))
dot = false;
if (dot == false){
if (vChar == '.') dot = true;
else if (!(Character.isDigit(vChar)
|| (vChar == KeyEvent.VK_BACK_SPACE)
|| (vChar == KeyEvent.VK_DELETE))) {
evt.consume();
}
} else {
if (!(Character.isDigit(vChar)
|| (vChar == KeyEvent.VK_BACK_SPACE)
|| (vChar == KeyEvent.VK_DELETE))) {
evt.consume();
}
}
}
This bit of code;
if (((caracter < '0') || (caracter > '9'))
&& (caracter != '\b')) {
decides whether to consume the key event. You need to update the condition so it doesn't consume the dot character.
Just right click on TextField / events / key / keytyped
if(!Character.isDigit(evt.getKeyChar())){
evt.consume();}
/////////////
JTextField ptoMinimoField = new JTextField();
ptoMinimoField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
boolean ret = true;
try {
Double.parseDouble(ptoMinimoField.getText()+e.getKeyChar());
}catch (NumberFormatException ee) {
ret = false;
}
if (!ret) {
e.consume();
}
}
});
maybe can help you for filtering keytyped just number and dot
public void filterHanyaAngkaDot(java.awt.event.KeyEvent evt){
char c = evt.getKeyChar();
if (! ((Character.isDigit(c) ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE))
)&& c==KeyEvent.VK_COMMA
)
{
evt.consume();
}
}
JTextField txtMyTextField = new JTextField();
numOnly(txtMyTextField);
public void numOnly(Object objSource){
((Component) objSource).addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
String filterStr = "0123456789.";
char c = (char)e.getKeyChar();
if(filterStr.indexOf(c)<0){
e.consume();
}
}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {}
});
}
WARNING: This function does not follow proper java documentation
guide.
I have been using this solution, it's simple and efficient:
jtextfield.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char vChar = e.getKeyChar();
if (!(Character.isDigit(vChar)
|| (vChar == KeyEvent.VK_BACK_SPACE)
|| (vChar == KeyEvent.VK_DELETE))) {
e.consume();
}
}
});
private boolean point = false;
private void txtProductCostPriceAddKeyTyped(java.awt.event.KeyEvent evt)
{
char Char = evt.getKeyChar();
if (txtProductCostPriceAdd.getText().equals(""))
point = false;
if (point == false){
if (Char == '.') point = true;
else if (!(Character.isDigit(Char) || (Char == KeyEvent.VK_BACK_SPACE) || (Char == KeyEvent.VK_DELETE))) {
evt.consume();
}
} else {
if (!(Character.isDigit(Char) || (Char == KeyEvent.VK_BACK_SPACE) || (Char == KeyEvent.VK_DELETE))) {
evt.consume();
}
}
}
JTextField textField = new JTextField();
textField.setColumns(10);
textField.addKeyListener(new KeyAdapter() {
#Override
public void KeyTyped(KeyEvent e) {
if (!(e.getKeyChar() >= '0' && e.getKeyChar() <= '9')) {
e.consume();
}
}
})
this is the easiest method i have found so far, and it works without any error
I'm creating an ATM machine with pin function. The problem is I want to get the input from the button when its pressed by the user and validate if its correct or wrong. When the button is pressed, it will store the result in the string. It will then be used to validate if its correct or wrong. For example: User A pressed 012345. Each number will then be stored to another string for validation. The string is then compared to the pin.
public class atmMachine:
int numberPinButton = 10;
String pin = "012345";
String zero, one, two, three, four, five, six, seven, eight, nine;
public atmMachine:
panel = new JPanel();
pinButton = new JButton[numberPinButton];
for(int i = 0; i < numberPinButton; i++) {
pinButton[i] = new JButton("" + i);
pinButton[i].addActionListener(this);
panel.add(pinButton[i]);
}
enterButton = new JButton("Enter");
enterButton.addActionListener(this);
panel.add(enterBtn);
panel.setBorder(BorderFactory.createTitledBorder("Enter your pin:"));
add(panel, BorderLayout.WEST);
public void actionPerformed:
public void actionPerformed(ActionEvent event) {
if(event.getSource() == pinButton[0]) {
zero = "0";
} else if(e.getSource() == pinButton[1]) {
one = "1";
} else if(e.getSource() == pinButton[2]) {
two = "2";
} else if(e.getSource() == pinButton[3]) {
three = "3";
} else if(e.getSource() == pinButton[4]) {
four = "4";;
} else if(e.getSource() == pinButton[5]) {
five = "5";
} else if(e.getSource() == pinButton[6]) {
six = "6";
} else if(e.getSource() == pinButton[7]) {
seven = "7";
} else if(e.getSource() == pinButton[8]) {
eight = "8";
} else if(e.getSource() == pinButton[9]) {
nine = "9";
}
if(e.getSource() == enterBtn) {
if(???.equals(pin)) {
System.out.println("Correct");
} else {
System.out.println("Wrong");
}
}
}
Have an instance variable-
StringBuffer userKeyString = new StringBuffer();
On action performed, append any digit button pressed-
userKeyString.append(event.getActionCommand());
On action performed, if enter pressed-
if(event.getSource() == enterBtn){
if(pin.equals(userKeyString.toString()){
// Correct pin
} else {
// Incorrect pin
}
userKeyString.setLength(0); // Clear the buffer for next input and validation
} else {
userKeyString.append(event.getActionCommand());
}
You should set the action commands of your buttons-
for(int i = 0; i < numberPinButton; i++) {
pinButton[i] = new JButton("" + i);
pinButton[i].setActionCommand(String.valueOf(i));
pinButton[i].addActionListener(this);
panel.add(pinButton[i]);
}
You can declare String pin as a field like:
String pin;
then in action performed you append to it (pseudo code)
actionPerformed(...){
pin += keyPressed;
if(pin.length > 5){
validatePin(pin);
}
}
Does this answer your question?
But to be honest I would suggest against validation in the action performed method. I'd try to validate the pin after all the numbers were inserted. This way you can save a bit on performance and the code would be more readable. The performance isn't an issue here but it's a good practice as you would check the pin 6 times here instead of just once outside the actionPerformed method.
Like:
for(int i = 0; i < pinLength; i++){
waitForUserToPressButtonOrTimeout();
appendToCurrentPin();
}
validatePin();
Or let the user simply press another button after entering the pin code and link validation to that button. But I think using String pin field and appending to it is an answer to your question.