Search code examples
javaswinghidejlabel

JLabel - how to hide a text?


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!


Solution

  • As far as I'm concerned, there's no direct way to do this. But you could try some of the following:

    1. Extend JLabel and override the setText() and getText() methods. These should store the text you give it in a new String field. Every time you call setText it should only delegate to super.setText() is your label-text is not invisible. Then you could add a method that switches visibility. If you call setTextVisibility() with true, the class should call super.setText() with a string of spaces.

    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;
        }
      }
    
    1. (This is more of a hack, but it could work) Make the foregroundcolor of the label match the background color so the text is no longer visible.