tags:

views:

38

answers:

3

hi! i hav a panel and i m trying to remove labels from it which were added to it during run-time. but when labels are removed succesfully i m not able to use the space,left by that label,again to add any label to it.

thanks in anticipation of the solution.

here is the relevant code snippet:

  1. to add label to the panel:

    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. to remove the label:

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

i hav tried revalidate() also but i dont know why it automatically aligns the components in a row at the top.

help me with this also

+3  A: 

Call Container.invalidate()

adrian.tarau
it didn't work...i stil cant use that area.
I just realized you are positioning your labels but you don't say anything about the container's layout. It looks like you have a layout manager, call Container.setLayout(null) to remove it.
adrian.tarau
+1  A: 

After adding/removing components from a visible frame you should use:

//panel.add(...);
panel.remove(...);
panel.revalidate();
panel.repaint();
camickr
i tried revalidate() but it aligned the components at the top in a row
Thats correct. That is the way layout managers work. The default layout manager for a JPanel is the FlowLayout which lays out components in a row. If you are trying to achieve some other layout then you need to use different layout managers. Read the section from the Swing tutorial on Using Layout Managers: http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html. You may think it is simpler to not use a layout manager at first, but you will always encounter problems later if you don't.
camickr
ok thats correct.but i m trying to add components at random locations.i dont think u can use any layout manager for this,it has to be set to null.
A: 

hi!!!

i think i got the answer.actually while removing the component,i was removing it from the panel but not from the arraylists(lcomponent and label above) because of which i was not able to use that area again to put any other component.removing the entry from lists worked for me.