//Author: ^-^ Veerle ^-^ import javax.swing.JTextField; import java.awt.event.*; public class currencyConverter2K implements KeyListener //Class used for testing the numbers input for currencies { public currencyConverter2K () { } public void keyTyped(KeyEvent e) { //Instead of trying to find which txt field was used, this creates a temp copy of that txt field by converting the source into //a txt field. JTextField txtTemp = (JTextField)e.getSource(); String strBuffer = txtTemp.getText(); boolean removeKey = false; //Flag used for if the key should be removed or not char c = e.getKeyChar(); //Get the key that was pressed if (c == ' ') //If space { removeKey = true; } else if (strBuffer.indexOf('.') != -1 && c == '.') //If a decimal place already exists, and the user has typed another decimal place { removeKey = true; } //If char is not a digit, not back space, not delete and not a decimal place else if (!((Character.isDigit(c)) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE) || (c == '.'))) { removeKey = true; } if (!removeKey && strBuffer.indexOf('.') != -1) //If a decimal place exists, and the key at the momment is still legal { int decimalPosition = strBuffer.indexOf('.'); //Get the index number of the decimal place int decimalPlaces = (strBuffer.length() - 1) - decimalPosition; //Counts how many numbers exist after the decimal place //If two decimal places exist AND current text position is past the decimal position AND entered key is NOT backspace OR delete if (decimalPlaces >= 2 && (txtTemp.getSelectionStart() > decimalPosition) && !((c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE))) { removeKey = true; } } if (removeKey) { e.consume(); //Consumes the current key so it is not used } } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } }