Reputation: 1142
I have JLabel with an icon and text. Is there any possibility to hide only JLabel's text? I don't want to hide whole component (setVisible(false)), but only text, so an icon remains visible. I'd like to still use getText and setText methods.
Thanks for Your help!
Upvotes: 1
Views: 8765
Reputation: 21
Easiest way would be to just set the font to 0!! Try it out. works fine.
label.setFont(new java.awt.Font("Lucida Grande", 1, 0));
Upvotes: 0
Reputation: 31
I also faced the same problem and my workaround was to simply use the setName()
and getName()
methods in place of the setText()
and getText()
methods. Hope it will help. The problem with setToolTipText()
is that the tool tip is displayed on mouse hover.
Upvotes: 3
Reputation: 516
I just encountered this problem today.
My JLabel has an icon and I needed only the icon to be displayed. I had a MouseListener and for that I required the text of the label to uniquely identify the label.
My workaround was to use setToolTipText()
instead of setText()
and use getToolTipText()
instead of getText()
in the MouseListener.
Upvotes: 0
Reputation: 2953
As far as I'm concerned, there's no direct way to do this. But you could try some of the following:
Here's an example of what I mean:
public class MyLabel extends JLabel {
private String labelText;
private boolean labelTextVisible = true;
private MyLabel( String text, Icon icon, int horizontalAlignment ) {
super( text, icon, horizontalAlignment );
labelText = text;
}
private MyLabel( String text, int horizontalAlignment ) {
super( text, horizontalAlignment );
labelText = text;
}
private MyLabel( String text ) {
super( text );
labelText = text;
}
@Override
public void setText( String text ) {
if ( labelTextVisible ) {
super.setText( text );
}
labelText = text;
}
@Override
public String getText() {
return labelText;
}
public void setLabelTextVisible( boolean labelVisible ){
if(labelVisible){
if(!labelText.equals( super.getText() )){
super.setText( labelText );
}
}else{
int spaceCount = super.getText().length();
String hiddenText = "";
for ( int i = 0; i < spaceCount; i++ ) {
hiddenText+=" ";
}
super.setText(hiddenText);
}
this.labelTextVisible = labelVisible;
}
public boolean getLabelTextVisible(){
return labelTextVisible;
}
}
Upvotes: 2
Reputation: 2606
Is this too obvious?
label.setText("");
If you really just want to hide it, you could set the foreground color to be the same as the background. Maybe that would suffice (and might be necessary to prevent the icon from moving, depending how you have the alignment set).
Upvotes: 4