How to Hide or remove a JLabel

安稳与你 提交于 2019-12-10 15:26:39

问题


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.


回答1:


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);



回答2:


Try panel.remove(l);

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




回答3:


you can try:

setVisible(false)



回答4:


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();



回答5:


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




回答6:


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 :)




回答7:


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);


来源:https://stackoverflow.com/questions/13859348/how-to-hide-or-remove-a-jlabel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!