在Java Swing的编程中,JFrame是最重要的组件之一。在Java中的继承关系如下:
java.lang.Object java.awt.Component java.awt.Container java.awt.Window java.awt.Frame javax.swing.JFrame
http://download.oracle.com/javase/6/docs/api/
以上是Java Swing的API地址。
Swing组件从功能分可以分成三种,分别是顶层组件,中间组件和基本组件。JFrame就是顶层组件,简单的描述也就是Windows组件,可以独立显示的组件。而中间组件是可以充当载体,但是不能独立显示的组件,可以把基础组件放在其中,但是还是要依托在顶层容器内才可以显示。基础组件则是实现人机交互的基本组件。后面会陆续提到。
JFrame一共有四种构造方式,分别是:
JFrame() Constructs a new frame that is initially invisible. |
JFrame(GraphicsConfiguration gc) Creates a Frame in the specified GraphicsConfiguration of a screen device and a blank title. |
JFrame(String title) Creates a new, initially invisible Frame with the specified title. |
JFrame(String title, GraphicsConfiguration gc) Creates a JFrame with the specified title and the specified GraphicsConfiguration of a screen device. |
需要说明的是:
JFrame(GraphicsConfiguration gc)
以屏幕设备的指定 GraphicsConfiguration 和空白标题创建一个 Frame。
GraphicsConfiguration()
这是一个不可直接实例化的抽象类。
在虚拟设备多屏幕环境中(其中桌面区域可以跨越多个物理屏幕设备),GraphicsConfiguration 对象的边界与虚拟坐标系统相关。当设置组件的位置时,使用 getBounds 来获得所需 GraphicsConfiguration 的边界和 GraphicsConfiguration 坐标位置的偏移量,以下代码示例给出了说明:
Frame f = new Frame(gc); // where gc is a GraphicsConfiguration
Rectangle bounds = gc.getBounds();
f.setLocation(10 + bounds.x, 10 + bounds.y); 要确定您的环境是否为虚拟设备环境,可以对系统中的所有 GraphicsConfiguration 对象调用 getBounds。如果所有返回的边界原点都不是 (0, 0),则您的环境为虚拟设备环境。
说实话,在API看到这段代码没有太看懂。在我日常的使用中基本上只使用和JFrame()和JFrame(String title)两个构造函数。所以,就不详细解释关于有gc的构造函数了。下次有空了去仔细研究研究。
例子1:JFrame()
import javax.swing.JFrame;
public class JFrameTest {
JFrameTest(){
JFrame jFrame = new JFrame();
jFrame.setSize(200, 100);
jFrame.setVisible(true);
}
public static void main(String[]args)
{
new JFrameTest();
}
}
运行结果是在屏幕的左上角出现了这个一个框框。
如果我们将上面的构造函数改成 JFrame jFrame = new JFrame("This is a JFrame");则会出现如下窗口。
从下次开始,我讲开始着手写JFrame的其他函数调用和方法。