Java技巧之在屏幕上定位窗口

 

Java Abstract Window Toolkit(AWT)的Window.setLocation函数为开发人员提供了一个条理清晰的方法来解决在用户屏幕上定位一个窗口的问题。但用这个方法就必须考虑精确的象素点,这就很麻烦,而用一个类似于java.awt.BorderLayout的系统就要好的多。

在BorderLayout中,各部分都是由下面这几个区域函数之一定位的:

BorderLayout.NORTH

BorderLayout.SOUTH

BorderLayout.CENTER

BorderLayout.WEST

BorderLayout.EAST

下面的代码用几乎相同的方法在屏幕上定位了一个窗口。它首先确定了五个固定的位置,然后用屏幕大小和窗口大小来定位一个窗口。

package com.generationjava.awt;

import java.awt.Dimension;

import java.awt.Window;

public final class WindowUtilities {

// ints used so a case-switch statement can be used.

static public final int TOP = 0;

static public final int BOTTOM = 1;

static public final int CENTER = 2;

static public final int LEFT = 3;

static public final int RIGHT = 4;

/**

* Position the given window on the screen at the given location,

*

* @param w Window to position

* @param x int horizontal position

* @param y int vertical position

*/

static public void positionWindowOnScreen(Window w, int x, int y) {

Dimension scrn = w.getToolkit().getScreenSize();

Dimension win = w.getSize();

int nx = 0;

int ny = 0;

switch(x) {

case LEFT: nx = 0; break;

case CENTRE: nx = (int)((scrn.width-win.width)/2); break;

case RIGHT: nx = (int)(scrn.width-win.width); break;

}

switch(y) {

case TOP: ny = 0; break;

case CENTRE: ny = (int)((scrn.height-win.height)/2); break;

case BOTTOM: ny = (int)(scrn.height-win.height); break;

}

w.setLocation(nx,ny);

}

}

要确定一个窗口的右下角的位置,就要执行下面的代码:

Window window = ….

WindowUtilities.positionWindowOnScreen(window,_

WindowUtilities.RIGHT, WindowUtilities.BOTTOM);

该方法还可以进行扩展。你可以增加一个简单的centerWindowOnScreen函数,该函数调用了positionWindowOnScreen函数。例如:

static public final void centerWindowOnScreen(Window w)

{

positionWindowOnScreen(w, CENTER, CENTER);

}

这两个函数简化了在AWT和Swing中所做的工作,使开发人员可以将更多的时间用在开发用户界面上。

评论关闭。