2015-03-19 21 views
0

將窗口的長度設置爲正確的長度使用這個類和這個主要方法,我試圖使它在運行主類時創建的窗口的大小適合保存所有的傳遞給它的圖標,而不必調整窗口的大小,並且不需要將值初始化時我的窗口大小需要硬編碼。使用圖標

現在,當它運行時,窗口開始變得非常小,當我調整它時,所有被繪製到它上面的圖標的佈局都搞亂了。

我知道如何確定它應該是正確的大小,但我不知道如何知道如何使用座標ArrayList是如何確定大小,但我不知道如何改變窗口的大小在它已經被初始化之後。

public class CompositeIcon implements Icon 
{ 


ArrayList<Icon> iList; 
static int width; 
    static int height; 
    ArrayList<Point> coordinates; 

public CompositeIcon() 
{ 
    iList = new ArrayList<Icon>(); 
    coordinates = new ArrayList<Point>(); 
} 



public int getIconHeight() 
{ 
    return height; 
} 


public void addIcon(Icon icon, int x, int y) 
{ 
    iList.add(icon); 
    coordinates.add(new Point(x, y)); 

} 



public int getIconWidth() 
{ 
    return width; 
} 


public void paintIcon(Component c, Graphics g, int x, int y) 
{ 
    int i = 0; 
    for (Icon s : iList) 
    { 
    Point offset = coordinates.get(i++); 
    s.paintIcon(c, g, x + offset.x, y + offset.y); 
    } 

} 

這是主要的,以測試它

public static void main (String args[]) { 
    JFrame frame = new JFrame(); 
    Container panel = frame.getContentPane(); 
    panel.setLayout(new BorderLayout()); 
    CompositeIcon icon = new CompositeIcon(); 
try { 
    icon.addIcon(new ImageIcon(new URL("http://th02.deviantart.net/fs71/150/f/2013/103/2/7/java_dock_icon_by_excurse-d61mi0t.png")), 10, 10); 
    icon.addIcon(new ImageIcon(new URL("http://www.bravegnu.org/blog/icons/java.png")), 5, 370); 
    icon.addIcon(new ImageIcon(new URL("http://fc03.deviantart.net/fs20/f/2007/274/9/8/3D_Java_icon_by_BrightKnight.png")), 200, 200); 

    } 

    catch (MalformedURLException e) { 
    System.err.println("Apparently, somebody cannot type a URL"); 
    } 
    panel.add(new JLabel(icon)); 
    frame.pack(); 
    frame.setVisible(true); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 



} 

回答

2

基本上,widthCompositeIconheight應該代表添加的圖標的組合的寬度和高度的(允許的x/y的偏移量)

喜歡的東西...

public void addIcon(Icon icon, int x, int y) { 
    iList.add(icon); 
    width = Math.max(width, x + icon.getIconWidth()); 
    height = Math.max(height, y + icon.getIconHeight()); 
    coordinates.add(new Point(x, y)); 
} 

你將需要刪除的static declearations爲widthheightCompositeIcon每個實例應該有它自己的widthheight

CompositeIcon

+0

該死的是這一切嗎?萬分感謝! – user1210304 2015-03-19 05:38:37

+0

那麼,這是一種方法;) – MadProgrammer 2015-03-19 05:39:00

1

你的方法允許圖標隨機定位,但它意味着你有責任瞭解每個圖標的大小並定位它們,使其不相互重疊。

如需更結構化的方法,可以查看Compound Icon。該類支持垂直,水平和堆疊的Icon對齊,併爲您執行所有位置/大小計算。