2008-09-28 26 views
89

¿Cuál es la forma más fácil de centrar un java.awt.Window, como un JFrame o un JDialog?¿Cómo centrar una ventana en Java?

+2

El título debería ser "en Swing" no "en Java", sería más claro de esa manera. –

+4

@Joe 'setLocation()', 'setLocationRelativeTo()' y 'setLocationByPlatform()' o todos AWT, no Swing. ;) –

Respuesta

205

De blog.codebeach.com/2008/02/center-dialog-box-frame-or-window-in.html (ya muerto)

Si está utilizando Java 1.4 o más reciente , puede usar el método simple setLocationRelativeTo (nulo) en el cuadro de diálogo , marco o ventana para centrarlo en .

+4

Como @kleopatra dijo en otra respuesta, setLocationRelativeTo (null) debe llamarse after pack() para poder funcionar. – Eusebius

+2

Como se explica a continuación, setLocationRelativeTo (null) debe invocarse después de cualquier llamada de pack() o setSize(). –

+1

@Eusebius Odd, seguí un tutorial que me hizo configurarlo antes de 'pack()' y puso la esquina superior del marco en el centro de mi pantalla. Después de mover la línea hacia abajo 'pack()' se centró correctamente. – user1433479

59

Esto debería funcionar en todas las versiones 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); 
} 
+0

Sé que esto es bastante antiguo pero funciona bien, siempre que el tamaño del marco esté establecido antes de llamar a esta función –

+0

Sí, asegúrese de que el tamaño se aplica antes (usando pack() por ejemplo) – Myoch

22

Tenga en cuenta que las técnicas tanto de la setLocationRelativeTo (nulo) y Tookit.getDefaultToolkit(). GetScreenSize() funcionan sólo para el monitor principal. Si se encuentra en un entorno de monitores múltiples, es posible que necesite obtener información sobre el monitor específico en el que se encuentra la ventana antes de realizar este tipo de cálculos.

veces importantes, a veces no

...

Ver GraphicsEnvironment javadocs para obtener más información sobre cómo conseguir esto.

2

frame.setLocationRelativeTo (null);

ejemplo completo:

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); 

    } 
} 
3

El siguiente no funciona para JDK 1.7.0.07:

frame.setLocationRelativeTo(null); 

Pone la esquina superior izquierda en el centro - no es el mismo que el centrado de la ventana . El otro no funciona bien, con la participación frame.getSize() y 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); 

El método getSize() se hereda de la clase de componente, y por lo tanto frame.getSize devuelve el tamaño de la ventana también. Así, al restar la mitad de las dimensiones verticales y horizontales de las dimensiones vertical y horizontal, para encontrar las coordenadas x, y de dónde colocar la esquina superior izquierda, se obtiene la ubicación del punto central, que también termina centrando la ventana. Sin embargo, la primera línea del código anterior es útil, "Dimensión ...". Simplemente haga esto para centrarlo:

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); 

El JLabel establece el tamaño de la pantalla. Está en FrameDemo.java disponible en los tutoriales de Java en el sitio de Oracle/Sun. Lo configuré a la mitad de la altura/ancho del tamaño de la pantalla. Luego, lo centré colocando la parte superior izquierda en 1/4 de la dimensión del tamaño de la pantalla desde la izquierda, y 1/4 de la dimensión del tamaño de la pantalla desde la parte superior. Puedes usar un concepto similar.

+1

Tampoco el otro. Estos códigos ponen la esquina superior izquierda de la pantalla en el centro. –

+7

-1 no se puede reproducir, o más precisamente: solo ocurre si setLocationRelative se llama _antes de dimensionar el fotograma (por paquete o setSize manual). Para un marco de tamaño cero, la esquina superior izquierda es la misma ubicación que su centro :-) – kleopatra

+0

-1. Ver Dzmitry Sevkovich respuesta –

0

En realidad enmarcan .getHeight() y getwidth() valores de retorno no funciona, comprobarlo por System.out.println(frame.getHeight()); poner directamente los valores para la anchura y la altura, entonces todo funcionará bien en el centro.por ejemplo: como abajo

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

tanto 450 es mi ancho del marco altura n

+1

-1 el tamaño de un fotograma es cero antes ... dimensionarlo :-) Preferiblemente por paquete, o al menos al configurar manualmente su tamaño a cualquier cosa que no sea _antes de llamar a setLocationRelative permitirá su cálculo interno correcto – kleopatra

20

setLocationRelativeTo (null) debe ser llamado después de que o bien utiliza setSize (x, y), o utilizar pack().

+0

esto funcionó para mí en JDK 1.7 – aldrin

+0

Tienes razón. Necesita tener setSize() llamar antes. –

14

En Linux el código

setLocationRelativeTo(null) 

poner mi ventana a la ubicación aleatoria cada vez que se puso en marcha, en un entorno multi pantalla. Y el código

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

"corte" de la ventana por la mitad con colocándolo al centro exacto, que está entre mis dos pantallas. He utilizado el siguiente método para centrarlo:

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); 
} 

hace que la ventana aparece a la derecha en el centro de la primera pantalla. Probablemente esta no sea la solución más fácil.

Funciona correctamente en Linux, Windows y Mac.

+0

Tener en cuenta los entornos de pantalla múltiple es la única respuesta correcta; de lo contrario, la pantalla donde aparece la ventana podría ser algo aleatorio o la ventana se centra entre ambas pantallas. – Stephan

0
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

La siguiente centro de código de la Window en el centro del monitor de corriente (es decir, donde está situado el puntero del ratón).

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); 
} 
2

Hay algo muy simple que podría estar pasando por alto después de intentar centrar la ventana utilizando setLocationRelativeTo(null) o setLocation(x,y) y que termina siendo un poco fuera del centro.

Asegúrese de que utiliza uno de estos métodos después llamando pack() porque el que va a terminar usando las dimensiones de la propia ventana para calcular dónde colocarlo en la pantalla. Hasta que se llame al pack(), las dimensiones no son lo que usted pensaría, por lo que se descartarían los cálculos para centrar la ventana. Espero que esto ayude.

4

fin llegué este montón de códigos para trabajar en NetBeans usando las Formas Swing GUI con el fin de centrar 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); 
    } 

} 

O

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... 

} 

O

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... 
    } 
0

Usted podría probar esto también

 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); 
+1

¿Qué hay de los monitores múltiples? – Supuhstar

3

a continuación es el código para mostrar un marco en la parte superior central de la ventana existente.

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 void main (String [] args) throws Exception {estáticas

new SwingContainerDemo().showJFrameDemo(); 

}

continuación es que la salida de código- anteriormente fragmento: enter image description here

+0

'frame.setLocation (x, 0);' parece estar equivocado, ¿no debería ser 'frame.setLocation (x, y);' en su lugar? – deem

+0

x denota la longitud del eje x e indica la longitud del eje y. Entonces, si haces y = 0 entonces solo debería estar en la parte superior. –

+0

Entonces 'int y = (int) ((dimension.getHeight() - frame.getHeight())/2);' existe solo en el código para mostrar que también se puede centrar en el eje vertical? Ok, pensé que te olvidaste de usarlo, lo siento por problemas. – deem