Comment centrer une fenêtre en Java?


Quel est le moyen le plus simple de centrer un java.awt.Window, comme un JFrame ou un JDialog?

Author: user1050755, 2008-09-28

14 answers

De blog.codebeach.com/2008/02/center-dialog-box-frame-or-window-in.html {[2] }( maintenant mort)

Si vous utilisez Java 1.4 ou plus récent, vous pouvez utiliser la méthode simple setLocationRelativeTo (null) sur le boîte de dialogue, cadre ou fenêtre au centre il.

 216
Author: Andrew Swan, 2015-11-17 20:28:17

Cela devrait fonctionner dans toutes les versions de Java

public static void centreWindow(Window frame) {
    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
    int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
    frame.setLocation(x, y);
}
 61
Author: Dónal, 2008-09-28 15:51:49

Notez que setLocationRelativeTo(null) et Tookit.getDefaultToolkit().Les techniques getScreenSize () ne fonctionnent que pour le moniteur principal. Si vous êtes dans un environnement multi-moniteurs, vous devrez peut-être obtenir des informations sur le moniteur spécifique sur lequel se trouve la fenêtre avant de faire ce type de calcul.

Parfois important, parfois non...

Voir GraphicsEnvironment javadocs pour plus d'informations sur la façon de l'obtenir.

 24
Author: Kevin Day, 2018-05-22 18:40:00

SetLocationRelativeTo(null) doit être appelé après avoir utilisé setSize(x,y) ou utilisé pack().

 22
Author: Dzmitry Sevkovich, 2013-05-01 22:06:39

Sous Linux le code

    setLocationRelativeTo(null)

Mettez ma fenêtre à un emplacement aléatoire à chaque fois que je l'ai lancée, dans un environnement multi-affichage. Et le code

    setLocation((Toolkit.getDefaultToolkit().getScreenSize().width  - getSize().width) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height - getSize().height) / 2);

"couper" la fenêtre en deux en la plaçant au centre exact, qui est entre mes deux affichages. J'ai utilisé la méthode suivante pour le centrer:

private void setWindowPosition(JFrame window, int screen)
{        
    GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] allDevices = env.getScreenDevices();
    int topLeftX, topLeftY, screenX, screenY, windowPosX, windowPosY;

    if (screen < allDevices.length && screen > -1)
    {
        topLeftX = allDevices[screen].getDefaultConfiguration().getBounds().x;
        topLeftY = allDevices[screen].getDefaultConfiguration().getBounds().y;

        screenX  = allDevices[screen].getDefaultConfiguration().getBounds().width;
        screenY  = allDevices[screen].getDefaultConfiguration().getBounds().height;
    }
    else
    {
        topLeftX = allDevices[0].getDefaultConfiguration().getBounds().x;
        topLeftY = allDevices[0].getDefaultConfiguration().getBounds().y;

        screenX  = allDevices[0].getDefaultConfiguration().getBounds().width;
        screenY  = allDevices[0].getDefaultConfiguration().getBounds().height;
    }

    windowPosX = ((screenX - window.getWidth())  / 2) + topLeftX;
    windowPosY = ((screenY - window.getHeight()) / 2) + topLeftY;

    window.setLocation(windowPosX, windowPosY);
}

Fait apparaître la fenêtre au centre du premier affichage. Ce n'est probablement pas la solution la plus simple.

Fonctionne correctement sur Linux, Windows et Mac.

 14
Author: Peter Szabo, 2013-11-14 18:16:35

J'ai finalement obtenu ce tas de codes pour fonctionner dans NetBeans en utilisant des formulaires GUI Swing afin de centrer le jFrame principal:

package my.SampleUIdemo;
import java.awt.*;

public class classSampleUIdemo extends javax.swing.JFrame {
    /// 
    public classSampleUIdemo() {
        initComponents();
        CenteredFrame(this);  // <--- Here ya go.
    }
    // ...
    // void main() and other public method declarations here...

    ///  modular approach
    public void CenteredFrame(javax.swing.JFrame objFrame){
        Dimension objDimension = Toolkit.getDefaultToolkit().getScreenSize();
        int iCoordX = (objDimension.width - objFrame.getWidth()) / 2;
        int iCoordY = (objDimension.height - objFrame.getHeight()) / 2;
        objFrame.setLocation(iCoordX, iCoordY); 
    } 

}

OU

package my.SampleUIdemo;
import java.awt.*;

