JApplet - alphabet will not allowed - java

this is my code, which is written inside my applet
KeyListener keyListener = new KeyListener()
{
public void keyPressed(KeyEvent keyEvent)
{
validate valid=new validate();
valid.errorMessage(txt_district_id, keyEvent);
}
public void keyReleased(KeyEvent keyEvent)
{
}
public void keyTyped(KeyEvent keyEvent)
{
}
};
txt_district_id.addKeyListener(keyListener);
and code of validate class is
public class validate
{
public String errorMessage(KeyEvent keyEvent,JTextField txt)
{
int keyCode = keyEvent.getKeyCode();
String keyText = KeyEvent.getKeyText(keyCode);
//msg.setText(title + " : " + keyText + " / " + keyEvent.getKeyChar());
if(keyCode > 47 && keyCode < 58)
{
txt.setEditable(true);
}
else
{
txt.setEditable(false);
return "Only Numeric Value Accepted";
}
}
}
everything working properly, but the problem is whenever user input any alphabet the textfield will become disable, and that is my problem. I mean it should like, alphabet can not be entered and textfield should be enabled in any case. Thanks in advance.!!

Use DocumentListener for listening changes inside JTextComponents,
Don't use KeyListener, this Listener is designated for prehistoric AWT Components, for Swing JComponents (JApplet) use KeyBindings

Related

Get caret position when key pressed using KeyboardFocusManager

I'm trying to get the current caret position when the "<" character is typed, using a KeyboardFocusManager. Code below. If the text field is empty when they character is typed I would expect the caret position to be 0. However, the result I actually get is this: 0 0 1. Could anyone explain why this is happening?
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TextEditor {
#SuppressWarnings("serial")
public static class TextClass extends JTextArea {
static int startpos = 0;
public boolean checkKeyTyped (KeyEvent e) {
String keystr = Character.toString(e.getKeyChar());
switch (keystr) {
case "<":
startpos = getSelectionStart();
System.out.print(" " + startpos);
}
return false;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
final JTextArea textArea = new TextClass();
frame.add(textArea);
frame.setVisible(true);
// Add keyboard listener
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
return ((TextClass) textArea).checkKeyTyped(e);
}
});
}
}
You are using a general Key Event dispatcher. The possible events are KEY_PRESSED, KEY_TYPED and KEY_RELEASED. Based on what you say, you need KEY_TYPED. So filter for that:
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.KEY_TYPED) {
return ((TextClass) textArea).checkKeyTyped(e);
}
}
});
It is not how you are supposed to do it, you are supposed to implement a KeyListener and add it to your JTextArea using addKeyListener(KeyListener), as next:
final JTextArea textArea = new TextClass();
...
textArea.addKeyListener(new KeyListener() {
#Override
public void keyTyped(final KeyEvent e) {
char key = e.getKeyChar();
switch (key) {
case '<':
System.out.print(" " + textArea.getSelectionStart());
}
}
#Override
public void keyPressed(final KeyEvent e) {
}
#Override
public void keyReleased(final KeyEvent e) {
}
});
Up to now, you get it printed 3 times because your method is called for each type of KeyEvent that is triggered whenever you type on a key:
KEY_TYPED
The "key typed" event. This event is generated when a character is
entered. In the simplest case, it is produced by a single key press.
Often, however, characters are produced by series of key presses, and
the mapping from key pressed events to key typed events may be
many-to-one or many-to-many.
KEY_PRESSED
The "key pressed" event. This event is generated when a key is pushed
down.
KEY_RELEASED
The "key released" event. This event is generated when a key is let
up.

Restrict Input of JTextField to Double Numbers?

