Search code examples
javaswingjava-17renderer

Why BasicComboBoxRenderer sets the text two times if the text does not exist or is empty with getPreferredSize()?


While working on something related on using this class, i found this piece of code:

public Dimension getPreferredSize() {
    Dimension size;
    if (this.getText() == null || this.getText().isEmpty()) {
         setText( " " );
         size = super.getPreferredSize();
         setText( "" );
    } 
     else {
         size = super.getPreferredSize();
    }
    return size;
}

I do understand that this class is a JLabel and can use labels for rendering. But why is being initialized (in case is not) during this getter? Wouldn't make more sense on just doing it on the constructor?


Solution

  • By reading the source code

    you can see a comment explaining such behavior:

      76:   /**
      77:    * Returns preferredSize of the renderer
      78:    * 
      79:    * @return preferredSize of the renderer
      80:    */
      81:   public Dimension getPreferredSize()
      82:   {
      83:     if (this.getText() != null && ! this.getText().equals(""))
      84:       return super.getPreferredSize();
      85:     else
      86:       {
      87:         // If the combo box option's text is empty or null, it won't size
      88:         // properly (ie, it'll be way too short)... so we throw in a dummy
      89:         // space to trick the superclass's sizing methods.
      90:         String oldText = this.getText();
      91:         this.setText(" ");
      92:         Dimension d = super.getPreferredSize();
      93:         this.setText(oldText);
      94:         return d;
      95:       }
      96:   }