public class Frameextends Windowimplements MenuContainer
Frame
是帶有標題和邊界的頂層窗口。
frame 的大小包括邊界指定的所有區域。邊界區域的尺寸可以使用 getInsets
方法獲得,但是,由於這些尺寸是與平臺相關的,因此在通過調用 pack
或 show
將 frame 設置爲可顯示的之前,無法獲得有效的 insets 值。由於 frame 的總大小包括了邊界區,因此邊界有效地模糊了 frame 的部分區域,約束了可用於在矩形中呈現和/或顯示子部件的區域,矩形左上角的位置爲 (insets.left, insets.top)
,寬度爲 width - (insets.left + insets.right)
,長度爲 height - (insets.top + insets.bottom)
。
frame 的默認佈局爲 BorderLayout
。
使用 setUndecorated
,frame 可以關閉本機裝飾(例如 Frame
和 Titlebar
)。只有在 frame 不是 displayable
時才能完成此操作。
在多屏幕環境中,通過使用 Frame(GraphicsConfiguration)
或 Frame(String title, GraphicsConfiguration)
構造 Frame
,可以在不同的屏幕設備上創建 Frame
。GraphicsConfiguration
對象是目標屏幕設備的 GraphicsConfiguration
對象之一。
在虛擬設備多屏幕環境中(其中桌面區域可以跨越多物理屏幕設備),所有配置的邊界都是相對於虛擬座標系統的。虛擬座標系統的原點位於主物理屏幕的左上角。是否使用負座標,取決於主物理屏幕在虛擬設備中的位置,如下圖所示。
在此環境中,調用 setLocation
時,必須傳遞一個虛擬座標到此方法中。類似地,對 Frame
調用 getLocationOnScreen
將返回虛擬設備座標。調用 GraphicsConfiguration
的 getBounds
方法,以查找它在虛擬座標系統中的原點。
以下代碼將 Frame
的位置設置爲 (10, 10)(相對於相應的 GraphicsConfiguration
的物理屏幕的原點)。如果不考慮 GraphicsConfiguration
的邊界,則 Frame
的位置將被設置爲 (10, 10)(相對於虛擬座標系統),並出現在主物理屏幕上,主物理屏幕不同於指定的 GraphicsConfiguration
的物理屏幕。
Frame f = new Frame(GraphicsConfiguration gc); Rectangle bounds = gc.getBounds(); f.setLocation(10 + bounds.x, 10 + bounds.y); 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()); } }
Frame 能夠產生以下類型的 WindowEvent
:
WINDOW_OPENED
WINDOW_CLOSING
:
在處理事件時,如果程序沒有顯式地隱藏或移除窗口,則取消窗口關閉操作。WINDOW_CLOSED
WINDOW_ICONIFIED
WINDOW_DEICONIFIED
WINDOW_ACTIVATED
WINDOW_DEACTIVATED
WINDOW_GAINED_FOCUS
WINDOW_LOST_FOCUS
WINDOW_STATE_CHANGED
- 從以下版本開始:
- JDK1.0
- import java.awt.*;
- import javax.swing.*;
- /**
* @author bo.wang
*
*/
/**
* @author bo.wang
*
*/
public class HelloWorldSwing1 {
public static void main(String[] args) {
JFrame frame = new JFrame("HelloWorldSwing1");
//GraphicsConfiguration gc=GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
GraphicsDevice[] gs =
ge.getScreenDevices();
GraphicsDevice gd = gs[0];
GraphicsConfiguration[] gcall =
gd.getConfigurations();
GraphicsConfiguration gc=gcall[0];
System.out.println(gc.toString());
Frame f = new Frame(gc);
Rectangle bounds = gc.getBounds();
f.setLocation(1000 + bounds.x, 1000 + bounds.y);
final JLabel label = new JLabel("Hello World1");
frame.getContentPane().add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();//縮緊所有組件,使初始打開頁面時即可顯示所有的組件
frame.setVisible(true);
}
}