2010-03-15 90 views
0

我將我的JPanel設置爲GridLayout(6,6),尺寸爲(600,600) 網格中的每個單元格將顯示具有不同寬度和高度的一張圖片。 圖片首先添加到JLabel,然後將JLabel添加到單元格中。如何獲取Gridlayout的座標

如何檢索單元格中圖片的座標而不是單元格的座標?到目前爲止,即使在屏幕上,也給出了這些等高和寬相同的座標,不同大小的圖片顯示出來。

例如

java.awt.Rectangle[x=100,y=100,width=100,height=100] 
java.awt.Rectangle[x=200,y=100,width=100,height=100] 
java.awt.Rectangle[x=300,y=100,width=100,height=100] 

我之所以用GridLayout代替gridBagLayout是因爲我希望每個圖片都有邊界。如果我使用GridBagLayout,網格將根據圖片大小進行擴展。 我希望網格大小處於固定大小。

JPanel pDraw = new JPanel(new GridLayout(6,6)); 
pDraw.setPreferredSize(new Dimension(600,600)); 

for (int i =0; i<(6*6); i++) 
{   
    //get random number for height and width of the image 
    int x = rand.nextInt(40)+(50); 
    int y = rand.nextInt(40)+(50); 

    ImageIcon icon = createImageIcon("bird.jpg");  

    //rescale the image according to the size selected 
    Image img = icon.getImage().getScaledInstance(x,y,img.SCALE_SMOOTH);   
    icon.setImage(img); 
    JLabel label = new JLabel(icon); 
    pDraw.add(label);  
} 

for(Component component:components) 
{ 
    //retrieve the coordinate 
    System.out.println(component.getBounds()); 
} 

編輯:我已經試過,但沒有工作:-(

for(Component component: pDraw.getComponents()){ 
    System.out.println(((JLabel)component).getIcon()); 
} 

我怎樣才能得到這樣的

java.awt.Rectangle[x=300,y=100,width=50,height=40] 
java.awt.Rectangle[x=400,y=400,width=60,height=50] 

回答

1

輸出做你的圖像出現在所需的大小?

我這麼認爲

無論如何,從你的代碼似乎做的事情來看,我想它會得到標籤的大小,而不是圖標的大小。像任何JComponent一樣,JLabel實際上是Container實例。因此,它們的大小取決於約束條件。因此,在GridLayout中,JLabel將具有單元的大小,而包含的圖標將具有圖像的大小。

作爲一個後果,要獲取圖像大小,必須調用((JLabel) component).getIcon()才能檢索有效的圖像尺寸。