Java KeyListener not firing on JSpinner - java

have tried a few different approaches to this but with no success so far. Just wondered if I'm missing anything. I have a JSpinner which is a component of a DateSelector widget alongside a Calendar. I am trying to fire a validation method if the user changes any text in the JSpinner instead of using the Calendar control or the JSpinner up and down arrows.
Here are the different approaches I have tried:
jSpinner1.addKeyListener(kl);
jSpinner1.getEditor().addKeyListener(kl);
((JSpinner.DefaultEditor) jSpinner1.getEditor().getTextField().addKeyListener(kl);
Anyone out there got any ideas as to what I'm doing wrong? Thanks
UPDATE
Apologies, I should have said that I have already added a ChangeListener to the JSpinnerDateModel which is attached to the JSpinner. Like so:
ChangeListener changeListener = new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
dateChanged();
}
};
jSpinnerDateModel.addChangeListener(changeListener);
KeyListener keyListener = new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyChar());
dateChanged();
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
};
((JSpinner.DefaultEditor) jSpinner1.getEditor()).getTextField().addKeyListener(
keyListener);
Thanks
Frank

If you want to disable keyboard editing do this:
JFormattedTextField tf = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField();
tf.setEditable(false);
To listen for key events you need to add a listener to the text field. This works for me:
((JSpinner.DefaultEditor)spinner.getEditor()).getTextField().addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("PRESSED!");
}
#Override
public void keyTyped(KeyEvent e) {
}
});

JSpinners handle KeyEvents themselves, but they fire ChangeEvents to the outside world. Adding a ChangeListener should allow you to perform the validation you wish.
See also: Detecting Spinner Value Changes (Java Tutorials)

This is a shortfall of swing, and in my opinion JSpinner should follow JComboBox in supplying the following access to the underlying text field:
JComboBox.getEditor().getEditorComponent()
From going through the source of J1.7 I found you can acheive pretty much the same thing with
JSpinner.getEditor().getComponent(0)
Therefore you can "hack" the listener in the following way:
JSpinner.getEditor().getComponent(0).addKeyListener(...)
Obviously this depends on the 'under the covers' implementation of swing and works as at J1.7 but there is no guarantee this works for other versions future or past.
Enjoy.
EDIT
or if the editor is an instance of DefaultEditor, you can cast it as such and use 'getTextField()'. It would be handy if this were defined in the interface.

Related

Java - MousePress Hold and Release event listener

