Test for Label overrun

前端 未结 4 2405
慢半拍i
慢半拍i 2021-02-20 09:58

I have a multiline label whose text has a chance of overrunning. If it does this, I want to decrease the font size until it isn\'t overrunning, or until it hits some minimum siz

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-20 10:22

    This work for me !! In javafx

    public class LabelHelper{
      public static boolean necesitaTooltip(Font font, Label label){
        Text text = new Text(label.getText());
        text.setFont(font);
        Bounds tb = text.getBoundsInLocal();
        Rectangle stencil = new Rectangle(
                tb.getMinX(), tb.getMinY(), tb.getWidth(), tb.getHeight()
        );
    
        Shape intersection = Shape.intersect(text, stencil);
    
        Bounds ib = intersection.getBoundsInLocal();
        return ib.getWidth() > label.getPrefWidth();
      }
    
      public static void asignarTexto(Label label, String texto){
          label.setText(texto);
          if (necesitaTooltip(label.getFont(), label)){
              Tooltip tp = new Tooltip(texto);
    
            label.setTooltip(tp);
          }
      }
    } 
    

    Only call a asignarTexto(label, texto) for set text a label and check if the text is overrun in the label then add a tooltip for label.

提交回复
热议问题