2010-04-01 19 views
0

我有一個面板,我試圖從中刪除它添加到它的標籤在運行時。 但是當標籤成功移除時,我無法使用該標籤留下的空間,再次向其中添加任何標籤。如何從容器中刪除任何組件時重用容器中的區域?

感謝預期的解決方案。

這裏是有關的代碼片段:

  1. 標註添加到面板:

    JLabel jl = new JLabel(); 
    jl.setOpaque(true); 
    jl.setIcon(new ImageIcon("D:/Project/router2.jpg")); 
    jl.setBounds(x, y, jl.getPreferredSize().width, 
        jl.getPreferredSize().height); 
    for (Component c : lcomponent) { 
        flag = true; 
        Rectangle r4 = c.getBounds(); 
        int x1 = (int) r4.getX(); 
        int y1 = (int) r4.getY(); 
        Rectangle r5 = new Rectangle(
         new Point(x1 - 60, y1 - 60), new Dimension(170, 170)); 
        if (r5.contains(p)) { //To ensure that two labels do not overlap 
         flag = false;  //or are too close to each other 
         break; 
        } 
    } 
    if (flag) { 
        p2.add(jl); //p2 is a panel 
        Component c2 = p2.getComponentAt(x, y); 
        p2.repaint(); 
        lcomponent.add(c2); //lcomponent is an ArrayList<Component> to 
             //store all the labels added to the panel 
    } 
    
  2. 去除標籤:

    p2.remove(<label name>); 
    p2.repaint(); 
    

我甲肝嘗試revalidate()也,但我不知道它爲什麼它自動將頂部的一行 中的組件對齊。

幫我這也

+0

我已經重新格式化了您的代碼;如果不正確請回復。 – trashgod 2010-04-01 18:19:56

回答

3

呼叫Container.invalidate()

+0

它沒有工作...我仍然無法使用該區域。 – userv 2010-04-01 20:06:29

+0

我剛剛意識到你正在定位你的標籤,但你不會說容器的佈局。它看起來像你有一個佈局管理器,調用Container.setLayout(null)來刪除它。 – 2010-04-02 00:40:46

1

從可見幀添加/刪除組件,你應該使用後:

//panel.add(...); 
panel.remove(...); 
panel.revalidate(); 
panel.repaint(); 
+0

我試過重新驗證(),但它在一行頂部對齊組件 – userv 2010-04-01 20:00:43

+0

這是正確的。這是佈局經理的工作方式。 JPanel的默認佈局管理器是FlowLayout,它將組件放在一行中。如果您正在嘗試實現其他佈局,那麼您需要使用不同的佈局管理器。閱讀使用佈局管理器的Swing教程中的部分:http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html。您可能會認爲最初不使用佈局管理器會更簡單,但如果您不這樣做,以後總會遇到問題。 – camickr 2010-04-02 00:43:18

+0

確定這是正確的,但我試圖在隨機位置添加組件。 我不認爲你可以使用任何佈局管理器,它必須設置爲null。 – userv 2010-04-02 06:41:25

0

我想我得到了答案。實際上在刪除組件時,我是從面板中刪除它,但不是從arraylist(lcomponent和上面的標籤),因爲我無法再使用該區域來放置任何其他組件。從列表中刪除條目對我有用。