问题
如何以像素为单位获得屏幕分辨率(宽x高)?
我正在使用JFrame和java swing方法。
#1 热门回答(232 赞)
你可以使用Toolkit.getScreenSize()
方法获得屏幕尺寸。
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
在多显示器配置上,你应该使用:
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();
如果你想在DPI中获得屏幕分辨率,你将不得不使用4303470701方法的getScreenResolution()
方法。
资源:- javadoc - Toolkit.getScreenSize()
- Java bug 5100801- Toolkit.getScreenSize()在multimon,linux上没有返回正确的维度
#2 热门回答(15 赞)
此代码将枚举系统上的图形设备(如果安装了多个监视器),你可以使用该信息来确定监视器关联或自动放置(某些系统在应用程序运行时使用一个小型监视器进行实时显示背景,这样的监视器可以通过大小,屏幕颜色等来识别。):
// Test if each monitor will support my app's window
// Iterate through each monitor and see what size each is
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
Dimension mySize = new Dimension(myWidth, myHeight);
Dimension maxSize = new Dimension(minRequiredWidth, minRequiredHeight);
for (int i = 0; i < gs.length; i++)
{
DisplayMode dm = gs[i].getDisplayMode();
if (dm.getWidth() > maxSize.getWidth() && dm.getHeight() > maxSize.getHeight())
{ // Update the max size found on this monitor
maxSize.setSize(dm.getWidth(), dm.getHeight());
}
// Do test if it will work here
}
#3 热门回答(11 赞)
此调用将为你提供所需的信息。
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();