Save JFrame location in multi-display environment

时光毁灭记忆、已成空白 提交于 2019-12-24 05:46:54

问题


I want to store a JFrame's location (bounds, extendedState) when the user closes it. However, when the user moves the frame onto the 2nd screen and maximizes it, how can I store that information? My naive (and single display) implementation is like this:


void saveFrame(JFrame frame) throws IOException {
    Properties props = new Properties();
    props.setProperty("State", String.valueOf(frame.getExtendedState()));
    props.setProperty("X", String.valueOf(frame.getX()));
    props.setProperty("Y", String.valueOf(frame.getY()));
    props.setProperty("W", String.valueOf(frame.getWidth()));
    props.setProperty("H", String.valueOf(frame.getHeight()));
    props.storeToXML(new FileOutputStream("config.xml"), null);
}
void loadFrame(JFrame frame) throws IOException {
    Properties props = new Properties();
    props.loadFromXML(new FileInputStream("config.xml"));
    int extendedState = Integer.parseInt(props.getProperty("State", String.valueOf(frame.getExtendedState())));
    if (extendedState != JFrame.MAXIMIZED_BOTH) {
        frame.setBounds(
            Integer.parseInt(props.getProperty("X", String.valueOf(frame.getX()))),
            Integer.parseInt(props.getProperty("Y", String.valueOf(frame.getY()))),
            Integer.parseInt(props.getProperty("W", String.valueOf(frame.getWidth()))),
            Integer.parseInt(props.getProperty("H", String.valueOf(frame.getHeight())))
        );
    } else {
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    }
}

How can I discover on which screen the frame is located? How can I move a frame to the second screen and maximize it there?


回答1:


To find the ID of the used graphics device:

frame.getGraphicsConfiguration().getDevice().getIDString()

Going the other way, you can find the graphics devices with:

 GraphicsEnvironment.getLocalGraphicsEnvironment().getDevices()

You can then use a configuration from the device in the JFrame constructor. I don't believe you can set it after construction.

Of course, you should be careful not to, say, open the frame off screen because the resolution has change.



来源:https://stackoverflow.com/questions/810539/save-jframe-location-in-multi-display-environment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!