2010-08-15 56 views
2

時,我有一個JComponent,做自定義繪製,並覆蓋下列方法:強制一個JComponent是正方形被調整

public Dimension getPreferredSize() { 
    return new Dimension(imageWidth, imageHeight); 
} 

public Dimension getMinimumSize() { 
    return new Dimension(imageWidth, imageHeight); 
} 

凡imageWidth和imageHeight是圖像的實際大小。

我一直在使用SpringLayout中把它添加到內容窗格:

layout.putConstraint(SpringLayout.SOUTH, customComponent, -10, SpringLayout.SOUTH, contentPane); 
layout.putConstraint(SpringLayout.EAST, customComponent, -10, SpringLayout.EAST, contentPane); 
layout.putConstraint(SpringLayout.NORTH, customComponent, 10, SpringLayout.NORTH, contentPane); 

所以它被限制在北部和南部,使其將調整它的高度在調整大小時,東被限制在內容窗格的邊緣,但西部可以自由向左移動。

我希望它在調整大小時保持方形大小(寬度==高度)。任何人有任何想法如何做到這一點?

回答

3

最小/首選/最大尺寸只是佈局管理器的提示。要強制指定大小,您需要覆蓋組件中的大小處理。

所有調整大小/定位方法(setHeight,setLocation,setBounds等)最終會調用reshape。通過在組件中重寫此方法,可以強制組件爲方形。

void reshape(int x, int y, int width, int height) { 
    int currentWidth = getWidth(); 
    int currentHeight = getHeight(); 
    if (currentWidth!=width || currentHeight!=height) { 
     // find out which one has changed 
     if (currentWidth!=width && currentHeight!=height) { 
     // both changed, set size to max 
     width = height = Math.max(width, height); 
     } 
     else if (currentWidth==width) { 
      // height changed, make width the same 
      width = height; 
     } 
     else // currentHeight==height 
      height = width; 
    } 
    super.reshape(x, y, width, height); 
} 
+1

非常好,謝謝。雖然重塑似乎已被棄用,所以我會使用setBounds,但這是我正在尋找的方向。 – DanielGibbs 2010-08-16 03:44:34

+0

如果您重寫'setBounds'而不是重新塑形,則可能無法捕捉所有尺寸更改。即使它已被棄用,「重塑」是所有其他人委派的方法。 – mdma 2010-08-16 10:19:29