Code example for JLabel

Methods: setSizegetPreferredSizesetText

0
   JLabel label;
   public SikuliGuideText(String text){         
      super(); 
      this.text = text;
 
      label = new JLabel();
      add(label);
 
      setMaximumWidth(DEFAULT_MAXIMUM_WIDTH);
      updateLabel();       
   } 
 
   public void setMaximumWidth(int max_width){
      this.max_width = max_width;
      updateLabel(); 
      updateSize(); 
   } 
       
   public void setText(String text){
      this.text = text;
      updateLabel(); 
   } 
    
   public String getText(){
      return text;
   } 
   void updateLabel(){ 
 
      String htmltxt = 
         "<html><div style='" + getStyleString() + "'>" 
         + text + "</div></html>";
      label.setText(htmltxt);
 
      Dimension size = label.getPreferredSize();
      if (size.width > max_width){
         // hack to limit the width of the text to width 
         htmltxt = 
            "<html><div style='width:" + max_width + ";" + getStyleString() + "'>"
            + text + "</div></html>";
         label.setText(htmltxt);
      } 
      updateSize(); 
   } 
 
   void updateSize(){ 
      Dimension size = label.getPreferredSize();
      label.setSize(size);
      setActualSize(size);
   } 
 
 
   int fontSize = 12;