public class classSampleUIdemo extends javax.swing.JFrame {
        /// 
        public classSampleUIdemo() {
            initComponents(); 
            //------>> Insert your code here to center main jFrame.
            Dimension objDimension = Toolkit.getDefaultToolkit().getScreenSize();
            int iCoordX = (objDimension.width - this.getWidth()) / 2;
            int iCoordY = (objDimension.height - this.getHeight()) / 2;
            this.setLocation(iCoordX, iCoordY); 
            //------>> 
        } 
        // ...
        // void main() and other public method declarations here...

}

OU

    package my.SampleUIdemo;
    import java.awt.*;
    public class classSampleUIdemo extends javax.swing.JFrame {
         /// 
         public classSampleUIdemo() {
             initComponents();
             this.setLocationRelativeTo(null);  // <<--- plain and simple
         }
         // ...
         // void main() and other public method declarations here...
   }
 4
Author: TheLooker, 2015-04-12 09:26:32

Ce qui suit ne fonctionne pas pour JDK 1.7.0.07:

frame.setLocationRelativeTo(null);

Il met le coin supérieur gauche au centre - pas la même chose que le centrage de la fenêtre. L'autre ne fonctionne pas non plus, impliquant frame.getSize () et dimension.getSize ():

Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, y);

La méthode getSize() est héritée de la classe Component, et donc frame.getSize retourne la taille de la fenêtre. Soustrayant ainsi la moitié des dimensions verticales et horizontales des dimensions verticales et horizontales, à trouver les coordonnées x,y de l'endroit où placer le coin supérieur gauche, vous donne l'emplacement du point central, ce qui finit de centrage de la fenêtre. Cependant, la première ligne du code ci-dessus est utile, "Dimension...". Faites simplement ceci pour le centrer:

Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension( (int)dimension.getWidth() / 2, (int)dimension.getHeight()/2 ));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
frame.setLocation((int)dimension.getWidth()/4, (int)dimension.getHeight()/4);

Le JLabel définit la taille de l'écran. C'est dans FrameDemo.java disponible sur les tutoriels java sur le site Oracle / Sun. Je l'ai réglé sur la moitié de la hauteur/largeur de la taille de l'écran. Ensuite, je l'ai centré en plaçant le haut à gauche au 1/4 de l'écran dimension de la taille à partir de la gauche, et 1/4 de la dimension de la taille de l'écran à partir du haut. Vous pouvez utiliser un concept similaire.

 3
Author: Jonathan Caraballo, 2012-09-30 06:13:51

Ci-dessous est le code pour afficher un cadre en haut au centre de la fenêtre existante.

public class SwingContainerDemo {

private JFrame mainFrame;

private JPanel controlPanel;

private JLabel msglabel;

Frame.setLayout(new FlowLayout());

  mainFrame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent windowEvent){
        System.exit(0);
     }        
  });    
  //headerLabel = new JLabel("", JLabel.CENTER);        
 /* statusLabel = new JLabel("",JLabel.CENTER);    
  statusLabel.setSize(350,100);
 */ msglabel = new JLabel("Welcome to TutorialsPoint SWING Tutorial.", JLabel.CENTER);

  controlPanel = new JPanel();
  controlPanel.setLayout(new FlowLayout());

  //mainFrame.add(headerLabel);
  mainFrame.add(controlPanel);
 // mainFrame.add(statusLabel);

  mainFrame.setUndecorated(true);
  mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  mainFrame.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
  mainFrame.setVisible(true);  

  centreWindow(mainFrame);

}

public static void centreWindow(Window frame) {
    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
    int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
    frame.setLocation(x, 0);
}


public void showJFrameDemo(){
 /* headerLabel.setText("Container in action: JFrame");   */
  final JFrame frame = new JFrame();
  frame.setSize(300, 300);
  frame.setLayout(new FlowLayout());       
  frame.add(msglabel);

  frame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent windowEvent){
        frame.dispose();
     }        
  });    



  JButton okButton = new JButton("Capture");
  okButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
  //      statusLabel.setText("A Frame shown to the user.");
      //  frame.setVisible(true);
        mainFrame.setState(Frame.ICONIFIED);
        Robot robot = null;
        try {
            robot = new Robot();
        } catch (AWTException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        final Dimension screenSize = Toolkit.getDefaultToolkit().
                getScreenSize();
        final BufferedImage screen = robot.createScreenCapture(
                new Rectangle(screenSize));

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ScreenCaptureRectangle(screen);
            }
        });
        mainFrame.setState(Frame.NORMAL);
     }
  });
  controlPanel.add(okButton);
  mainFrame.setVisible(true);  

} public static void main (String [] args) lève l'exception {

