how to reuse the area in a container when any component is removed from it?
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.
tha开发者_开发知识库nks in anticipation of the solution.
here is the relevant code snippet:
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 }
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
Call Container.invalidate()
After adding/removing components from a visible frame you should use:
//panel.add(...);
panel.remove(...);
panel.revalidate();
panel.repaint();
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.
精彩评论