B4J Question [Solved] Menu Shortcut Problem with Function Keys and Textfield

specci48

Well-Known Member
Licensed User
Longtime User
I got in some trouble using function keys as a menu shortcut.
I reduced the problem to the attached sample.

If the views on the left side have the focus, pressing Ctrl+S or F12 for the two sample menu entries work like a charm.
If I set the focus on the textfield, only Ctrl+S activates the sample entry 2. By pressing F12 for the first sample entry... nothing happens.

How do I prevent the textfield from catching the function key so the menu entry can be activated with F12 even if a textfield has the focus?

specci48
 

Attachments

  • ShortcutProblem.zip
    2.7 KB · Views: 255

Daestrum

Expert
Licensed User
Longtime User
Textfields normally ignore (some) unprintable characters, you can force it to tell you if any key is pressed.
It requires a bit of pure java, as you have to interrupt the usual event dispatch chain.

(Not for the faint hearted)

You need to call the code like this
B4X:
' in globals
dim inline as JavaObject
...

' in AppStart
inline = Me
...
'call this before you start using the field
' the field must be in the globals ie Dim TextField1 as TextField
 inline.RunMethod("setDispatcher",Array(TextField1))
...

The actual java code
B4X:
#if java
import javafx.event.*;
import javafx.scene.Node;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import java.lang.Exception.*;

static EventDispatcher initial = null;
public static void setDispatcher(Node n){
    initial = n.getEventDispatcher();  
    n.setEventDispatcher(new EventDispatcher() {
        @Override
        public Event dispatchEvent(Event event, EventDispatchChain tail) {
            if (event instanceof KeyEvent) {
                KeyEvent keyEvent = (KeyEvent)event;
                if (keyEvent.getEventType() == KeyEvent.KEY_PRESSED){
                    if (keyEvent.getCode() == KeyCode.F12) {
                        try{
                            _mnusampleentry1_action(); // calls your function here for F12
                        }catch (Exception ure){
                            System.out.println("Broke it");
                        }
                    event.consume();
                    }
                    if (keyEvent.getCode() == KeyCode.S && keyEvent.isControlDown()){
                        try{
                            _mnusampleentry2_action(); // calls your function here for ctrl S
                        }catch (Exception ure){
                            System.out.println("Broke it");
                        }
                    event.consume();
                    }
                }
            }
        return initial.dispatchEvent(event, tail);
        }
    });
}
#end if

Hope this helps :)
 
Last edited:
Upvote 0
Top