events,javafx,frameworks,mouselistener , JavaFX application, framework to relay data from a nativeMouseListener to JavaFX


JavaFX application, framework to relay data from a nativeMouseListener to JavaFX

Question:

Tag: events,javafx,frameworks,mouselistener

I'm making a JavaFX application and I want to do the following.

I present a couple buttons, when they are pressed, the GUI will minimize and waits for a mouseClick from the JNativeHook library. When a mouse is clicked it's x,y coordinats needs to be relayed back to the javaFx controller, the GUI maximizes and represents the data in the gui and gives me the possibility to do also other stuff with it.

I've got this behaviour working for one button but it is not good at all. My current implementation won't work if I want more buttons as you will see below and it would need alot of duplicate code, where I need to make a specific mouseListener and method in the layoutController for each button (aside from the buttonHandlers). I obviously do not want this, basicly I'm searching for a little framework to let the next NativeMouseEvent relay data in my buttonHandle method in the controller

This is what I got, the JavaFX layoutController with the button, has the following handle

@FXML
private void handleGetPos() {
    try {
        mouseManager.startMousePosChecker(cntrl);
        mainGUI.minimizeGUI();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

The layoutController passes itself as cntrl to my mouseManager, the manager just (un)registers a nativeHook to GlobalScreen and adds a new mouseListener to it and passes the layoutController cntrl with it. (passing the controller to it is also stupid if I want to use it another layoutControllers, since they are not the same type)

    GlobalMouseListener mouseListener = new GlobalMouseListener();
    mouseListener.setLayoutController(cntrl);                       
    GlobalScreen.getInstance().addNativeMouseListener(mouseListener);

In the mouseListener this happends:

public void nativeMouseClicked(NativeMouseEvent e) {
    Platform.runLater(() -> {
        cntrl.setMousePos(ConvTypes.toStr(e.getX()), ConvTypes.toStr(e.getY()), e.getX(), e.getY() );
    });
}

This is ugly, when the events happens it passes the x,y coordinates as strings to a specific method in my layoutController:

public void setMousePos(String sX, String sY, int x, int y) {
    xPos.setText(sX);
    yPos.setText(sY);
    mainGUI.maximizeGUI();
    mouseManager.stopMousePosChecker();
    //other stuff

Obviously this implementation is not going to work for multiple buttons. Therefore I would like to build a little framework with mouseManager. Which registers/unregisters the nativeHook and makes only one mouseListener, which returns data to the mouseManager. This mouseManager then gives the necessary data to anyone who needs it. If I'm correct this sounds like a custom Event class? (Tried to make one but I have no idea how to implement it my layoutController or how to wrap it around the globalMouseEvents)

Anyway I think it would become something like this or maybe something with a lambda? (Note I actually have no idea):

     @FXML
     private void handleButton() {
         xPos.setText(mouseManager<MouseEvent>() {
         @Override
         public void handle(MouseEvent e) {
              //necessery stuff goes here

So yes I have no idea how to get started on how to get that data to return in any buttonHandle() method or any method actually. I know my current code is bad and I want to make it better and reuse code instead of duplicate code, but this problem is currently breaking my head...

It is a long post, thanks for reading and helping!


Answer:

Not sure I completely understand, but can you do something like this:

import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseListener;
import org.jnativehook.GlobalScreen;


import javafx.scene.input.MouseEvent ;
import javafx.application.Platform ;
import javafx.event.EventType ;
import javafx.geometry.Point2D ;
import javafx.beans.property.ReadOnlyObjectWrapper ;
import javafx.beans.property.ReadOnlyObjectProperty ;

public class GlobalMouseListener implements NativeMouseListener {
    private final EventType<MouseEvent> eventType ;
    private final ReadOnlyObjectWrapper<Point2D> mouseLocation = new ReadOnlyObjectWrapper<>();

    /**
      * @param eventType The type of event to listen for. Should be one of
      * MouseEvent.MOUSE_CLICKED, MouseEvent.MOUSE_PRESSED, or MouseEvent.MOUSE_RELEASED.
      * The mouseLocationProperty() will be updated if a global mouse event
      * matching the semantic type of the provided eventType occurs.
      */

    public GlobalMouseListener(EventType<MouseEvent> eventType) {
        this.eventType = eventType ;
        GlobalScreen.addNativeMouseListener(this);
    }

    public ReadOnlyObjectProperty<Point2D> mouseLocationProperty() {
        return mouseLocation.getReadOnlyProperty() ;
    }

    public final Point2D getMouseLocation() {
        return mouseLocationProperty().get();
    }

    @Override
    public void nativeMouseClicked(NativeMouseEvent e) {
        if (eventType == MouseEvent.MOUSE_CLICKED) {
            Platform.runLater(() -> mouseLocation.set(new Point2D(e.getX(), e.getY())));
        }
    }

    @Override
    public void nativeMousePressed(NativeMouseEvent e) {
        if (eventType == MouseEvent.MOUSE_PRESSED) {
            Platform.runLater(() -> mouseLocation.set(new Point2D(e.getX(), e.getY())));
        }
    }    

    @Override
    public void nativeMouseReleased(NativeMouseEvent e) {
        if (eventType == MouseEvent.MOUSE_RELEASED) {
            Platform.runLater(() -> mouseLocation.set(new Point2D(e.getX(), e.getY())));
        }
    }

    public void cleanup() {
        GlobalScreen.removeNativeMouseListener(this);
    }
}

Then your button handler just needs

@FXML
public void handleGetPos() {
    GlobalMouseListener gml = new GlobalMouseListener(MouseEvent.MOUSE_CLICKED);
    gml.mouseLocationProperty().addListener((obs, oldLocation, newLocation) -> {
        double x = newLocation.getX();
        double y = newLocation.getY();
        gml.cleanup();
        // restore window and process x, y...
    });
    mainGUI.minimizeGUI();
}

If you really want to minimize the boilerplate code, you can define

private void processMouseLocation(BiConsumer<Double, Double> pointProcessor) {
    GlobalMouseListener gml = new GlobalMouseListener(MouseEvent.MOUSE_CLICKED);
    gml.mouseLocationProperty().addListener((obs, oldLocation, newLocation) -> {
        double x = newLocation.getX();
        double y = newLocation.getY();
        gml.cleanup();
        // restore window...
        pointProcessor.accept(x, y);
    });
    mainGUI.minimizeGUI();
}

and then each of your button handlers just reduce to

@FXML
public void handleGetPos() {
    processMouseLocation((x, y) -> {
        // code to handle mouse press at x,y...
    });
}

That's all untested (both compiling and running, I just typed it in here) but I think it should be enough to get you started. The point is you just expose a property for the mouse location, and listen to it from each button handler, executing the button-specific code when it changes. Your native mouse listener just has to update the property when the relevant event occurs; it doesn't need a reference to the controller, etc.


Related:


JavaFX8 : Single Controller for 1+1popup scene (Solved)


java,javafx,fxml
After following the tutorial at http://www.javafxtutorials.com/tutorials/switching-to-different-screens-in-javafx-and-fxml/, I have a functioning popup window, however, I am having difficulty figuring out how to interact with it with a controller. From the tutorial, I got the impression that there is to be a shared controller between the two FXML files, but I'm having...

Chart JavaFX, my hover Label are hidden by the edges of chart


charts,javafx,popup,linechart
I have a problem again with the JavaFX Chart : D Context : I had Popup/Label on my chart to display the value on hover : JavaFX LineChart Hover Values (Jewelsea answer) Problem : But when the point are near the edges of chart, the popup is hidden by them....

How do you start a function at a certain time in Python?


python,multithreading,events,time,condition
I have a list of timestamps, and I need to call a specific method when those timestamps are reached. Those timestamps are roughly 20ms apart. At the moment I am using busy waiting in a separate thread, but I am worried about the CPU overload. Example : while True: if...

JavaFX - how to get background color of Tab, Button, etc


java,animation,colors,javafx,background
Problem description: I can't get background of object in JavaFX. I don't mean Shapes, but normal Nodes like Buttons, Tabs and others. I don't know how to access to theirs background color. What I want? I am developing IDE and I want to run Color animation on tab with file...

How to change the color of treeitem expand and collapse arrow in javafx?


javafx,treeview
I have got some trouble with treeitems of a treeview. There are expand and collapse icon-arrows, when you have child-treeitems. I only know how to change the background-color of this expand/collapse icons. But I don't know how to change the color of the arrow. .tree-cell .tree-disclosure-node { -fx-background-color: #CCCCCC; }...

Windows Phone: how to handle an event from a web page in a WebView?


events,webview,event-handling,windows-phone,handler
Which callback/delegate is the one to intercept the event of a user clicking on a link within a WebView? I'd want that URL. I just need to know if it is possible and how should I do in some way.

UI4J - Get the entire document innerhtml


java,javafx,ui4j
Is there a way to get the innerhtml for the entire page, including html, head, body and so on. I am only able to call page.getDocument().getBody().getInnerHTML() ... there is no page.getDocument().getInnerHTML() ... shouldn't there be ?...

JavaFX subclassed Button - How to make Label update work?


java,javafx
I want to have several JavaFX Buttons that update one Label in my Application with text. For testing purposes it's just Button Text. What I did at first worked fine and looked like this: String Text = "..."; public void kons() { System.out.println("Works..."); System.out.println(Text); Tekst.setText(Text); Button G4 = new Button("Spadantes");...

Javafx Tableview dont show data of ObservableList


user-interface,javafx
i have a Problem mit the Tableview in JavaFX. I know there are some other posts in the forum, but i checked them and tried to use the solutions, but nothing work for me ... I have 3 Classes. One Version class, the data model. The Class which populats the...

JavaFx TreeCell how to expand nodes after one second


javafx,nodes,expand,treecell
i'm implementing the Drag&Drop on a generic TreeView. My purpose is to expand a folder during DragEntered event after a second of stationing, actual code: setOnDragEntered(e -> { TreeItem<TreeItemContent> enteredItem = getSourceItem(e); if(model.isFolder(enteredItem)){ enteredItem.setGraphic(images.getFolderOpened()); enteredItem.setExpanded(true); } e.consume(); }); desired: setOnDragEntered(e -> { TreeItem<TreeItemContent> enteredItem = getSourceItem(e); if(model.isFolder(enteredItem)){ if(dragDuration >= 1...

How is the Point2D “angle” method to be understood?


javafx,geometry
I thought I'd use the Point2D class for calculating e. g. the angle betwen 2 points instead of creating a utility method. It turned out, it's not usable at all. Code example: Point2D p1; Point2D p2; p1 = new Point2D(0, 0); p2 = new Point2D(10, 10); System.out.println( "Point2D: " +...

How to accomplish 3 horizontal line menu in fxml


menu,javafx,overlay,fxml
I want to create menu like "Firefox (Three horizontal line - top right side) Menu". I don't know how to create this line of overlay menu in FXML. Have anybody any idea about this? Thank a lot....

Using framework event dispatcher to raise domain event


php,events,laravel,domain-driven-design,dispatcher
When i need to raise domain events, should i use framework specific Event Dispatcher or create my own Event Dispatcher that implemented by framework event dispatcher ? Since the framework has a really nice event dispatcher and the term of DDD said the domain layer should not dependent on any...

Opening frame that is under the JavaFX program category


eclipse,video,javafx,jframe,mp4
Most of program is using JFrames throughout the application for all the different windows that can appear. However, I have to play an instructional video for the user inside a JFrame. I couldn't find a way to do this, so I had to make a JavaFX program. Is there a...

ActionScript: How to listen for an event from a different XML


actionscript-3,events,flash-builder,mxml
I have a popup screen in which the player enters their name and clicks OK. When OK is clicked I want the player's name to be passed to the main XML. How can I do this? Here is the function in the main XML that handles the popup: private function...

Google map infowindow position


javascript,google-maps,events,infowindow
Here is a sample google map with three polygons. I am setting the infowindow for each polygon as, for (var i in coordinates) { arr = []; for (var j=0; j < coordinates[i].length; j++) { arr.push( new google.maps.LatLng( parseFloat(coordinates[i][j][0]), parseFloat(coordinates[i][j][1]) )); bounds.extend(arr[arr.length-1]) } // Construct the polygon. polygons.push(new google.maps.Polygon({ paths:...

How to analyze incoming message (JavaFX on Android)


java,javafx,javafx-2,javafx-8,javafxports
I ported my JavaFX application to my Android device. I want my application to read incoming SMS messages and store it in a database. I found several questions here in StackOverflow but I don't know how to implement in a JavaFX approach. Please help!

Load all user controls of a form on start


c#,winforms,events,user-controls
My Winform application has a main form with a tab control. In each tab there is a User Control. And each user control has Controls (such as DataGridViews, etc) that are loaded on the Load event of the user control. The problem I have is that I would like to...

How to identify web actions in JavaFX webview?


javascript,webview,javafx
I need to catch the actions like clicks, drag, right-click, double click etc, that are done by the user on JavaFX web view. How to achieve it?

Javafx TextField pseudoClassStateChanged method not working


java,javafx
I'm setting PseudoClass to TextField to highlight them when error occurs. The red border appears around TextField only when I click mouse inside it (to put text value), but I need to show border all time. there is how I sets border: element.pseudoClassStateChanged(PseudoClass.getPseudoClass("error"), true); It worked just fine till last...

Angularjs $watchCollection on $rootScope not triggered when values updated from directive


javascript,angularjs,events,angularjs-directive,angularjs-watch
I'm running into a bit of an issue solving a problem with some Angularjs functionality I'm working on. The basic idea is that I have a system where certain criteria must be met before the user is allowed to advance to the next section of the app. One example of...

JavaFX TextField : Automatically transform text to uppercase


java,javafx,fxml,keyevent
I have a JavaFX TextField control on my FXMl that looks like this... <TextField fx:id="input_search" onKeyPressed="#keyListener" prefHeight="25.0" prefWidth="197.0" /> I want to automatically change all characters to uppercase when the user is typing. The code in my controller : public void keyListener(KeyEvent event){ //maybe transform the pressed key to uppercase...

Multi-Threading error when binding a StringProperty


java,multithreading,javafx,javafx-8
I have a question about multi-threading and the binding of a StringProperty. I have a class CacheManager, which contains a Thread which updates my cache with the changes on the server. Now, I want to notify the user with a text and percentage of the progress (which are a Label...

Return a value created in an event handler inside a function from the same function


javascript,jquery,events
I have an input box and a go button. When the user clicks the go button I want to compare the inserted value with another value. I am trying to acquire the input value inside a function like so function getInput(){ var entry =''; $('button.go').on('click',function(){ var entry = $(this).siblings('.input').val(); //return...

FX - Suggestions for aligning CheckBox in Grid


java,checkbox,javafx,grid,alignment
Converting from Swing to FX here. We have some CheckBoxes where the Label appears on the left side of the CheckBox. We are accomplishing this by calling setNodeOrientation(NodeOrientation.RIGHT_TO_LEFT); The problem is that in some GridPanes, we'll have a Label in column 0 with a Node in column 1 on row...

function wait to execute


matlab,events,delay
In Matlab functions can be started at events,but occasionally, like with the resize function, the events are called in rapid order and the function is called many times in succession, which can cause weird behavior and lag. Is there a way to have it listen for the event but only...

JavaFX FilteredList, filtering based on property of items in the list


javafx,javafx-8
I have a case where I need to filter a ObservableList<Item> based on some properties of the items (i.e. the condition is internal and not external). I found out that javafx has FilteredList so I tried it. I could set the predicate and filtering works, until the property value that...

VBA - Trapping events on dynamically created Textbox


excel,vba,excel-vba,events,userform
I am writing a VBA application in Excel. I have a Userform that dynamically builds itself based upon the data contained in one of the worksheets. All of the code that creates the various comboboxes, textboxes and labels is working. I created a class module to trap OnChange events for...

Singleton events


c#,events,design
I am refactoring some old code, where I have a lot of static events like this public static event Action Updated; public static void OnUpdated() { if (Updated != null) Updated(); } I found out what using lazy singletons is often better than using static classes: no memory is consumed...

Getting a mouse position with JavaFX and Event


java,javafx
I'm trying to get the position of a mouse click in my JavaFX application. I have an EventHandler as so: EventHandler<Event> mouseHandler = new EventHandler<Event>() { @Override public void handle(Event event) { String eType = event.getEventType().toString(); if(eType.equals("MOUSE_PRESSED")){ //mouse position } } }; which is called on mouse press, release and...

jQuery event.preventDefault() don't work unless debugging


javascript,jquery,events,javascript-events,event-handling
I am trying to use this approach in order to convert GET parameters to POST. I also want the anchor to be properly handled even if the middle mouse button is clicked. This is how I did the the event handlers binding: $(document).ready(function () { $(".post").each(function(){ $(this).mousedown(function(evt){ switch(evt.which){ case 1:...

How to detect when a specific window is closed in java


java,events,window,action,windowlistener
I'm pretty new to Java and I've tried looking this up but couldn't really find any thing that helped. I'm wondering how I could detect when a specific window is closed? I've been using windowClosing() but this applies to any window that is closed, and so the event that I...

How would I connect to a MySQL database back-end from an Android device's application? [closed]


java,android,mysql,javafx,apk
I have developed a standalone JavaFx application in Netbeans with a MySQL database back-end which I want to also package as an APK package for running on Android. How would I go about porting the MySQL database script it uses to Android?

How to code a arrival generator with a varying intensity rate


events,simulation,stochastic
This is for a simulation model: Most questions I've come about deal with how to code an generator with exponential arrival times. But I'm currently stuck on how to program a generator where the arrival rate can change within a discrete event simulation. In particular I'm stuck with the following...

How to change ImageView on KeyPressed


javafx
I am having difficulty trying to solve this, I am currently trying to figure out how to change the ImageView to another ImageView when I press a certain Key on my keyboard but I have no idea how to, I have already looked around almost everywhere I can think of...

FXML: ClassNotFoundException


javafx,fxml,fxmlloader
I'm very new to JavaFX and I'm having problem using my custom class in FXML. The console keeps giving me this exception when trying to load main.fxml: ... 1 more Caused by: java.lang.ClassNotFoundException: sample.View$BoardPane at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ... I created BoardPane class as a subclass of FlowPane in package sample.View and...

password check directive elem.add error


javascript,angularjs,validation,events,angularjs-directive
I'm making a password checking directive to ensure password and confirm_password fields are the same: angular .module('myModule') .directive('pwCheck', function() { return { require: 'ngModel', link: function (scope, elem, attrs, ctrl) { var password = "#" + attrs.pwCheck; elem.add(password).on('keyup', function() { scope.$apply(function () { ctrl.$setValidity('pwmatch', elem.val() === $(password).val()); }); }); }...

JavaFX splash screen message and progress not updating


java,multithreading,javafx
I have a JavaFX application that checks for the presence of a database at startup. If the database is not found, a "seed" database must be created before the program can proceed. Since creating the seed database can be lengthy, I want to display a splash screen and show progress...

FXML file won't load even when file path is correct


java,eclipse,javafx
I am trying to load an FXML file: URL url = getClass().getClassLoader().getResource("/frontEnd/fxml/ModeScreen.fxml"); try { this.value = FXMLLoader.load(url); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } But when I run, I get: NullPointerException: Location is required the path to my fxml file is: src/frontEnd/fxml/ModeScreen.fxml and the path...

Dependencies in forms Symfony2


php,forms,symfony2,events,entities
I'm working on a webapplication in Symfony2. I came to a point in which I need some advice/explanation from some one more advanced in Symfony. I have a part of my database that is set up as follows: I have cards that belong to a card attribute set and consists...

wait for an event regulary


multithreading,events
In a program I need to wait for an event (keypress) and get it's char. after that program will continue. this progress will Repeat several time. in my first try, codes run and any character did not save. I find out I should use threading but I am not Familiar...

Filter JDK Bug System by JavaFX


java,javafx,openjdk
Is there a way (filter settings, etc) to see only JavaFX related bugs in the JDK Bug System? Also, the Reporter names seem to be gone. Now I'm "J. Duke", I guess like everyone else that doesn't have an acount there. So how do I find the bugs I reported?...

Should all Objects that register events be IDisposable


c#,events,event-handling,destructor,idisposable
As per my understanding when an Object is no longer required it is best practice to unsubscribe all event handlers in any Objects that subscribes to events. This is done to avoid handling an event within an Object when the given Object may reside in a invalid state (no doubt...

Difference between Pane and Group


javafx,group,pane
My question is simple : in JavaFX, what is the difference between a Pane and a Group ? I can't make any difference ... Thank for your answer...

How to make a Javafx Image Crop App


java,image,canvas,graphics,javafx
I am building an application for my colleagues to crop image. I use FXML with Scene Builder to build the GUI. The user click a button to choose a image from his computer. Then, the image is shown in the GUI. User can zoom and move in the pane. At...

Component event detection in Delphi


delphi,events,components
I am developing a DataAware component and executing some code after the database is open. This is the code I have at the moment: TMyDataAwareComponent = class(TDataAwareComponent) private { Private declarations } procedure ToBeExecutedOnAfterOpen(DataSet: TDataSet); protected { Protected declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; end;...

Error in reading Ubuntu 14.04 mouse event file (/dev/input/event3) with java programmig


java,events,ubuntu,terminal,mouse
I want to handle mouse event in Linux terminal via java programming. I wrote two program via c++ and java that they do same process. when i use c++ programming to open and read file ("/dev/input/event3"-mouse event file), there is no problem while running executable file. (Ubuntu 14.04 terminal and...

Rotate line segment with Button


math,javafx,geometry,coordinates
I have a line which has points (x1,y1) and (x2,y2). I wanted to attach a Button to it, it should align with the line by rotating based on the line segment points. I need some help in calculating the rotation angle for the Button.

What is wrong with this JavaFX/FXML custom component?


java,javafx,javafx-8,fxml,fxmlloader
I am learning to write FXML custom components for use with JavaFX 8 and Scene Builder. I wrote the FXML file shown below but Scene Builder will not open it, giving me the message "Open operation has failed" due to the exception: java.io.IOException: javafx.fxml.LoadException: mycustomcomponent.TicoTeco is not a valid type....

JavaFX : Button never sets a graphic


java,javafx,controller
EDIT : A MCVE version of my code has been made to help debug it. It reproduces my bug. The purpose of my code is doing a Memory game. Which means that when it is your turn, you "open" a card, then another one. If they form a pair, they...