Código de Java - JFrame en el centro de la pantalla – Java Swing

Imágen de perfil
Val: 42
Ha disminuido su posición en 2 puestos en Java (en relación al último mes)
Gráfica de Java

JFrame en el centro de la pantalla – Java Swinggráfica de visualizaciones


Java

Publicado el 18 de Enero del 2016 por Julio (12 códigos)
9.367 visualizaciones desde el 18 de Enero del 2016
Vamos a ver en este código como centrar un JFrame en Java Swing, en este sencilllo ejemplo con Java Swing simplemente se crea un JFrame con Netbeans para añadir un par de JLabel con el editor gráfico y utilizar el método para centrarlo.


Aquí os dejo el primero de una serie de códigos sobre Java Swing ( http://codigoxules.org/java/java-swing/) que iré publicando próximamente.

El objetivo de este código es explicar como centrar un JFrame o colocarlo en la posición que quieras de forma sencilla. Estos es el método que se puede utilizar en cualquier clase con JFrame:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/** 
     * Place the JFrame with the parameters by moving the component relative to the center of the screen.
     * Colocamos el JFrame con los parámetros desplazando el componente respecto al centro de la pantalla.  
     * @param moveWidth int positive or negative offset width (desplazamiente de width positivo o negativo).
     * @param moveHeight int Positive or negative offset height (desplazamiento de height positivo o negativo).
     */
    public void setLocationMove(int moveWidth, int moveHeight) {
        // Obtenemos el tamaño de la pantalla.
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        // Obtenemos el tamaño de nuestro frame.
        Dimension frameSize = this.getSize();
        frameSize.width = frameSize.width > screenSize.width?screenSize.width:frameSize.width;
        frameSize.height = frameSize.height > screenSize.height?screenSize.height:frameSize.height;
        // We define the location. Definimos la localización.
        setLocation((screenSize.width - frameSize.width) / 2 + moveWidth, (screenSize.height - frameSize.height) / 2 + moveHeight);
    }
Así que para colocarlo en el centro de la pantalla simplemente añadimos otro método por comodidad:
1
2
3
4
5
6
7
/**
     * Set the JFrame in the center of the screen.
     * Colocamos nuestro JFrame en el centro de la pantalla.
     */
    public void setLocationCenter(){
        setLocationMove(0, 0);
    }


En el método main encontrarás el ejemlo de utilización:
1
2
3
new JFrameCenterSimple(100, 200).setVisible(true);
        new JFrameCenterSimple(-100, -200).setVisible(true);
        new JFrameCenterSimple().setVisible(true);

Este será el resultado del ejemplo usando:
JFrameCenterSimple


Espero que te sea útil.

Requerimientos

No necesita ninguna librería adicional, mi ejemplo está hecho con Netbeans utilizando el editor gráfico, pero los métodos de centrado los puedes utilizar en cualquier clase que sea un JFrame.

1.0
estrellaestrellaestrellaestrellaestrella(2)

Publicado el 18 de Enero del 2016gráfica de visualizaciones de la versión: 1.0
9.368 visualizaciones desde el 18 de Enero del 2016
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package org.xulescode.swing;
 
import java.awt.Dimension;
import java.awt.Toolkit;
 
/**
 * Easy to focus a JFrame on screen or place where we want about the center example.
 * Ejemplo sencillo para centrar un JFrame en pantalla o colocar donde queramos respecto al centro.
 * @author xules
 *      You can follow me on my website http://www.codigoxules.org/en 
 *      Puedes seguirme en mi web http://www.codigoxules.org
 */
public class JFrameCenterSimple extends javax.swing.JFrame {
 
    /**
     * Create a new form JFrameCenterSimple centered with respect to the screen
     * Crea un nuevo form JFrameCenterSimple centrado con respecto a la pantalla.
     */
    public JFrameCenterSimple() {
        initComponents();
        setLocationCenter();
        setVisible(true);
    }
    /**
     * Create a new form JFrameCenterSimple centered with respect to the screen
     * Crea un nuevo form JFrameCenterSimple centrado con respecto a la pantalla.
     * @param moveWidth int positive or negative offset width (desplazamiente de width positivo o negativo).
     * @param moveHeight int Positive or negative offset height (desplazamiento de height positivo o negativo).
     */
    public JFrameCenterSimple(int moveWidth, int moveHeight) {
        initComponents();
        setLocationMove(moveWidth, moveHeight);
        setVisible(true);
    }
    /**
     * Set the JFrame in the center of the screen.
     * Colocamos nuestro JFrame en el centro de la pantalla.
     */
    public void setLocationCenter(){
        setLocationMove(0, 0);
    }
    /** 
     * Place the JFrame with the parameters by moving the component relative to the center of the screen.
     * Colocamos el JFrame con los parámetros desplazando el componente respecto al centro de la pantalla.  
     * @param moveWidth int positive or negative offset width (desplazamiente de width positivo o negativo).
     * @param moveHeight int Positive or negative offset height (desplazamiento de height positivo o negativo).
     */
    public void setLocationMove(int moveWidth, int moveHeight) {
        // Obtenemos el tamaño de la pantalla.
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        // Obtenemos el tamaño de nuestro frame.
        Dimension frameSize = this.getSize();
        frameSize.width = frameSize.width > screenSize.width?screenSize.width:frameSize.width;
        frameSize.height = frameSize.height > screenSize.height?screenSize.height:frameSize.height;
        // We define the location. Definimos la localización.
        setLocation((screenSize.width - frameSize.width) / 2 + moveWidth, (screenSize.height - frameSize.height) / 2 + moveHeight);
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
 
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
 
        jTextField1.setText("jTextField1");
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("JFrame screen location (posicionamiento en pantalla)");
 
        jLabel1.setFont(new java.awt.Font("Ubuntu", 1, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Centramos el JFrame en la pantalla");
        jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
 
        jLabel2.setFont(new java.awt.Font("Ubuntu", 1, 18)); // NOI18N
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("Center the JFrame on the screen");
        jLabel2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(107, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 312, Short.MAX_VALUE))
                .addContainerGap(120, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(79, Short.MAX_VALUE)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(59, 59, 59)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(84, 84, 84))
        );
 
        pack();
    }// </editor-fold>                        
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFrameCenterSimple.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrameCenterSimple.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrameCenterSimple.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrameCenterSimple.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JFrameCenterSimple(100, 200).setVisible(true);
                new JFrameCenterSimple(-100, -200).setVisible(true);
                new JFrameCenterSimple().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}



Comentarios sobre la versión: 1.0 (2)

Imágen de perfil
21 de Enero del 2016
estrellaestrellaestrellaestrellaestrella
Muy Bueno
Responder
Imágen de perfil
26 de Noviembre del 2016
estrellaestrellaestrellaestrellaestrella
Muy buenas, yo utilizo otro comando, básicamente es lo mismo pero un tanto diferente:

En este ejemplo... Mi jFrame se llama jFRM_Menu, en la parte del public simplemente se pone "setLocationRelativeTo(null);" sin las comillas y debajo de initComponents(); como en el ejemplo de abajo:

public jFRM_Menu() {

initComponents();
setLocationRelativeTo(null);

}

Espero que le sea de utilidad a alguien más ya que me ha servido bastante ésta pequeña sección de código.

Saludos.
Responder

Comentar la versión: 1.0

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s3411