una poner pantalla imagen hacer formulario form fondo envio confirmacion como colocar centro centrar java swing netbeans layout-manager

poner - formulario en el centro java



¿Cómo colocar el formulario en la pantalla central? (9)

Soy desarrollador de .Net pero, de alguna manera, era tarea de crear una aplicación simple en Java por algún motivo adicional. Pude crear esa aplicación pero mi problema es ¿cómo puedo centrar el formulario en la pantalla cuando se lanza la aplicación?

Aquí está mi código:

private void formWindowActivated(java.awt.event.WindowEvent evt) { // Get the size of the screen Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // Determine the new location of the window int w = this.getSize().width; int h = this.getSize().height; int x = (dim.width-w)/2; int y = (dim.height-h)/2; // Move the window this.setLocation(x, y); }

El código anterior funciona bien, pero el problema es que he visto que la forma se mueve desde la parte superior hasta la pantalla central. También intenté agregar ese código en el evento formWindowOpened y todavía muestra la misma acción. ¿Hay una mejor manera para esto? Al igual que en .NET Application hay una CenterScreen Position . O si el código anterior es correcto, ¿en qué evento lo pondré?

Gracias por leer esto


Cambia esto:

public FrameForm() { initComponents(); }

a esto:

public FrameForm() { initComponents(); this.setLocationRelativeTo(null); }


El siguiente ejemplo centra un marco en la pantalla:

package com.zetcode; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.GraphicsEnvironment; import java.awt.Point; import javax.swing.JFrame; public class CenterOnScreen extends JFrame { public CenterOnScreen() { initUI(); } private void initUI() { setSize(250, 200); centerFrame(); setTitle("Center"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private void centerFrame() { Dimension windowSize = getSize(); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); Point centerPoint = ge.getCenterPoint(); int dx = centerPoint.x - windowSize.width / 2; int dy = centerPoint.y - windowSize.height / 2; setLocation(dx, dy); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { CenterOnScreen ex = new CenterOnScreen(); ex.setVisible(true); } }); } }

Para centrar un marco en una pantalla, necesitamos obtener el entorno de gráficos local. Desde este entorno, determinamos el punto central. Junto con el tamaño del marco, logramos centrar el marco. El setLocation() es el método que mueve el marco a la posición central.

Tenga en cuenta que esto es realmente lo que hace el setLocationRelativeTo(null) :

public void setLocationRelativeTo(Component c) { // target location int dx = 0, dy = 0; // target GC GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode(); Rectangle gcBounds = gc.getBounds(); Dimension windowSize = getSize(); // search a top-level of c Window componentWindow = SunToolkit.getContainingWindow(c); if ((c == null) || (componentWindow == null)) { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); gc = ge.getDefaultScreenDevice().getDefaultConfiguration(); gcBounds = gc.getBounds(); Point centerPoint = ge.getCenterPoint(); dx = centerPoint.x - windowSize.width / 2; dy = centerPoint.y - windowSize.height / 2; } ... setLocation(dx, dy); }


En realidad, no tienes que codificar para que el formulario llegue a la pantalla central.

Solo modifica las propiedades del jframe
Siga los pasos a continuación para modificar:

  • haga clic derecho en el formulario
  • cambiar la política FormSize a: generar código de cambio de tamaño
  • luego edita la posición de formulario X -200 Y- 200

Ya terminaste Por qué tomar el dolor de la codificación. :)


Espero que esto sea útil.

poner esto en la parte superior del código fuente:

import java.awt.Toolkit;

y luego escribe este código:

private void formWindowOpened(java.awt.event.WindowEvent evt) { int lebar = this.getWidth()/2; int tinggi = this.getHeight()/2; int x = (Toolkit.getDefaultToolkit().getScreenSize().width/2)-lebar; int y = (Toolkit.getDefaultToolkit().getScreenSize().height/2)-tinggi; this.setLocation(x, y); }

buena suerte :)


Intenta usar esto:

this.setBounds(x,y,w,h);


Si usa NetBeans IDE, haga clic derecho en formulario

Propiedades -> Código -> echa un vistazo Generar Centro


Simplemente configure la ubicación relativa a null después de llamar al paquete en el JFrame, eso es todo.

p.ej,

JFrame frame = new JFrame("FooRendererTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(mainPanel); // or whatever... frame.pack(); frame.setLocationRelativeTo(null); // *** this will center your app *** frame.setVisible(true);


Usando esta función puedes definir tu posición ganadora

setBounds(500, 200, 647, 418);


public class Example extends JFrame { public static final int WIDTH = 550;//Any Size public static final int HEIGHT = 335;//Any Size public Example(){ init(); } private void init() { try { UIManager .setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); SwingUtilities.updateComponentTreeUI(this); Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); setSize(WIDTH, HEIGHT); setLocation((int) (dimension.getWidth() / 2 - WIDTH / 2), (int) (dimension.getHeight() / 2 - HEIGHT / 2)); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (UnsupportedLookAndFeelException e) { e.printStackTrace(); } } }