it-source

Swing GUI를 가장 잘 포지셔닝하는 방법

criticalcode 2022. 11. 20. 12:17
반응형

Swing GUI를 가장 잘 포지셔닝하는 방법

또 다른 스레드에서는, 다음과 같은 조작으로 GUI 의 중심을 잡는 것을 좋아한다고 말하고 있습니다.

JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new HexagonGrid());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

하지만 앤드류 톰슨은 다른 의견을 가지고 있었다.

frame.pack();
frame.setLocationByPlatform(true);

왜 그런지 알고 싶은가?

화면 중앙에 있는 GUI는 제 눈에는 그렇게 보입니다."화면 표시"나는 그것들이 사라지고 진짜 GUI가 나타나기를 계속 기다리고 있어!

Java 1.5 이후, 에 액세스 할 수 있게 되었습니다.

다음 번에 창을 표시할 때 이 창을 네이티브 창 시스템의 기본 위치에 표시할지 아니면 현재 위치(getLocation에 의해 반환됨)에 표시할지 설정합니다.이 동작은 프로그래밍 방식으로 위치를 설정하지 않고 표시되는 네이티브 창과 유사합니다.대부분의 윈도우 시스템은 위치가 명시적으로 설정되지 않은 경우 창을 계단식으로 표시합니다.화면에 창이 뜨면 실제 위치가 결정됩니다.

이 예에서는 Windows 7, Gnome 및 Mac OS X를 탑재한 Linux에서 3개의 GUI를 OS에서 선택한 디폴트 위치에 배치하고 있습니다.

Windows 7의 창 스택 여기에 이미지 설명 입력 Mac OS X의 누적 창

(3개의 로트) 3개의 GUI를 깔끔하게 스택.이는 OS가 기본 플레인 텍스트 에디터의 인스턴스 3개를 배치하는 방법이기 때문에 최종 사용자에게 '놀라지 않는 경로'를 나타냅니다.Linux & Mac 이미지용 쓰레기의 신에게 감사드립니다.

사용되는 간단한 코드는 다음과 같습니다.

import javax.swing.*;

class WhereToPutTheGui {

    public static void initGui() {
        for (int ii=1; ii<4; ii++) {
            JFrame f = new JFrame("Frame " + ii);
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            String s =
                "os.name: " + System.getProperty("os.name") +
                "\nos.version: " + System.getProperty("os.version");
            f.add(new JTextArea(s,3,28));  // suggest a size
            f.pack();
            // Let the OS handle the positioning!
            f.setLocationByPlatform(true);
            f.setVisible(true);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                try {
                    UIManager.setLookAndFeel(
                        UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {}
                initGui();
            }
        });
    }
}

나는 전적으로 동의한다setLocationByPlatform(true)는 새로운 JFrame의 위치를 지정하는 가장 적절한 방법이지만 듀얼 모니터 설정에서는 문제가 발생할 수 있습니다.내 경우, 하위 JFrame은 '다른' 모니터에서 생성됩니다.예:화면 2에 메인 GUI가 있고, 다음으로 새로운 JFrame을 시작합니다.setLocationByPlatform(true)화면 1에서 열립니다.여기 보다 완전한 솔루션이 있습니다.

...
// Let the OS try to handle the positioning!
f.setLocationByPlatform(true);
if (!f.getBounds().intersects(MyApp.getMainFrame().getBounds())) {
    // non-cascading, but centered on the Main GUI
    f.setLocationRelativeTo(MyApp.getMainFrame()); 
}
f.setVisible(true);

언급URL : https://stackoverflow.com/questions/7143287/how-to-best-position-swing-guis

반응형