Clear textField immediately after entering char in Java Swing - java

After entering into textField one of this letters: "e,E,f,F,g,G", the comboBox in my app is changing. I want to clear my textField immediately after entering one of this letters but i can't do this. I use :
tekstField.setText("");
but it doesn't work. Probably it because that i can't eat listener in Swing.
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
updateLog(e);
}
public void removeUpdate(DocumentEvent e) {
}
public void insertUpdate(DocumentEvent e) {
updateLog(e);
}
public void updateLog(DocumentEvent e) {
Document doc = (Document) e.getDocument();
int docLength = doc.getLength();
String key;
try {
key = e.getDocument().getText(0, docLength);
if (docLength == 1 && !key.matches("^[0-9]$")) {
char labSymbol = key.charAt(0);
switch (labSymbol) {
case 'E' :
case 'e' :
labTypeComboBox.setSelectedIndex(0);
break;
case 'F' :
case 'f' :
labTypeComboBox.setSelectedIndex(1);
break;
case 'G' :
case 'g' :
labTypeComboBox.setSelectedIndex(2);
break;
default :
break;
}
tekstField.setText("");
}
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
Anybody know how to solve this problem?

Related

EDIT - Java while loop means events aren't called

So I've updated my code with the help of Cruncher, and now the clicker appears to work better. However whilst the while(pressed) loop is running, no other events are called & so it stays running.
public class Function implements NativeMouseListener {
private Robot robot;
private boolean pressed = false;
private boolean skip = false;
public Function()
{
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
}
private void repeatMouse()
{
skip = true;
robot.mouseRelease(InputEvent.BUTTON1_MASK);
while (pressed)
{
System.out.println("pressed while loop " + pressed);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void nativeMouseClicked(NativeMouseEvent nativeMouseEvent) {
}
#Override
public void nativeMousePressed(NativeMouseEvent nativeMouseEvent) {
System.out.println("GG");
if (!(nativeMouseEvent.getButton() == NativeMouseEvent.BUTTON1)) {
System.out.println("Returned.");
return;
}
if (!Native.get().getData().getEnabled())
{
System.out.println("Isn't enabled.");
return;
}
pressed = true;
repeatMouse();
}
#Override
public void nativeMouseReleased(NativeMouseEvent nativeMouseEvent) {
System.out.println("released");
if (!(nativeMouseEvent.getButton() == NativeMouseEvent.BUTTON1)) {
System.out.println("Returned 2");
return;
}
if (!skip)
{
System.out.println("pressed " + pressed);
pressed = false;
System.out.println("pressed " + pressed);
} else {
skip = false;
}
}
}
Any idea why the while loop would stop events from being called? Do I need to use multi threading or some of that jazz?
Thank you.
For one, your main method is not included in your code, but I assume it contains the following line(or similar):
new Project()
try {
bot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
while (pressed) {
bot.mousePress(InputEvent.BUTTON1_MASK);
//bot.mouseRelease(InputEvent.BUTTON1_MASK);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Now let's look at this code. When this runs, pressed will be false at the beginning(presumably), and it will just exit and not be running on later clicks.
What you want to do is have your loop started when you register a click. Let's move it into another method
private void repeatMouse() {
bot.mouseRelease(InputEvent.BUTTON1_MASK);
while (pressed) {
bot.mousePress(InputEvent.BUTTON1_MASK);
bot.mouseRelease(InputEvent.BUTTON1_MASK);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Now let's call it in your mouse down native hook
#Override
public void nativeMousePressed(NativeMouseEvent nativeMouseEvent) {
if (nativeMouseEvent.getButton() == NativeMouseEvent.BUTTON1)
{
pressed = true;
System.out.println(pressed);
repeatMouse();
}
}
EDIT:
It appears your other problem is that after the first mouseRelease, the handler will get called from the native library. I have a potential solution for this.
First next to where you define your pressed variable, define a new skipRelease
boolean skipRelease = false;
Then before every call to mouseRelease, first set skipRelease to true. Then change your mouseRelease handler to the following
#Override
public void nativeMouseReleased(NativeMouseEvent nativeMouseEvent) {
if (nativeMouseEvent.getButton() == NativeMouseEvent.BUTTON1)
{
if(skipRelease) {
skipRelease = false;
return;
}
pressed = false;
System.out.println(pressed);
}
}

Enable Jbutton only if Validation is True

What is the best way to validate swing application's input fields such as text fields, comboboxes, etc and let the user to press Save button only if everything is ok. Assume that Search function also in the same interface. So searching for record will also fill up input fields. But Save button should remain disable in that case.
initComponents();
btnSave.setEnabled(false);
txt1.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void changedUpdate(DocumentEvent e) {
}
#Override
public void removeUpdate(DocumentEvent e) {
validate(txt1.getText(),e);
}
#Override
public void insertUpdate(DocumentEvent e) {
validate(txt1.getText(),e);
}
public void validate(String enteredText,DocumentEvent e) {
String currText = "";
try {
Document doc = (Document) e.getDocument();
currText = doc.getText(0, doc.getLength());
} catch (BadLocationException e1) {
}
if(enteredText.equals(currText)){
//if validated successfully
btnSave.setEnabled(false);
}else{
btnSave.setEnabled(true);
}
}
});
did you try like this?
final JTextField textField = new JTextField();
final JButton submitBtn = new JButton();
submitBtn.setEnabled(true);
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
validate(e);
}
public void removeUpdate(DocumentEvent e) {
validate(e);
}
public void insertUpdate(DocumentEvent e) {
validate(e);
}
public void validate(String enteredText) {
String currText = "";
try {
Document doc = (Document)e.getDocument();
currText = doc.getText(0, doc.getLength());
} catch (BadLocationException e1) {
e1.printStackTrace();
}
//validation of currText here
//if validated successfully
submitBtn.setEnabled(true);
//else
submitBtn.setEnabled(false);
}
});
Condition the enabled property of your Save button using setEnabled() in two places:
In your implementation of shouldYieldFocus() in an InputVerifier attached to each relevant component. The tutorial and some examples are cited here.
In your component's normal listener.
Create a method to check if all the inputs are completed or/and all the validations are passed and finally return a boolean.
public boolean validate(...){
//some stuff
if(validated){
return true;
}else{
return false;
}
}
then you can use it like.
button.setEnabled(validate(...));

Allow characters storage on JTextField only if are numbers

I want to filter the key that are pressed on JTextField.
I want that only numbers are allowed, and if other character are pressed it remove it or don't allow the storage on the text field.
I'm thinking to use an addKeyListener, and use the methods: key pressed and key released.
Any Ideas?
Try this
final JTextField myTextField = new JTextField();
myTextField.addKeyListener(new KeyListener() {
String oldText = "";
public void keyPressed(KeyEvent keyEvent) {
// Store old text in a temporary variable
oldText = myTextField.getText();
}
public void keyReleased(KeyEvent keyEvent) {
// Make sure that the user is typing a number else replace with old text.
int charCode = (int)keyEvent.getKeyChar();
if (charCode < 48 || charCode > 57){
myTextField.setText(oldText); // Replace with old text.
}
}
public void keyTyped(KeyEvent keyEvent) {
}
});
No offence, Mr. Ravindra's answer is correct but it fails when you type continuously ..
I hope this helps :
final JTextField myTextFiled=new JTextField();
JFrame frame=new JFrame("onlyNums");
KeyListener myKeyListner=new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyChar()>='0' && e.getKeyChar()<='9')
myTextFiled.setText(myTextFiled.getText()+e.getKeyChar());
else if(e.getKeyChar()==KeyEvent.VK_BACK_SPACE && myTextFiled.getText().length()>0)
myTextFiled.setText(myTextFiled.getText().substring(0, myTextFiled.getText().length()-1));
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
};
//to null out handling other inputs
myTextFiled.setInputMap(JTextField.WHEN_FOCUSED, new InputMap());
//to add your own handling
myTextFiled.addKeyListener(myKeyListner);
Note: You have to add handling to insert/remove from the pointer's position.
Regards,
Use a custom Document:
public class NumericDocument extends PlainDocument {
#Override
public void insertString(int pos, String text, AttributeSet as)
throws BadLocationException {
try {
Integer.parseInt(text);
super.insertString(pos, text, as);
} catch(NumberFormatException e) {
Toolkit.getDefaultToolkit().beep();
}
}
}
Install to your TextField:
JtextField field = new JTextField();
field.setDocument(new NumericDocument());
This will work, even if text is pasted (where no KeyEvent is fired).

How to use KeyEvent

I'm writing small graphics editor and I want catch event when I press Ctrl+A
I use such code (this is test version):
#Override
public void keyPressed(KeyEvent e) {
System.out.println("Press");
switch (e.getKeyCode()){
case KeyEvent.VK_A :
System.out.println("A");
break;
}
}
but I don't know how to catch Ctrl+a
I tryed something like this
case KeyEvent.VK_CONTROL+KeyEvent.VK_A :
System.out.println("A+CTRL");
break;
but this code KeyEvent.VK_CONTROL+KeyEvent.VK_A returns int and maybe another key combination returns the same number
So can someone can help me
You can use isControlDown() method:
switch (e.getKeyCode())
{
case KeyEvent.VK_A :
if(e.isControlDown())
System.out.println("A and Ctrl are pressed.");
else
System.out.println("Only A is pressed");
break;
...
}
Try this.....
f.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if ((e.getKeyCode() == KeyEvent.VK_A) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
System.out.println("woot!");
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
Try isControlDown method on KeyEvent: http://docs.oracle.com/javase/6/docs/api/java/awt/event/InputEvent.html#isControlDown%28%29

How can i prevent CTRL+C on a JTextField in java?

How can i prevent a user from copying the contents of a JTextField?
i have the following but i cannot figure a way to get multiple keys at the same time?
myTextField.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!Character.isDigit(c)) {
e.consume();
}
}
});
For this, you will have to modify your KeyAdapter so that it can register when a key was pressed and when it was released, so that we may know when both keys were pressed simultaneously, the following code should do the trick:
textfield.addKeyListener(new KeyAdapter() {
boolean ctrlPressed = false;
boolean cPressed = false;
#Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_C:
cPressed=true;
break;
case KeyEvent.VK_CONTROL:
ctrlPressed=true;
break;
}
if(ctrlPressed && cPressed) {
System.out.println("Blocked CTRl+C");
e.consume();// Stop the event from propagating.
}
}
#Override
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_C:
cPressed=false;
break;
case KeyEvent.VK_CONTROL:
ctrlPressed=false;
break;
}
if(ctrlPressed && cPressed) {
System.out.println("Blocked CTRl+C");
e.consume();// Stop the event from propagating.
}
}
});
i was just adding this to one of my JTextFields.

Categories