hello is there a way mouse even that can Hold the mouse and release cause I can't find it on google.
so for example this image..
When the jTextBox is **** when he click the button, he see the words oops...
then after he release the click of mouse the jTextBox will back to **** again
I know this code already but the mouseevent is I only don't know
Yes. You will want to implement the MouseListener interface with a new class and add this new Listener against your button with the following;
button.addMouseListener(new YourMouseListener());
An example custom MouseListener might look like this.
class YourMouseListener implements MouseListener {
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
// Insert code to show password
}
#Override
public void mouseReleased(MouseEvent e) {
// Insert code to hide password again
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
I hope this helps.
You'll need a Robot object. This can do things as follows:
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
The Mousebutton is pressed until you do this:
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
This should do what you want.

Java Swing default focus on frame

I am learning java and Swing right now and trying to develop simple programms for education purposes.
So here is the question.
I have gridlayout and fields on my frame with default text
accNumberField = new JTextField("0", 10);
accNumberField.addFocusListener(new FocusListener() {
int focusCounter = 0;
#Override
public void focusGained(FocusEvent arg0) {
// TODO Auto-generated method stub
if (focusCounter > 0)
accNumberField.setText("");
focusCounter++;
}
What I want is that when user click on field for the first time the default text is disappered. So I add focus listener and used accNumberField.setText(""); in focusGained method.
But the problem is that for default first field in my frame getting focus right in time of frame creation. And default text is disappearing from the begining. I used counter as you can see. But that's not what I wanted.
I want that no field would get focus in time of creation and every field would be able to get focus from the time when user would click on one of them.
Sorry if I spelled something wrong. English is not my native language.
Found a thread having a code example of your desired functionality, Java JTextField with input hint. Precisely, you need to provide your own implementation of JTextField which will be holding the "default-text" in a field, specially created for that.
For your second question, you can set the focus to some button or frame itself.
Is there any reason that you use focusListener()? why not use mouseListener() as follow?
accNumberField.addMouseListener(new MouseAdapter()
{
#Override
public void mouseReleased(MouseEvent e)
{
accNumberField.setText("");
}
});
if you want to clear the text for the first click, you can simply use a boolean:
//outside constructor
private boolean isTextCleared = false;
//in constructor
accNumberField.addMouseListener(new MouseAdapter()
{
#Override
public void mouseReleased(MouseEvent e)
{
if (!isTextCleared)
{
accNumberField.setText("");
isTextCleared = true;
}
}
});

How can I Listen for Keyboard input without Text Field Java

I am working on a Java application and interfacing with an RFID reader that acts as a keyboard input device.
The application will be used for employee time tracking, so the employee should not see the code that his/her RFID tag contains.
Currently, the application opens a jFrame that asks the employee to scan their tag. This is where I would like to listen for the keyboard input.
All of the RFID tags are 10 digits, so I would like to use some kind of regex to detect when a card is scanned if possible.
If someone could point me in the right direction, or contribute some code I would be grateful.
Thanks in advance.
UPDATE:
I was able to read the input of the scanner by adding the following to the constructor of my JFrame.
addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent e){ System.out.print(e.getKeyChar());}
#Override
public void keyReleased(KeyEvent e) { }
#Override
public void keyTyped(KeyEvent e) { }
});
So it is now confirmed that the Reader is just standard Keyboard input.
Here is an example of what I get for a tag: 0006459027
Now, the big question is, how do I take the characters that I got, and detect that it is a 10 digit string, and from there trigger an event to open a new frame?
First, I'd see if the RFID reader is triggering an ActionEvent to be fired when the tag is scanned. This would be the simplest approach.
Failing that, you would need to attach a DocumentListener to the fields underlying document and monitor for changes.
You'll need to decide how best to interrupt the results (as you're likely to get each letter of the RFID at a time). You could monitor the length of the document or have a javax.swing.Timer which triggers after a short delay (you'd reset the timer on each update event triggered by the DocumentListener)
Check out
JTextField.addActionListener
JTextField.getDocument().addDocumentListener
I'd suggest taking a look at DocumentFilter as well, but your interested in the final result, not modifying it.
UPDATED with DocumentListener Example
// In the classes variable decleration section...
private JTextField rfidField;
// In the classes constructor or UI init method...
rfidField = new JTextField(12);
rfidField.getDocument().addDocumentListener(new DocumentListener() {
public void handleUpdate(DocumentEvent e) {
if (e.getDocument().getLength() == 10) {
System.out.println("Trigger me happy...");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
rfidField.setText(null);
}
});
}
}
#Override
public void insertUpdate(DocumentEvent e) {
handleUpdate(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
handleUpdate(e);
}
#Override
public void changedUpdate(DocumentEvent e) {
handleUpdate(e);
}
});
// Now don't forget to add the field to your forms container ;)
//////
One of things I would be do when you "trigger" the code event is, once you've read it from the text field, is clear the text field (JTextField.setText(null)) - IMHO
If the RFID reader acts as a keyboard input device, try with key events:
JFrame frame = new JFrame();
// frame setup
frame.addKeyListener(new KeyAdapter(){
public void KeyPressed(KeyEvent ke)
{
System.out.println(ke);
}
});
Otherwise you have to check which kind of event it fires.
I was in a similar situation but with a bar-code scanner.
I really worked hard on a custom DocumentListener that would take care of all scenarios, and none of it worked.
Out of desperation, I added an ActionListener and it then worked very well.
Here is a code snap-shot :
try {
txtStockItemRef.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println(txtStockItemRef.getText());
DatabaseManager.peformStockItemLookupByBarcodeRef(txtStockItemRef.getText());
}
});
} catch(Exception exc) {
LiveCityRetailTools.handleExceptionWithUserMessage(exc);
}

Text Changed event in JTextArea? How to?

I have been trying to make a text changed event handling mechanism for my JTextArea. For my purposes an event has to be fired whenever there is a change in the text of the JTextArea. I tried using the KeyListener interface and here is my code for that.
txtArea.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent arg0) {
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent arg0) {
currentText = text.getText();
if (currentText == textString)
JOptionPane.showMessageDialog(null, "Correct");
}
});
Nothing happened when the textarea's text matched the hardcoded text. How can an event changed event be made for this.
Can this objective be achieved with a PropertyChangedListener? If it can, then how?
I would get the JTextArea's Document via getDocument() (a PlainDocument actually) and use a DocumentListener to listen for changes. This way you'd capture changes from key strokes and also from copy/paste/cut events.
Not the JTextArea, but the contained document receives updates, so you need:
jTextArea.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
}
#Override
public void insertUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent arg0) {
}
});
You are comparing strings with ==
if (currentText == textString)
This will never be true. This compares if the strings are the same String object. You should use equals.
if (currentText.equals( textString) )
You might also want to check out DocumentListeners.
See also this How do I compare strings in Java?

action listening for a JFrame

I am trying to listen tab-in tab-out action for my swing gui that is made by JFrame. I have a JTextField added to the JFrame that will be getting the user clipboard whenever the window is selected so the user may tab between programs, copy some url so when back to my program, this JTextField will be populated by the copied url string.
EDIT:
I have tried this:
frame.addFocusListener(
new FocusListener() {
public void focusGained(FocusEvent e) {
url= getClipboardData();
}
#Override
public void focusLost(FocusEvent arg0) {
// TODO Auto-generated method stub
}
}
);
it doesnt work
A frame doesn't recieve a focus event. A component on the frame gets the focus event.
If you want to know when a frame gets focus then use a WindowListener and handle the windowActivated event.
What you want is a FocusListener not an ActionListener. Check out the java Doc and you'll know how to use it. It's easy.
it looks like you are not setting the clipboard data onto the text field.
frame.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
getJTextField().setText(getClipboardData());
}
public void focusLost(FocusEvent e) {
//ignored
}
});
Something like that will likely solve your problem

Categories