tutorial gui framework example español create java swing user-interface awt

gui - java swing pdf



Cómo centrar una ventana en Java? (14)

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

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

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


El siguiente código centra la Window en el centro del monitor actual (es decir, donde se encuentra el puntero del mouse).

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


En Linux, el código

setLocationRelativeTo(null)

Poner mi ventana en una ubicación aleatoria cada vez que la lancé, en un entorno de múltiples pantallas. Y el código

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

"corte" la ventana por la mitad con la colocación en el centro exacto, que se encuentra entre mis dos pantallas. Usé 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 aparezca justo 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.


En realidad, frame .getHeight() y getwidth() no devuelven valores, System.out.println(frame.getHeight()); por System.out.println(frame.getHeight()); poner directamente los valores de ancho y alto, entonces funcionará bien en el centro. Ej .: 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);

ambos 450 es mi ancho de cuadro n altura


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


Finalmente conseguí este conjunto de códigos para trabajar en NetBeans usando Swing GUI Forms para 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... }


Hay algo realmente simple que puede pasar por alto después de intentar centrar la ventana usando setLocationRelativeTo(null) o setLocation(x,y) y termina siendo un poco descentrado.

Asegúrese de utilizar uno de estos métodos después de llamar a pack() porque terminará utilizando las dimensiones de la ventana para calcular dónde colocarlo en la pantalla. Hasta que se llame a pack() , las dimensiones no son lo que se podría pensar, por lo que se descartan los cálculos para centrar la ventana. Espero que esto ayude.


Lo siguiente no funciona para JDK 1.7.0.07:

frame.setLocationRelativeTo(null);

Pone la esquina superior izquierda en el centro, no lo mismo que centrar la ventana. El otro tampoco funciona, involucrando 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 Component y, por lo tanto, frame.getSize también devuelve el tamaño de la ventana. 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 ...". Solo haz 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);

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.


Podrías 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);


Tenga en cuenta que las técnicas setLocationRelativeTo (null) y Tookit.getDefaultToolkit (). GetScreenSize () solo funcionan 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.

A veces importante, a veces no ...

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


a continuación se muestra un código para mostrar un cuadro 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 static void main (String [] args) throws Exception {

new SwingContainerDemo().showJFrameDemo();

}

A continuación se muestra la salida del fragmento de código anterior:


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


setLocationRelativeTo (null) debe invocarse después de usar setSize (x, y) o use pack ().


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