문제

중앙에 맞추는 가장 쉬운 방법은 무엇입니까? java.awt.Window, 과 같은 JFrame 또는 JDialog?

도움이 되었습니까?

해결책

에서 이 링크

Java 1.4 또는 최신을 사용하는 경우 대화 상자, 프레임 또는 창에서 간단한 방법 SetLocationRelativeto (NULL)를 사용하여 중앙 중심을 사용할 수 있습니다.

다른 팁

이것은 모든 버전의 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);
}

setLocationRelativeTo (NULL) 및 TOKET.GetDefaultToolKit (). getScreensize () 기술은 기본 모니터에만 작동합니다. 다중 모니터 환경에있는 경우 이러한 종류의 계산을 수행하기 전에 창에 켜진 특정 모니터에 대한 정보를 얻어야 할 수도 있습니다.

때때로 중요하고 때로는 ...

보다 그래픽 환경 Javadocs 이것을 얻는 방법에 대한 자세한 정보.

setSize (x, y)를 사용하거나 pack ()를 사용한 후에 setLocationRelativeto (null)를 호출해야합니다.

Linux에서 코드

    setLocationRelativeTo(null)

다중 디스플레이 환경에서 발사 할 때마다 창문을 임의의 위치에 두십시오. 그리고 코드

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

두 디스플레이 사이에있는 정확한 센터에 배치 한 창을 반으로 "절단"합니다. 다음 방법을 사용하여 중앙에 사용했습니다.

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

첫 번째 디스플레이의 중앙에 창이 바로 나타납니다. 이것은 아마도 가장 쉬운 솔루션이 아닐 것입니다.

Linux, Windows 및 Mac에서 제대로 작동합니다.

마침내 메인 JFrame을 중심으로 스윙 GUI 양식을 사용하여 NetBeans에서 작동하는이 코드를 얻었습니다.

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

}

또는

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

}

또는

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

다음은 JDK 1.7.0.07에서 작동하지 않습니다.

frame.setLocationRelativeTo(null);

왼쪽 상단 모서리를 중앙에 배치합니다. 창을 중앙에 배치하는 것과는 다릅니다.Frame.getSize() 및 차원.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);

getSize() 메서드는 Component 클래스에서 상속되므로 Frame.getSize는 창 크기도 반환합니다.따라서 수직 및 수평 치수에서 수직 및 수평 치수의 절반을 빼서 왼쪽 상단 모서리를 배치할 위치의 x, y 좌표를 찾으면 중심점의 위치가 제공되며 결국 창의 중심이 됩니다.그러나 위 코드의 첫 번째 줄인 "Dimension..."이 유용합니다.중앙에 맞추려면 다음을 수행하세요.

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은 화면 크기를 설정합니다.이는 Oracle/Sun 사이트의 Java 튜토리얼에서 사용할 수 있는 FrameDemo.java에 있습니다.화면 크기의 높이/너비의 절반으로 설정했습니다.그런 다음 왼쪽 상단을 왼쪽에서 화면 크기 치수의 1/4, 위에서 화면 크기 치수의 1/4에 배치하여 중앙에 배치했습니다.비슷한 개념을 사용할 수 있습니다.

아래는 기존 창의 상위 센터에 프레임을 표시하기위한 코드입니다.

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)은 예외 {

new SwingContainerDemo().showJFrameDemo();

}

아래는 위의 코드 스냅 펫의 OUPUT입니다.enter image description here

frame.setLocationRelativeTo (null);

Full example:

    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) 또는 setLocation(x,y) 그리고 그것은 약간의 중심이됩니다.

이 방법 중 하나를 사용하는지 확인하십시오. ~ 후에 부름 pack() 화면에 배치 할 위치를 계산하기 위해 창 자체의 크기를 사용하여 끝나기 때문입니다. 까지 pack() 차원은 당신이 생각하는 것이 아니기 때문에 창을 중심으로 계산을 버리는 것이 아닙니다. 도움이 되었기를 바랍니다.

예 : 3 행의 MyWindow () 내부는 화면 중앙에 창을 설정하는 데 필요한 코드입니다.

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

실제로 프레임.getHeight() 그리고 getwidth() 값을 반환하지 않고 확인하십시오 System.out.println(frame.getHeight()); 너비와 높이의 값을 직접 넣으면 중앙에서 잘 작동합니다. 예 : 아래와 같이

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

모두 450은 내 프레임 너비 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);
        }
   }

다음 코드 센터 Window 현재 모니터의 중앙 (즉, 마우스 포인터가있는 위치).

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

당신은 이것도 시도 할 수 있습니다.

       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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top