Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top