4

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)

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.