new SwingContainerDemo().showJFrameDemo();

}

Ci-Dessous est la sortie de code ci-dessus-extrait de:entrez la description de l'image ici

 3
Author: Aman Goel, 2017-05-02 07:35:29

Cadre.setLocationRelativeTo (null);

Exemple Complet:

    public class BorderLayoutPanel {

    private JFrame mainFrame;
    private JButton btnLeft, btnRight, btnTop, btnBottom, btnCenter;

    public BorderLayoutPanel() {
        mainFrame = new JFrame("Border Layout Example");
        btnLeft = new JButton("LEFT");
        btnRight = new JButton("RIGHT");
        btnTop = new JButton("TOP");
        btnBottom = new JButton("BOTTOM");
        btnCenter = new JButton("CENTER");
    }

    public void SetLayout() {
        mainFrame.add(btnTop, BorderLayout.NORTH);
        mainFrame.add(btnBottom, BorderLayout.SOUTH);
        mainFrame.add(btnLeft, BorderLayout.EAST);
        mainFrame.add(btnRight, BorderLayout.WEST);
        mainFrame.add(btnCenter, BorderLayout.CENTER);
//        mainFrame.setSize(200, 200);
//        or
                mainFrame.pack();
        mainFrame.setVisible(true);

        //take up the default look and feel specified by windows themes
        mainFrame.setDefaultLookAndFeelDecorated(true);

        //make the window startup position be centered
        mainFrame.setLocationRelativeTo(null);


        mainFrame.setDefaultCloseOperation(mainFrame.EXIT_ON_CLOSE);

    }
}
 2
Author: Thulani Chivandikwa, 2011-09-13 07:04:59

Il y a quelque chose de très simple que vous pourriez ignorer après avoir essayé de centrer la fenêtre en utilisant setLocationRelativeTo(null) ou setLocation(x,y) et cela finit par être un peu décentré.

Assurez-vous d'utiliser l'une ou l'autre de ces méthodes après appeler pack() parce que vous finirez par utiliser les dimensions de la fenêtre elle-même pour calculer où la placer à l'écran. Jusqu'à ce que pack() soit appelé, les dimensions ne sont pas ce que vous pensez, jetant ainsi les calculs pour centrer le fenêtre. Espérons que cette aide.

 2
Author: Clay Ellis, 2015-03-15 05:41:30

En fait , le cadre.getHeight() et getwidth() ne renvoie pas de valeurs ,vérifiez-le par System.out.println(frame.getHeight()); mettez directement les valeurs pour la largeur et la hauteur, puis cela fonctionnera bien au centre. par exemple: comme ci-dessous

Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();      
int x=(int)((dimension.getWidth() - 450)/2);
int y=(int)((dimension.getHeight() - 450)/2);
jf.setLocation(x, y);  

Les deux 450 est ma largeur de cadre n hauteur

 0
Author: Viswanath Lekshmanan, 2012-12-02 11:44:55
    public class SwingExample implements Runnable {

        @Override
        public void run() {

          // Create the window
          final JFrame f = new JFrame("Hello, World!");
          SwingExample.centerWindow(f);
          f.setPreferredSize(new Dimension(500, 250));
          f.setMaximumSize(new Dimension(10000, 200));
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }


        public static void centerWindow(JFrame frame) {

           Insets insets = frame.getInsets();
           frame.setSize(new Dimension(insets.left + insets.right + 500, insets.top + insets.bottom + 250));
           frame.setVisible(true);
           frame.setResizable(false);

           Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
           int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
           int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
           frame.setLocation(x, y);
        }
   }
 0
Author: borchvm, 2014-12-16 19:41:12

Le code suivant centre le Window au centre du moniteur actuel (c'est-à-dire où se trouve le pointeur de la souris).

public static final void centerWindow(final Window window) {
    GraphicsDevice screen = MouseInfo.getPointerInfo().getDevice();
    Rectangle r = screen.getDefaultConfiguration().getBounds();
    int x = (r.width - window.getWidth()) / 2 + r.x;
    int y = (r.height - window.getHeight()) / 2 + r.y;
    window.setLocation(x, y);
}
 0
Author: Julien, 2015-03-06 08:33:16

Vous pouvez essayer cela aussi.

       Frame frame = new Frame("Centered Frame");
       Dimension dimemsion = Toolkit.getDefaultToolkit().getScreenSize();
       frame.setLocation(dimemsion.width/2-frame.getSize().width/2, dimemsion.height/2-frame.getSize().height/2);
 0
Author: manikant gautam, 2016-01-19 06:00:39