In java , i am trying to make simple currency converter, but for that i need a text field which can restrict input to numbers only and more importantly double numbers. I tried using JFormatedTextField but it only format the input after you have done your input and click elsewhere but i need to restrict TextField to consume() each invalid character while doing input.
Possible Attempts:
Using JFormatedTextField:
JFormatedTextField textField = new JFormatedTextField(new DoubleFormat());
textField.setBounds(190, 49, 146, 33);
frame.getContentPane().add(textField);
textField.setColumns(10);
Using KeyTyped Event:
char c = arg0.getKeyChar();
if(!(Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE || c== KeyEvent.VK_DELETE)){
arg0.consume();
}
Using KeyTyped Event with regex:
if(!((textField.getText().toString+arg0.getKeyChar()).matches("[0-9]*(.[0-9]*)?"))){
arg0.consume();
}
Second and third attempt were close but then second attempt failed on point values and third attempt always read first character on textField no matter what it is, So any suggestions ? i am not very fond of JAVA GUI so kindly be patient.
If you know how many places before and after decimal point you want, you can also use MaskFormatter. For example:
JFormattedTextField field = new JFormattedTextField(getMaskFormatter("######.##"));
(...)
private MaskFormatter getMaskFormatter(String format) {
MaskFormatter mask = null;
try {
mask = new MaskFormatter(format);
mask.setPlaceholderCharacter('0');
}catch (ParseException ex) {
ex.printStackTrace();
}
return mask;
}
However it will chenge a look of JTextField, so it will be always visible 000000.00 in it.
EDIT
Another way, not too elegant, but in my opinion working. Try with DecumentListener, maybe it will suit your needs:
field = new JFormattedTextField();
field.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
Runnable format = new Runnable() {
#Override
public void run() {
String text = field.getText();
if(!text.matches("\\d*(\\.\\d{0,2})?")){
field.setText(text.substring(0,text.length()-1));
}
}
};
SwingUtilities.invokeLater(format);
}
#Override
public void removeUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent e) {
}
});
I used regex: \\d*(\\.\\d{0,2})? because two decimal places is enough for currency.
You would need to use a DocumentFilter. Read the section from the Swing tutorial on Implementing a DocumentFilter for an example to get you started.
Your implementation will be more complex because you will need to take the text already in the Document and then insert the new text in the appropriate location in the String and then invoke Double.parseDouble(...) on the String to make sure it is a valid double value.
If the validation succeeds then you continue with the insertion otherwise you can generate beep.
You can add a key listener to the text field and implement the keyReleased() method to determine if they value in the text field is a double after every key stroke by the user.
public class CurrencyJTF extends JFrame {
JButton jButton = new JButton("Unfocus");
final JFormattedTextField textField = new JFormattedTextField(new DecimalFormat());
double lastDouble = 0.0;
public CurrencyJTF() throws HeadlessException {
textField.setColumns(20);
textField.setText(lastDouble + "");
this.setLayout(new FlowLayout());
this.add(textField);
this.add(jButton);
textField.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
handleKeyReleased();
}
});
}
private void handleKeyReleased() {
String text = textField.getText();
if (text.isEmpty()) return;
try {
lastDouble = Double.parseDouble(text);
} catch (NumberFormatException ex) {
textField.setText(lastDouble + ""); // or set to other values you want
}
}
public static void main(String[] args) {
JFrame frame = new CurrencyJTF();
frame.setVisible(true);
frame.pack();
}
}
You can write your own KeyListener something like that:
public class DoubleNumbersKeyListener implements KeyListener {
final HashSet<Character> valid_keys = new HashSet<>();
final ArrayList<Character> sequence = new ArrayList<>();
public DoubleNumbersKeyListener() {
valid_keys.add('.');
valid_keys.add('0');
valid_keys.add('1');
valid_keys.add('2');
valid_keys.add('3');
valid_keys.add('4');
valid_keys.add('5');
valid_keys.add('6');
valid_keys.add('7');
valid_keys.add('8');
valid_keys.add('9');
valid_keys.add((char) KeyEvent.VK_BACK_SPACE);
valid_keys.add((char) KeyEvent.VK_DELETE);
}
#Override
public void keyTyped(KeyEvent event) {
char c = event.getKeyChar();
if (!valid_keys.contains(c)) {
event.consume();
} else {
if (c == KeyEvent.VK_DELETE || c == KeyEvent.VK_BACK_SPACE) {
if (!sequence.isEmpty()) {
char last = sequence.remove(sequence.size() - 1);
if (last == '.') {
valid_keys.add(last);
}
}
} else {
sequence.add(c);
if (c == '.') {
valid_keys.remove(c);
}
}
}
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
}

Java How to get ascii char from key code

I want to get ascii char from each key that user inputs into JComponent.
<JComponentName>.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
char ch = getAsciiCharFromKeyCode(e.getKeyCode());
}
});
private char getAsciiCharFromKeyCode(int keyCode) {
// this implementation is what I'm interested in
}
When I press 'e' (English 'e') and 'у' (Cyrillic 'u'), I get the same key code (0x45 or KeyEvent.VK_E). Is there some way to implement getAsciiCharFromKeyCode function without writing my own hash map like this:
HashMap<Integer, Character> keyCodeToChar = new HashMap<Integer, Character>();
keyCodeToChar.put(KeyEvent.VK_E, 'e');
?
As Pshermo already mentioned the method you are looking for is e.getKeyChar() however, it is only meaningfull in the method keyTyped as explained here
Your code would modified look like this:
<JComponentName>.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
char ch = e.getKeyChar();
}
});
Check out the tutorial Oracle: How to Write a Key Listener for more information on how to use KeyEvent to grab key info.
Oracle says:
For key-typed events you can obtain the key character value as well as any modifiers used.
Note:
You should not rely on the key character value returned from getKeyChar unless it is involved in a key-typed event.
You may need to set the locale to accept language specific keyboard characters.
class MyFrame extends JFrame {
private JTextArea txtara;
private JLabel lbl;
public MyFrame() {
super();
this.getContentPane().setLayout();
this.getInputContext().selectInputMethod(new Locale("ru")); // Russian
txtara = new JTextArea(5, 20);
lbl = new JLabel("Key: ");
txtara.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
lbl.setText("Key: " + e.getKeyChar()); // Show typed character
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
};
this.getContentPane().add(txtara, BorderLayout.CENTER);
this.getContentPane().add(lbl, BorderLayout.SOUTH);
}
}
Disclaimer: This code has not been compiled...

