Salva posizione JFrame in ambiente multi-display
Domanda
Voglio archiviare la posizione di un JFrame (limiti, extendedState) quando l'utente lo chiude. Tuttavia, quando l'utente sposta il riquadro sulla seconda schermata e lo ingrandisce, come posso memorizzare tali informazioni? La mia implementazione ingenua (e con display singolo) è così:
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);
}
}
Come posso scoprire su quale schermo si trova la cornice? Come posso spostare una cornice sulla seconda schermata e ingrandirla lì?
Soluzione
Per trovare l'ID del dispositivo grafico utilizzato:
frame.getGraphicsConfiguration().getDevice().getIDString()
In alternativa, puoi trovare i dispositivi grafici con:
GraphicsEnvironment.getLocalGraphicsEnvironment().getDevices()
È quindi possibile utilizzare una configurazione dal dispositivo nel costruttore JFrame
. Non credo che tu possa impostarlo dopo la costruzione.
Ovviamente, dovresti stare attento, per esempio, ad aprire il riquadro fuori dallo schermo perché la risoluzione è cambiata.