Кто-нибудь знает, как вы получите ширину экрана в java? Я кое-что прочитал о методе инструментальных средств, но я не совсем уверен, что это такое.
Спасибо, Эндрю
Кто-нибудь знает, как вы получите ширину экрана в java? Я кое-что прочитал о методе инструментальных средств, но я не совсем уверен, что это такое.
Спасибо, Эндрю
java.awt.Toolkit.getDefaultToolkit().getScreenSize()
Вот два метода, которые я использую, которые учитывают несколько мониторов и вставки на панели задач. Если вам не нужны эти два метода отдельно, вы можете, конечно, не дважды получать конфигурацию графики.
static public Rectangle getScreenBounds(Window wnd) {
Rectangle sb;
Insets si=getScreenInsets(wnd);
if(wnd==null) {
sb=GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration()
.getBounds();
}
else {
sb=wnd
.getGraphicsConfiguration()
.getBounds();
}
sb.x +=si.left;
sb.y +=si.top;
sb.width -=si.left+si.right;
sb.height-=si.top+si.bottom;
return sb;
}
static public Insets getScreenInsets(Window wnd) {
Insets si;
if(wnd==null) {
si=Toolkit.getDefaultToolkit().getScreenInsets(GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration());
}
else {
si=wnd.getToolkit().getScreenInsets(wnd.getGraphicsConfiguration());
}
return si;
}
Рабочая область - это область рабочего стола дисплея, исключая панели задач, стыковочные окна и стыковочные панели инструментов.
Если вы хотите использовать "рабочую область" экрана, используйте это:
public static int GetScreenWorkingWidth() {
return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().width;
}
public static int GetScreenWorkingHeight() {
return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height;
}
Следующий код должен сделать это (не пробовал):
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
gd.getDefaultConfiguration().getBounds().getWidth();
изменить
Для нескольких мониторов вы должны использовать следующий код (взятый из javadoc java.awt.GraphicsConfiguration
:
Rectangle virtualBounds = new Rectangle();
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
GraphicsDevice[] gs =
ge.getScreenDevices();
for (int j = 0; j < gs.length; j++) {
GraphicsDevice gd = gs[j];
GraphicsConfiguration[] gc =
gd.getConfigurations();
for (int i=0; i < gc.length; i++) {
virtualBounds =
virtualBounds.union(gc[i].getBounds());
}
}
Toolkit имеет ряд классов, которые помогли бы:
В итоге мы используем 1 и 2, чтобы вычислить максимальный размер окна. Чтобы получить соответствующую GraphicsConfiguration, мы используем
GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0].getDefaultConfiguration();
но могут быть более разумные решения с несколькими мониторами.
OP, вероятно, хотел что-то вроде этого:
Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
Toolkit.getDefaultToolkit().getScreenSize().getWidth()
Вы можете получить его с помощью AWT Toolkit.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Если вам требуется разрешение экрана, на который в данный момент назначен определенный компонент (на этом экране видна большая часть корневого окна), вы можете использовать этот ответ.
Хороший способ определить, находится ли что-либо в пределах визуальных границ, использует
Screen.getScreensForRectangle(x, y, width, height).isEmpty();
Это усовершенствование решения для нескольких мониторов, размещенного (выше) Лоуренсом Дол. Как и в его решении, этот код учитывает множество мониторов и вставки на панели задач. Включенные функции: getScreenInsets(), getScreenWorkingArea() и getScreenTotalArea().
Изменения в версии Лоуренса Дола:
код:
/**
* getScreenInsets, This returns the insets of the screen, which are defined by any task bars
* that have been set up by the user. This function accounts for multi-monitor setups. If a
* window is supplied, then the the monitor that contains the window will be used. If a window
* is not supplied, then the primary monitor will be used.
*/
static public Insets getScreenInsets(Window windowOrNull) {
Insets insets;
if (windowOrNull == null) {
insets = Toolkit.getDefaultToolkit().getScreenInsets(GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration());
} else {
insets = windowOrNull.getToolkit().getScreenInsets(
windowOrNull.getGraphicsConfiguration());
}
return insets;
}
/**
* getScreenWorkingArea, This returns the working area of the screen. (The working area excludes
* any task bars.) This function accounts for multi-monitor setups. If a window is supplied,
* then the the monitor that contains the window will be used. If a window is not supplied, then
* the primary monitor will be used.
*/
static public Rectangle getScreenWorkingArea(Window windowOrNull) {
Insets insets;
Rectangle bounds;
if (windowOrNull == null) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
insets = Toolkit.getDefaultToolkit().getScreenInsets(ge.getDefaultScreenDevice()
.getDefaultConfiguration());
bounds = ge.getDefaultScreenDevice().getDefaultConfiguration().getBounds();
} else {
GraphicsConfiguration gc = windowOrNull.getGraphicsConfiguration();
insets = windowOrNull.getToolkit().getScreenInsets(gc);
bounds = gc.getBounds();
}
bounds.x += insets.left;
bounds.y += insets.top;
bounds.width -= (insets.left + insets.right);
bounds.height -= (insets.top + insets.bottom);
return bounds;
}
/**
* getScreenTotalArea, This returns the total area of the screen. (The total area includes any
* task bars.) This function accounts for multi-monitor setups. If a window is supplied, then
* the the monitor that contains the window will be used. If a window is not supplied, then the
* primary monitor will be used.
*/
static public Rectangle getScreenTotalArea(Window windowOrNull) {
Rectangle bounds;
if (windowOrNull == null) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
bounds = ge.getDefaultScreenDevice().getDefaultConfiguration().getBounds();
} else {
GraphicsConfiguration gc = windowOrNull.getGraphicsConfiguration();
bounds = gc.getBounds();
}
return bounds;
}