FX窗体框架:Stage、Scene与Node

这是一个将窗口与按钮关系的文章

理论

FX中控件不是直接在窗体上的,而是通过中间一层Scene连接。整体基本结构就是Stage包裹Scene,Scene上面放控件。但是控件一般有多个,所以就有一个布局问题,这时候就会多出一个布局的东西——Group,所以结果就是将Group的对象作为了根节点,其他控件放在Group上面。由此可以知道一般的结构为Stage包裹Scene,Scene上面放Group确认布局方式,Group添加各个控件。

代码

逻辑就是上面那样了,所以先看具体实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub

Button button= new Button("button");
button.setPrefWidth(80);
button.setPrefHeight(80);

Group gr=new Group();
gr.getChildren().add(button);

Scene sc=new Scene(gr);

primaryStage.setScene(sc);

primaryStage.setWidth(500);
primaryStage.setHeight(300);
primaryStage.setTitle("primaryStage TITLE");

primaryStage.show();
}

代码实现顺序也是如此,先创建控件对象new Button("button"),然后创建布局对象new Group()再使用gr.getChildren().add()添加控件对象,在new Scene时将布局对象放入构造方法中,最后Stage对象调用setScene方法设置Scene,整个过程完成。要注意的是虽然可以直接将控件传给Scene,但是那样的话控件作为根节点就不能设置大小(设置也无效),会默认铺满窗口。

其它

打开网页的实现

1
2
3
4
//打开网页使用默认浏览器
HostServices host=getHostServices();
host.showDocument("http://cn.bing.com");