SWT/JFace實(shí)踐:為Composite添加滾動(dòng)條效果(ScrolledComposite)
工作中一個(gè)任務(wù)是為一個(gè)已經(jīng)有的Composite添加滾動(dòng)條,原以為可以這樣實(shí)現(xiàn):Composite scrollabledComposite = new Composite(parent, SWT.H_SCROLL | SWT.V_SCROLL);
再設(shè)置一下其它的參數(shù)就可以了,誰(shuí)知這樣是可以添加滾動(dòng)條,但是滾動(dòng)條里的Composite根本不會(huì)跟著動(dòng);于是,查API,發(fā)現(xiàn)有ScrolledComposite這個(gè)類(lèi),好家伙,這個(gè)類(lèi)里的注釋連main () 方法都提供了,正點(diǎn)!
于是,我的代碼如下:
parentComposite.setLayout(new FillLayout());
ScrolledComposite scrolledComposite = new ScrolledComposite(parentComposite, SWT.H_SCROLL|SWT.V_SCROLL);
Composite mainComposite = new Composite(scrolledComposite,SWT.NONE);
scrolledComposite.setContent(mainComposite);
mainComposite.setBackground(Display.getCurrent().getSystemColor (SWT.COLOR_WHITE));// White color
mainComposite.setLayout(new GridLayout(1,true));
GridData data = new GridData(GridData.FILL_BOTH);
mainComposite.setLayoutData(data);
Composite topComposite = new Composite(mainComposite, SWT.BORDER);
topComposite.setLayout(new GridLayout(2, false));
topComposite.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));// White color
reloadBtn = new Button(topComposite, SWT.PUSH);
reloadBtn.setText("&Reload from preferences");
reloadBtn.setToolTipText("Reload values from preference page(Shift+R)");
saveBtn = new Button(topComposite, SWT.PUSH);
saveBtn.setText("&Save to preferences");
saveBtn.setToolTipText("save values to preference page(Shift+S)");
scrolledComposite.setExpandHorizontal(true);
scrolledComposite.setExpandVertical(true);
scrolledComposite.setMinWidth(800);
scrolledComposite.setMinHeight(400);
總結(jié):
1)在為Composite添加滾動(dòng)條時(shí),最上面的Composite的布局需設(shè)為FillLayout();
2) 不要直接往scrolledComposite上面添加控件;
3) 在創(chuàng)建完ScrolledComposite后不要忘記使用setContent()方法去設(shè)置滾動(dòng)條所控制的Composite;
4) 最重要的是,Scrolledcomposite的以下四個(gè)參數(shù)必須設(shè)置才能出現(xiàn)滾動(dòng)條:
scrolledComposite.setExpandHorizontal(true);
scrolledComposite.setExpandVertical(true);
scrolledComposite.setMinWidth(800);
scrolledComposite.setMinHeight(400);
只有前兩項(xiàng)設(shè)為true之后,后面的兩項(xiàng)才起作用。
5) 對(duì)于setMinWidth()和setMinHeight()方法,API的注釋中是說(shuō)用來(lái)設(shè)置滾動(dòng)條出現(xiàn)的最小寬度和高度,但是我試了一下,有時(shí)出現(xiàn)滾動(dòng)條了,
但是拖動(dòng)滾動(dòng)條還是不能顯示Composite里面的全部?jī)?nèi)容,于是把setMinWidth()和setMinHeight()設(shè)大一些就可以了,個(gè)人感覺(jué)滾動(dòng)條出現(xiàn)的
寬度和高度檢測(cè)Scrolledcomposite自己已經(jīng)實(shí)現(xiàn)了,這里的寬度和高度是指拖動(dòng)滾動(dòng)條里可以看到的Composite的最大寬度和最大高度。
posted on 2007-10-31 09:07 liaojiyong 閱讀(5132) 評(píng)論(3) 編輯 收藏 所屬分類(lèi): Eclipse