Pergunta

O que é a maneira mais fácil de centralizar um java.awt.Window, como um JFrame ou um JDialog?

Foi útil?

Solução

De este link

Se você estiver usando Java 1.4 ou mais recente, você pode usar o método simples setLocationRelativeTo (nulo) na caixa de diálogo, quadro ou janela para o centro -lo.

Outras dicas

Isso deve funcionar em todas as versões do 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);
}

Note que as técnicas tanto o setLocationRelativeTo (null) e Tookit.getDefaultToolkit (). GetScreenSize () funciona somente para o monitor principal. Se você estiver em um ambiente multi-monitor, você pode precisar de obter informações sobre o monitor específico a janela está em antes de fazer esse tipo de cálculo.

Às vezes importante, às vezes não ...

Consulte GraphicsEnvironment javadocs para obter mais informações sobre como conseguir isso.

setLocationRelativeTo (null) deve ser chamado depois de tanto uso setSize (x, y), ou o uso pack ().

No Linux o código

    setLocationRelativeTo(null)

Coloque a minha janela para localização aleatória a cada vez que o lançou, em um ambiente de display multi. E o código

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

"corte" a janela ao meio com colocando-o para o centro exato, que está entre os meus dois monitores. Eu usei o seguinte método para centralizá-lo:

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

Faz a janela aparecer bem no centro da primeira apresentação. Isto provavelmente não é a solução mais fácil.

funciona corretamente no Linux, Windows e Mac.

Eu finalmente consegui esse bando de códigos para trabalhar no NetBeans usando GUI Swing formas, a fim de JFrame principal centro:

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

A seguir não funciona para JDK 1.7.0.07:

frame.setLocationRelativeTo(null);

Ele coloca o canto superior esquerdo no centro - não o mesmo que centrar a janela. O outro não quer trabalhar, envolvendo frame.getSize () e 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);

O getSize () método é herdado a partir da classe de componentes, e, por conseguinte, frame.getSize retorna o tamanho da janela, bem. Assim, subtraindo metade das dimensões vertical e horizontal das dimensões verticais e horizontais, para encontrar o x, y coordenadas de onde colocar o canto superior esquerdo, dá-lhe a localização do ponto central, o que acaba centrando a janela também. No entanto, a primeira linha do código acima é útil, "Dimensão ...". Só não esta para centralizá-la:

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

O JLabel define o tamanho de tela. É em FrameDemo.java disponíveis nos tutoriais java no site da Oracle / dom Eu defini-lo para a metade do tamanho da tela altura / largura. Então, eu centrada-lo, colocando a parte superior esquerda no 1/4 da dimensão do tamanho da tela da esquerda, e 1/4 da dimensão do tamanho da tela de cima. Você pode usar um conceito similar.

Abaixo está o código para exibir um quadro na parte superior central da janela 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();

}

Abaixo está a ouput de trecho de código acima: enter descrição da imagem aqui

frame.setLocationRelativeTo (null);

exemplo completa:

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

    }
}

Há algo de muito simples que você pode ser vista depois de tentar centrar a janela usando setLocationRelativeTo(null) ou setLocation(x,y) e ele acaba sendo um pouco fora do centro.

Certifique-se de que você usar qualquer um desses métodos depois chamando pack() porque o que você vai acabar usando as dimensões da própria janela para calcular onde colocá-lo na tela. Até pack() é chamado, as dimensões não o que você pensaria assim, jogando fora os cálculos para centralizar a janela é. Espero que isso ajude.

Exemplo: Inside MyWindow () na linha 3 é o código que você precisa para definir a janela no centro da tela.

JFrame window;

public myWindow() {

    window = new JFrame();
    window.setSize(1200,800);
    window.setLocationRelativeTo(null); // this line set the window in the center of thr screen
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().setBackground(Color.BLACK);
    window.setLayout(null); // disable the default layout to use custom one.
    window.setVisible(true); // to show the window on the screen.
}

Na verdade valores frame.getHeight() e retorno getwidth() não faz, verificá-lo por System.out.println(frame.getHeight()); colocar diretamente os valores para largura e altura, então ele vai funcionar bem no centro. por exemplo: como abaixo

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

450 é tanto meu quadro largura altura n

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

O centro de código a seguir a Window no centro do monitor de corrente (isto é, quando o cursor do rato está localizado).

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

Você poderia tentar isso também.

       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);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top