Sharon Watinsan
Sharon Watinsan

Reputation: 9850

How to Hide or remove a JLabel

I have declared a JLable as follows;

l = new JLabel("Hello");
l.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(l);

Now, i want to hide or remove it. What should be the method i should call ?

i tried l.removeAll(); <--- nothing hapend.

there's another one calle remove(int) which takes an int. But i am not sure what to pass as the parameter.

There's also something called hide(). but it's deprecated.

Upvotes: 6

Views: 26489

Answers (7)

Eloy M
Eloy M

Reputation: 1

You have to use the method getContentPane(). This way is possible to remove the element by the declaration name of the component.

private JFrame frame;
private JLabel label;
...

frame.getContentPane().remove(label);

Upvotes: 0

Javatech
Javatech

Reputation: 23

I faced the same problem in my project.

You should make sure about removing previous controls and refreshing the panel.

see this snippet code :

panel.removeAll();  


panel.revalidate();  

Hope This Helps U All The Best :)

Upvotes: 0

Nikolay Kuznetsov
Nikolay Kuznetsov

Reputation: 9579

i tried l.removeAll(); <--- nothing hapend.

you need to call to remove on JPanel which the JLabel was added to :

panel.remove(l);

//after that you need to call this to revalidate and repaint the panel
panel.revalidate(); 
panel.repaint();

just to hide and not to remove call

l.setVisible(false);

Upvotes: 12

Shantanu Banerjee
Shantanu Banerjee

Reputation: 1447

This may help you

Hiding Label

l.setVisible(false);

Removing from parent with passing the Label object as argument

panel.remove(l);

Remove all components

panel.removeAll();

Upvotes: 3

vishal_aim
vishal_aim

Reputation: 7854

you can try:

setVisible(false)

Upvotes: 2

gogognome
gogognome

Reputation: 759

Try panel.remove(l);

panel.removeAll() should also work, but that also removes other components which may have been added to the pannel.

Upvotes: 2

Kai
Kai

Reputation: 39651

The javadoc of hide() tells setVisible() should be used instead. So try calling setVisible(false).

Upvotes: 1

Related Questions