I have a JTextField bean on a form which is set to be editable. It is ok until I call a method to assign a listener to the field.
var listener = new java.awt.event.KeyListener({keyTyped: globals.getKeyTyped()});
elements.bean_text.addKeyListener(listener);
After this code is executed the cursor is still blinking in the field but I’m unable to type anything.
The code seemed to work fine yesterday but I’ve been playing with it and did not save the working version (though I think it was the same).
Remember to always dispose of your java listeners!
Especially in case of KeyListener since they can eat some memory and slow down your app significantly if you attach your listener more than once (it’s so easy to do, especially in developer where you launch and stop your client repeatedly)…
To avoid this pitfall, I usually do the following:
First, initialize the listener inside a form variable in the Form “onLoad” like this:
var listener = {}; // this is to tell Servoy that the "listener" var is an Object, otherwise you will get cast exceptions...
function onLoad() {
var listener = new java.awt.event.KeyListener({keyTyped: globals.getKeyTyped});
}
then when I want to attach it, I put:
// remove first, if the listener wasn't already attached, this will do nothing:
elements.bean_text.removeKeyListener(listener);
// now I can attach my listener:
elements.bean_text.addKeyListener(listener);
And of course in the form “onUnload”, release the resources:
// remove:
elements.bean_text.removeKeyListener(listener);
// and release:
listener = null;
As far as I know the only argument that is accepted by getKeyTyped() is the keyboard event but I might be unaware of something.
What would you pass as arguments?
Actually, i was poking around with a mouse listener. I wanted to pass on the source element on which the mouse had entered. But, I found out that reading the first argument (no matter if you didn’t pass on any arguments) already gives the source element!
Kaptan:
Actually, i was poking around with a mouse listener. I wanted to pass on the source element on which the mouse had entered. But, I found out that reading the first argument (no matter if you didn’t pass on any arguments) already gives the source element!
Um…
I can’t figure out the name of the calling element arguments[0].source returns a java object javax.swing.plaf.basic.BasicComboBoxEditor$BorderlessTextField
But arguments[0].source.name is null, though the bean on the form (JComboBox) definitely has got a name.