Java AWT KeyListener not working

I have been playing around with Java and I added a KeyListener. When I type a key it prints "0" and I would like it to print the key code.
Key.java
import java.awt.event.*;
public class Key implements KeyListener {
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
System.out.println("TYPED: " + Integer.toString(e.getKeyCode()));
}
}
Main.java
public void init() {
addKeyListener(new Key());
addMouseListener(new Mouse());
this.setBackground(new Color(100, 100, 255));
this.setSize(screen);
}
Thanks for all the help!
Just read the doc :
void keyTyped(KeyEvent e)
Invoked when a key has been typed. See the class description for
KeyEvent for a definition of a key typed event.
So go through the description :
public int getKeyCode()
Returns the integer keyCode associated with the key in this event.
Returns: the integer code for an actual key on the keyboard. (For
KEY_TYPED events, the keyCode is VK_UNDEFINED.)
And the constant VK_UNDEFINED is :
public static final int VK_UNDEFINED = 0;
So that's totally normal you only get 0.
You should use :
public void keyTyped(KeyEvent e) {
System.out.println("TYPED: " + e.getKeyChar());
}
Here's an example using the three methods.
For KEY_TYPED event, the Key Code is undefined. Check the java docs:
http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html#getKeyCode()
Use getKeyChar() instead.

Java Swing: How to get TextArea value including the char just typed?

What's the best way to get a value of a TextArea after a key is typed, including this character?
If I do it in the even listener, textarea.getText() returns the value without the eventual new char.
Basically I see two ways:
postponing processing with something like invokeLater(). I would prefer a solution without threads.
figuring out where to put the char into the text, based on the carret position.
Is there any other, simpler?
Thanks.
Edit: This is what I have:
JTextArea textarea = (JTextArea) evt.getComponent();
String texySource = textarea.getText();
char keyCode = evt.getKeyChar();
//if( Character.isLetterOrDigit( keyCode ) || Character.isSpaceChar( keyCode ) )
if( keyCode >= 0x20 || keyCode == 0x0A || keyCode == 0x0D ){
// TODO: The carret doesn't have to be at the end...
//texySource += Character.toString( evt.getKeyChar() );
String ch = Character.toString( evt.getKeyChar() );
texySource = StringUtils.overlay(texySource, ch,
textarea.getSelectionStart(),
textarea.getSelectionStart() );
}
Have you considered a document listener? possibly armed by the typing event?
class TheListener implements DocumentListener, KeyListener {
boolean armed;
void keyPressed(KeyEvent ignore) { }
void keyReleased(KeyEvent ignore) { }
void keyTyped(KeyEvent e) {
armed = true;
SwingUtilities.invokeLater(new Runnable() { public void run() {
armed = false;
}
}
void deleteUpdate(DocumentEvent e) {
changeUpdate(e);
}
void insertUpdate(DocumentEvent e) {
changeUpdate(e);
}
void changedUpdate(DocumentEvent e) {
if (armed) {
String s = ((JTextComponent)e.getSource()).getText();
//.... whatever you want to do now
}
}
}
//...
TheListener aListener = new TheListener();
textArea.addKeyListener(aListener);
textArea.getDocument().addDocumentListener(aListener);
The theory is to arm the document change listener on a key typed, then add an EDT event to disarm it. The document changes will occur first before disarmed. Once armed, you can assume that any document changes were caused in some part by the key typing event. (warning, I haven't compiled this code, YMMV).
You need to use a DocumentListener and wirte your code in one of the xxxupdate() methods.
Have you tried registering a KeyListener with a custom implementation of keyReleased(KeyEvent e) ?
check the api here: KeyListener
sun's tutorial with examples: How to write a Key Listener

Categories