在处理与使用这个类相关的东西时,我发现了这段代码:

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

我知道这个类是一个JLabel,可以使用标签进行渲染. 但是为什么在这个getter期间被初始化(如果不是)? 只是在构造函数上做这件事不是更有意义吗?

推荐答案

通过阅读source code

你可以看到一条解释这种行为的 comments :

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

Java相关问答推荐

查找最大子数组的和

CriteriaQuery with max

如何使用Java API在Oracle ODI中运行模拟?

H2弹簧靴试验跌落台

Java List with all combinations of 8 booleans

我无法将附件发送到NetBeans之外

如何使用AWS CLI从S3存储桶中的所有对象中删除用户定义的元数据?

不推荐使用的Environment.getExternalStorageDirectory().getAbsolutePath()返回的值不同于新的getExternalFilesDir(空)?

Spring Boot Maven包

相同的Java SerializedLambda为implMethodKind返回不同的结果

Java ArrayList的整数和数组的泛型

我的Spring Boot测试显示&IlLegalStateException:无法加载某事的ApplicationContext.

try 将JSON字符串响应从API转换为映射字符串、对象>;时出错

没有使用Lombok生成的参数

在settings.gradle.kts和Build.gradle.kts中使用公共变量

是否在settings.xml中使用条件Maven镜像?

STREAMS减少部分结果的问题

try 使用预准备语句占位符获取信息时出现Try-With-Resources错误

Java CDI:@Singleton@Startup@Inject无法实现接口

按长度排序字符串数组