Ouvrez l'application JavaFX sur l'écran actif ou le moniteur dans la configuration multi écran


Je me demandais s'il existait un moyen de rendre la fenêtre d'application indépendante de la plate-forme de bureau JavaFX ouverte sur l'écran actuellement actif, Tout en travaillant sur un exemple d'application JavaFX à partir du tutoriel.

J'utilise un système à deux moniteurs et ce serait génial s'il existe un moyen d'ouvrir l'outil sur l'écran actif au lieu de l'écran principal à chaque fois.

Jusqu'à présent, j'ai pu apprendre réglage personnalisé XY emplacement sur l'écran pour ouvrir la fenêtre de l'application, mais cela utilise le primaire moniteur de bureau.

Recherche plus ou moins de centrer la fenêtre sur l'écran où le curseur de la souris est présent au moment où l'application démarre.

Mise à Jour:

C'est quelque chose qui peut être réalisé dans Windows Forms C# en définissant Form.Propriété StartPosition. Fondamentalement, dire à l'application de démarrer ou de s'ouvrir sur l'écran du bureau sur lequel l'utilisateur travaille ou regarde actuellement.

Author: Indigo, 2014-09-08

3 answers

Merci à @ galovics et @ Rafael Guillen pour les conseils 1 et 2, J'ai pu contourner ce problème.

C'est juste un essai et non la réponse finale, mais je voudrais partager le morceau de code assez fonctionnel pour donner une idée. Je l'ai testé sur Windows et Ubuntu, a plutôt bien fonctionné. Pour info, je suis encore en train d'apprendre JavaFX.

Le code ci-dessous centre ma fenêtre d'application JavaFX non re-dimensionnable sur l'écran d'affichage ou de moniteur actif à start-up.

Remarque: Cela ne fonctionne que si vous avez fixé la taille de la fenêtre prédéfinie comme dans mon cas. Sinon JavaFX calcule la taille de la fenêtre après Stage.show(), puis nous ne pouvons pas obtenir la largeur et la hauteur avant la méthode show(). Il renvoie NaN. Lisez les commentaires en classe sur la façon de l'utiliser dans ce cas.

/*
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package Window_On_ActiveScreen;

import java.awt.HeadlessException;
import java.awt.MouseInfo;
import java.awt.Point;
import java.util.List;
import javafx.geometry.Rectangle2D;
import javafx.stage.Screen;

/**
 * X-Y position of a Window on active screen at startup if more than one screen.
 * Note: This works smooth only if the outer most AnchorPane size is fixed at
 * design time. This is because, if the size is not fixed JavaFX calculates
 * Window size after Stage.show() method. If the pref size is fixed, then use
 * this class in WindowEvent.WINDOW_SHOWING event, or if the pref size is set to
 * USE_COMPUTED_SIZE then use it in WindowEvent.WINDOW_SHOWN event (this will
 * give a quick splash Window though). Feel free to improve and share this code.
 * I am new to JavaFX so tired what I know so far. Tested on Windows but need
 * more attention to Linux and Mac
 *
 * @author
 */
public class StartUpLocation {

    private double xPos = 0;
    private double yPos = 0;

    /**
     * Get Top Left X and Y Positions for a Window to centre it on the
     * currently active screen at application startup
     * @param windowWidth - Window Width
     * @param windowHeight - Window Height
     */
    public StartUpLocation(double windowWidth, double windowHeight) {
        // Get X Y of start-up location on Active Screen
        // simple_JavaFX_App
        try {
            // Get current mouse location, could return null if mouse is moving Super-Man fast
            Point p = MouseInfo.getPointerInfo().getLocation();
            // Get list of available screens
            List<Screen> screens = Screen.getScreens();
            if (p != null && screens != null && screens.size() > 1) {
                // Screen bounds as rectangle
                Rectangle2D screenBounds;
                // Go through each screen to see if the mouse is currently on that screen
                for (Screen screen : screens) {
                    screenBounds = screen.getVisualBounds();
                    // Trying to compute Left Top X-Y position for the Application Window
                    // If the Point p is in the Bounds
                    if (screenBounds.contains(p.x, p.y)) {
                        // Fixed Size Window Width and Height
                        xPos = screenBounds.getMinX() + ((screenBounds.getMaxX() - screenBounds.getMinX() - windowWidth) / 2);
                        yPos = screenBounds.getMinY() + ((screenBounds.getMaxY() - screenBounds.getMinY() - windowHeight) / 2);
                        return;
                    }
                }
            }
        } catch (HeadlessException headlessException) {
            // Catch and report exceptions
            headlessException.printStackTrace();
        }
    }

    /**
     * @return the top left X Position of Window on Active Screen
     */
    public double getXPos() {
        return xPos;
    }

    /**
     * @return the top left Y Position of Window on Active Screen
     */
    public double getYPos() {
        return yPos;
    }
}

Maintenant, définissez Stage avec ces positions X et Y sinon zéro ou simplement définissez centerOnScreen Il est important de vérifier cela ici car si la souris se déplace trop vite, le point p peut revenir null, de même que le reste des calculs ou en cas d'exception.

    // If Outer most AnchorPane pref size is fixed then use it in this event
    // Else otherwise use the handleWindowShownEvent(WindowEvent event) 
    public void handleWindowShowingEvent(WindowEvent event) {
        Stage stage = (Stage) event.getSource();
        // Get X Y of start-up location on Active Screen
        StartUpLocation startUpLoc = new StartUpLocation(mainWindowAnchorPane.getPrefWidth(), mainWindowAnchorPane.getPrefHeight());
        double xPos = startUpLoc.getXPos();
        double yPos = startUpLoc.getYPos();
        // Set Only if X and Y are not zero and were computed correctly
        if (xPos != 0 && yPos != 0) {
            stage.setX(xPos);
            stage.setY(yPos);
        } else {
            stage.centerOnScreen();
        }
    }

N'hésitez pas à suggérer des améliorations ou des erreurs ici.

Update: Ajouté en tant que méthode générique dans une classe.

 2
Author: Indigo, 2017-05-23 12:24:00

Je pense qu'il n'y a pas un tel outil pour le faire. Cependant, vous pouvez créer une application qui détermine où se trouve la souris, puis cette application doit démarrer l'application JavaFX et transmettre les paramètres de la souris.

Dans l'application JavaFX, il vous suffit de traiter les paramètres et de définir votre fenêtre à la bonne position.

 1
Author: galovics, 2014-09-07 21:03:28

Comme @ galovics dit que vous pouvez déterminer la position de la souris avant d'afficher la scène, vérifiez ceci: http://docs.oracle.com/javafx/2/api/javafx/stage/Screen.html https://community.oracle.com/thread/2390272?tstart=0 J'espère que cela aide

 1
Author: Rafael Guillen, 2014-09-08 12:42:36