right錛堝彲閫夛級銆乥ottom錛堝彲閫夛級甯冨眬綰︽潫鍙互瀵圭粍浠惰繘琛岀簿紜畾浣嶃傜劧鑰屾湁浜涚粍浠跺湪涓氬姟涓婃槸鏈夊浐瀹氬昂瀵哥殑錛屼緥濡?a title="鑷畾涔夌粍浠朵箣Button" href="http://www.aygfsteel.com/javagui/archive/2007/11/11/javagui.html">鑷畾涔夌粍浠朵箣Button浠嬬粛鐨勪竴鏍鳳紝閫氳繃緇欐寜閽寚瀹?縐嶇姸鎬佹椂鐨勫浘鐗囷紝閭d箞緇勪歡鐨勬渶浣沖昂瀵稿氨鏄浘鐗囩殑灝哄錛屽洜姝ょ粍浠剁殑PreferredSize灝卞彲浠ョ‘瀹氾紝鎵浠ユ鏃跺彧闇瑕佺粍浠?span style="color: red;">涓績鐨勭‘瀹氬潗鏍囧氨鍙互浜嗭紝瀹為檯緇勪歡鐨凩ocation鍙拰鍏禤referredSize鏈夊叧銆傚涓嬪浘鎵紺猴細
榪欏氨鏄疌enterLayout鐨勬濇兂銆?/p>
淇敼FormData錛屽彧闇瑕佹坊鍔犱袱涓彉閲忓嵆鍙?br />
public final class FormData {
public FormAttachment left;
public FormAttachment right;
public FormAttachment top;
public FormAttachment bottom;
public FormAttachment centerX;
public FormAttachment centerY;
}
CenterLayout涓嶧ormLayout涓嶅悓鍙湪浜巃ddLayoutComponent銆乴ayoutContainer榪欎袱涓?/p>
鏂規硶瀹炵幇錛屽叾浠栨帴鍙f柟娉曞潎鐩稿悓錛屾墍浠ヤ笅闈㈠彧浠嬬粛榪欎袱涓柟娉曞疄鐜幫紝鍏朵粬鎺ュ彛鏂規硶璇?/p>
鍙傞槄涓婃枃鑷畾涔夊竷灞綆$悊鍣?FormLayout
鍦╝ddLayoutComponent鏂規硶鐨勫紑澶達紝鍚屾牱鏄甯冨眬綰︽潫鍙傛暟constraints鍚堟硶鎬ц繘琛屾鏌ワ紝榪欑偣涓嶧ormLayout澶ц嚧鐩稿悓銆?/p>
if (constraints == null) {
throw new IllegalArgumentException("constraints can't be null");
} else if (!(constraints instanceof FormData)) {
throw new IllegalArgumentException("constraints must be a " + FormData.class.getName() + " instance");
} else {
synchronized (comp.getTreeLock()) {
FormData formData = (FormData) constraints;
if (formData.centerX == null || formData.centerY == null) {
throw new IllegalArgumentException("centerX FormAttachment and centerY FormAttachment can't be null");
} else if (comp.getPreferredSize() == null) {
throw new RuntimeException("component must have preferred size before be add into parent with CenterLayout");
}
componentConstraints.put(comp, (FormData) constraints);
}
}
瀵逛簬CenterLayout鏉ヨ錛孎ormData瀵硅薄鐨刢enterX銆乧enterY蹇呴』緇欏嚭錛屽洜涓哄畠浠h〃錛岀偣鐨勫潗鏍囷紝闄ゆ涔嬪緇勪歡蹇呴』鏈塒referredSize灞炴ф潵鎸囧畾緇勪歡澶у皬銆?/p>
layoutContainer鏂規硶瀹炵幇涔熷ぇ鑷寸浉鍚?br />
public synchronized void layoutContainer(Container target) {
synchronized (target.getTreeLock()) {
int w = target.getWidth();
int h = target.getHeight();
Component[] components = target.getComponents();
for (Component comp : components) {
FormData formData = componentConstraints.get(comp);
if (formData != null) {
...
}
}
}
}
涓婇潰榪欐涓嶧ormLayout涓鏍楓傚叧閿湪if璇彞鍧楀唴錛屼唬鐮佸涓嬶細
FormAttachment centerX = formData.centerX;
FormAttachment centerY = formData.centerY;
int width = component.getPreferredSize().width;
int height = component.getPreferredSize().height;
int x = (int) (centerX.percentage * w) + centerX.offset - width / 2;
int y = (int) (centerY.percentage * h) + centerY.offset - height / 2;
comp.setBounds(x, y, width, height);
鑾峰緱centerX銆乧enterY浠ュ強鏈浣沖昂瀵革紝濡備笂鍥炬墍紺猴紝涓嶉毦寰楀嚭x銆亂鐨勮綆楁柟娉曘?br />
鑷蟲錛岃嚜瀹氫箟甯冨眬綆$悊鍣ㄥ氨浠嬬粛鍒拌繖閲岋紝榪欎袱涓竷灞綾誨彲浠ヨВ鍐沖緢澶?span style="color: red;">闈欐佸竷灞闇姹傦紝鎵璋撻潤鎬佸竷灞鏄寚瀹瑰櫒鍐呮湁浠涔堢粍浠舵槸鍥哄畾鐨勩傚鏋滈亣鍒板姩鎬佺晫闈紝渚嬪緇勪歡鐨勫唴瀹逛緷鐓х敤鎴風駭鍒佹彃浠舵墿灞曠偣絳夊洜绱犲喅瀹氾紝涔熷茍涓嶆槸闅句簨錛屽洜涓轟簡瑙d簡甯冨眬綆$悊鍣ㄨ繍琛屾満鍒朵互鍚庡彲寰堝鏄撳湴瀹氫箟閫傚悎浣犻渶姹傜殑甯冨眬綾匯傚浜庨潤鎬佸竷灞鏉ヨ錛屼綘鍙兘鍘屽︿簡hard coding鏉ュ竷灞錛屼綘甯屾湜榪欎竴鍒囩敱xml榪欐牱鐨勯厤緗悶瀹氾紝濂斤紝涓嬩竴閮ㄥ垎鍒欏紑濮?#8220;鍘嬭醬鎴?#8221;——鐢ㄩ厤緗枃浠惰В鍐沖竷灞銆?/p>