Reputation: 8209
I want to get the resolution for the screen the window is currently located in. So if I drag the window from one display to another with a different resolution the application should be able to change.
I'm running this on a thinkpad running ubuntu gnome connected to a external screen.
Here're my current attempts:
import java.awt.Dimension;
import java.awt.DisplayMode;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class sizetest {
void run() {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("sizetest");
shell.pack();
shell.open();
while (!shell.isDisposed()) {
DisplayMode mode = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode();
System.out.println(String.format("Current environment screensize: %s, %s", mode.getWidth(), mode.getHeight()));
Dimension current = Toolkit.getDefaultToolkit().getScreenSize();
System.out.println(String.format("Current toolkit screensize: %s, %s", current.getWidth(), current.getHeight()));
Rectangle bounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().getBounds();
System.out.println(String.format("Bounds %s, %s", bounds.width, bounds.height));
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
public static void main(String[] args) {
sizetest o = new sizetest();
o.run();
}
}
Output is
Current environment screensize: 1920, 1080
Current toolkit screensize: 3840.0, 3240.0
Bounds 1920, 1080
Neither of them change when I move the window from one screen to the other.
Upvotes: 0
Views: 2143
Reputation: 100309
If you have an AWT/Swing window, you can query its GraphicsConfiguration
to get what you want. Note that the different parts of the window can be located on several displays at a time. This method returns the display where the the window center is located. Here's simple component which displays the size of its current display:
public class TestFrame extends JFrame {
JLabel label = new JLabel();
public TestFrame() {
super("Resolution tracker");
setSize(300, 50);
add(label);
updateResolution();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent e) {
updateResolution();
}
});
}
protected void updateResolution() {
DisplayMode mode = this.getGraphicsConfiguration().getDevice().getDisplayMode();
label.setText(mode.getWidth()+" x "+mode.getHeight());
}
public static void main(String args[]) {
new TestFrame().setVisible(true);
}
}
Upvotes: 3