FormLayout是SWT里面的一种layout管理方法.熟练掌握了FormLayout就能够排版出随心所欲的版面风格.
一、FormLayout最最简单的应用
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.SWT;
public class FormLayoutSimple {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FormLayout());
new Button(shell, SWT.PUSH).setText("Button");
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
其展现效果为:
可以通过设置marginheight和marginwidth来调整button的位置
FormLayout layout = new FormLayout();
layout.marginHeight = 5;
layout.marginWidth = 10;
shell.setLayout(layout);
这个是直接改变layout的位置,展现效果为:
我们可以通过定义FormData,通过设置FormData对象的high和width属性的大小来改变button的形状:
Button button = new Button(shell, SWT.PUSH);
button.setText("Button");
FormData data = new FormData();
data.height = 50;
data.width = 50;
button.setLayoutData(data);
展现为:
二、重要的FormAttachment
attachment:附件,附属的意思.直接地表达了贴,附着的含义,也是FormLayout中最重要的一个对象类.
FormAttachment的理论依据是y = ax + b; a为斜率,b为位移.从新定义a = m/n ,则我们可以看到最完成的FormAttachment构造函数:FormAttachment(m,n,b);其中m/n在[0,1]的范围中,n!=0,
FormAttachment有5个构造函数,他们分别为:
//组件附着
FormAttachment(Control control) ;//将组件附着到control
FormAttachment(Control control, int offset) ;
FormAttachment(Control control, int offset, int alignment) ;
//数字定位
FormAttachment(int n) ; <==>FormAttachment(int n,100) ;<==>FormAttachment(int n,100,0) ;
FormAttachment(int n, int b) ;<==>FormAttachment(int n,100, int offset) ;FormAttachment(int n, int m, int offset) ;
要使用FormAttachment,就必须和FormData紧密结合使用:
FormData有好几个属性分别为:height,width,top,bottom,left,right:
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.SWT;
public class FormLayoutSimple {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
FormLayout layout = new FormLayout();
shell.setLayout(layout);
Button button = new Button(shell, SWT.PUSH);
button.setText("Button");
FormData data = new FormData();
data.height = 50;
data.width = 50;
data.right = new FormAttachment(100, -50);//<==>FormAttachment(100,100,-50)
//注意上面的代码:right:表示以屏幕的右边况为基线,n=100,m=100,b=-50如果屏幕是800*600大小,我们可以知道该按狃的位置:y = n/m * x + b =>y = x - 50 ,x=800,=>y = 750,所以,按狃的右边框靠近右边屏幕始终是50pix
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
拉伸后,靠近右边50pix
以上方法对data.left,data.top,data.bottom一样通用