Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: any way to detect changes in display configuration?

Tags:

java

swing

One of my coworkers would like my Swing app to adapt correctly to the removal of a 2nd display monitor.

Is there any way to get notification of this, other than polling to repeatedly compute virtual bounds? (per the code sample in http://download.oracle.com/javase/6/docs/api/java/awt/GraphicsConfiguration.html)

like image 214
Jason S Avatar asked Oct 18 '25 15:10

Jason S


2 Answers

Hum, tricky one. Because GraphicsConfiguration class won't give us any listeners, I'll have only a couple of alternatives:

  1. (If Windows) Use a JNI interface to Windows to detect display settings change and forward them to Java. This would be the SystemEvents::DisplaySettingsChanged Event.

  2. Create a simple polling Thread - timer that retrieves the result of Toolkit.getDefaultToolkit().getScreenSize() as you've already stated before.

like image 166
Reynaldo Avatar answered Oct 20 '25 04:10

Reynaldo


Not sure if it was any different back then with Java 6, but currently one could listen to graphicsConfiguration property changes on the top-level window:

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

public class SampleFrame extends JFrame {

    private final JTextArea log = new JTextArea();

    public SampleFrame() {
        super("Sample Window");
        log.setEditable(false);
        log.setLineWrap(true);
        logGC("Initial");
        super.add(new JScrollPane(log));
        super.addPropertyChangeListener("graphicsConfiguration",
                evt -> logGC("Changed"));
    }

    private void logGC(String label) {
        Document text = log.getDocument();
        try {
            Object gc = super.getGraphicsConfiguration();
            text.insertString(text.getLength(), String.format("%s: (%x) %s\n\n",
                    label, System.identityHashCode(gc), gc), null);
        } catch (BadLocationException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(() -> {
            SampleFrame window = new SampleFrame();
            window.setDefaultCloseOperation(EXIT_ON_CLOSE);
            window.setSize(640, 480);
            window.setLocationRelativeTo(null);
            window.setVisible(true);
        });
    }

}

I can see changes to the graphicsConfiguration of the application window are notified on system display settings changes, moving the application window to another monitor, connecting or disconnecting monitors from the system.

like image 43
Stanimir Avatar answered Oct 20 '25 06:10

Stanimir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!