tags:

views:

222

answers:

2

What is the best way to post a Button Press to a component? I tried using the Robot class and it works, normally. However, this class has some problems under some Linux platforms, so I wonder what is the best Java-only way to post an event to a component.

In this particular case, I want to post backspace events to a JTextField when I press a button.

EDIT: I've used the Robot class after all. I fixed the problem that prevented this class from working correctly under Linux

+1  A: 

You can find example of such key post event, like in this class

Those posts are using the dispatchEvent() function

public void mousePressed(MouseEvent event) {
    KeyboardButton key = getKey(event.getX(), event.getY());

[...]

      KeyEvent ke;
      Component source = Component.getFocusComponent();
      lastPressed = key;
      lastSource = source;
      key.setPressed(true);

      if(source != null) {

        if((key == k_accent || key == k_circle) && (lastKey instanceof KeyboardButtonTextJapanese)) {
          int accent = ((KeyboardButtonTextJapanese)lastKey).getAccent();
          if(accent >= 1 && key == k_accent) {

            /*
            ** First send a backspace to delete the previous character, then send the character with the accent.
            */

            source.dispatchEvent(new KeyEvent(source, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, k_backspace.getKeyEvent(), k_backspace.getKeyChar()));
            source.dispatchEvent(new KeyEvent(source, KeyEvent.KEY_TYPED,   System.currentTimeMillis(), 0, k_backspace.getKeyEvent(), k_backspace.getKeyChar()));
VonC
That is a nice library you pointed me to. I've been ripping some pages off their book ;)
Mario Ortegón
A: 

I ended up using the robot class, which was the easiest way after all. The problem is that in the specific Linux distro I was using, the instantiation of the Robot class would hang the Virtual Machine. Looking at the log files I found out that java was trying to load a DLL that wasn't available:

libXi.so.6

After adding this library to the distro I was able to continue

Mario Ortegón