views:

24

answers:

1

Hi,

I want to have a JTextField (or another text-like input which supports focus and a cursor -- or maybe I should code my own?) where I want to have full control over the immediate input. I.e. I want to ignore most inputs and handle the rest specifically. It seems that JFormattedTextField is not what I want because it does the verification not on the immediate input but when the focus is lost.

I tried to add a key listener but it's a bit non-obvious how I should use it. It seems I can catch up events like cursor changes (via keys) or copy/paste (via key-shortcuts) in keyPressed and I can catch all normal key input in keyTyped. I am not sure how I can catch cursor changes or copy/paste made via mouse (for some reason, right click does not work anyway, so copy/paste via mouse in the context menu seems not possible but I am not sure if that might be a different issue or if it should work and just does not for some reason).

I basically want something like the following handler:

interface InputHandler {
   void addStringAt(int pos, String s);
   void deleteSubString(int pos, int len);
   void setFocusTo(int pos);
}

And it should be absolutely impossible for the user to get any stuff onto the textbox which are not going through this handler.

Right now, it seems like I have to take care about a lot of specific cases (like on some architectures, there may be some context menu where they could copy/paste or input something, handle all mouse events manually, etc).

Or the other way, which also involves a lot of special handlings: To recode such input field myself. This still seems saver because I can know for sure that there are no tricky methods how the user could bypass the handler (and I really must know that for sure). Btw., how would I do this? I thought of extending a JLabel. How can I extend it so that it can get a focus?

I wonder how you would implement something like this.

+1  A: 

It sounds like you need a DocumentFilter. A couple of existing questions that will help with this:

Ash