2011-09-07 15 views
11

¿Cómo puedo agregar una nueva línea a JLabel? Sé que si uso HTML simple, funcionará. Pero si uso html, JLabel no muestra la fuente que se incrustó con la aplicación. Estoy incrustando la fuente usando el método - createFont() y usando JLabel.setFont() para aplicar la fuente.Cómo agregar una nueva línea a JLabel sin usar HTML

Respuesta

4

Estoy incrustar la fuente utilizando el método - createFont()) y el uso de JLabel.setFont() para la aplicación de la fuente.

En lugar de tratar de colocarlo en el código HTML, como se muestra here.

+0

Desde mi punto de vista, el principal problema con el uso de HTML es la pérdida de la línea de base, que la mayoría de los administradores de diseño usan actualmente (y ese es un buen punto en mi humilde opinión) – jfpoilpret

3

JLabel no está pensado originalmente para texto de líneas múltiples, por lo que recuerdo. Debería anular los diversos métodos de representación para dividir la línea de texto manualmente.

Quizás debería utilizar un JTextArea no editable si desea etiquetas de varias líneas.

1

1) si quieres JComponents de varias líneas sin usar JLabel, entonces usted tiene que buscar TextComponent como son JTextArea, JTextPane, JEditorPane, si DEBERÍAMOS ser editadas luego myTextComponent#setEditable(false);

2) Nunca veo problema html & & fuente de color en oscilación, por ejemplo:

enter image description here

import java.awt.Color; 
import java.awt.Font; 
import javax.swing.*; 

public class ButtonFg extends JFrame { 

    private static final long serialVersionUID = 1L; 

    public ButtonFg() { 
     JButton button = new JButton("<html> - myText <br>" 
       + " - myText <br>" 
       + " - myText <br>" 
       + " - myText </html>"); 
     button.setForeground(Color.blue); 
     button.setFont(new Font("Serif", Font.BOLD, 28)); 
     button.setFocusPainted(false); 
     add(button); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setLocation(150, 150); 
     pack(); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       new ButtonFg().setVisible(true); 
      } 
     }); 
    } 
} 
7


No creo que haya una forma directa (y fácil) de hacer JLabel con múltiples líneas sin recurrir a HTML. Puede usar JTextArea en su lugar.

JTextArea textArea = new JTextArea(); 
textArea.setEditable(false); 
textArea.setLineWrap(true); 
textArea.setOpaque(false); 
textArea.setBorder(BorderFactory.createEmptyBorder()); 
add(textArea, BorderLayout.CENTER); 

Debe ser casi igual. Si tiene fuentes diferentes para diferentes componentes, se puede añadir la siguiente línea para asegurarse de que la fuente de JTextArea es lo mismo con JLabel

textArea.setFont(UIManager.getFont("Label.font")); 

Espero que esto ayude.

+0

¿Puedo alinear el texto de un JTextArea? – Nauphal

+0

Revisa esta publicación http: // stackoverflow.com/questions/3213045/centering-text-in-a-jtextarea-or-jtextpane-horizontal-text-alignment – Serhiy

9

SwingX soporta etiquetas de varias líneas:

JXLabel label = new JXLabel(); 
    label.setLineWrap(true); 
+0

¿Tiene JXLabel la línea de base "correcta" cuando se utilizan múltiples líneas de texto? Tenga en cuenta que "correcto" puede significar cosas diferentes para diferentes personas ;-) – jfpoilpret

+0

@jfpoilpret - no sé. ¿Cuál sería la línea base correcta? – kleopatra

+0

para mí, la línea base correcta sería la línea base del primer carácter de la primera línea de la etiqueta. Pero estoy seguro de que podría encontrar otras personas que prefieran una línea base centrada en toda la altura de la etiqueta, por ejemplo; otras personas también pueden querer que la línea base sea la línea de base del primer carácter de la última línea en la etiqueta. En realidad, depende de cómo la gente quiere etiquetas alineadas en sus diseños. Creo que mi primera sugerencia tiene más sentido. – jfpoilpret

1

mayor parte del código siguiente se toma de BasicLabelUI y/o WindowsLabelUI pero añade código para que funcione con múltiples líneas. Esta era la cantidad mínima de código copiado que pude obtener para trabajar. Puede establecer el carácter separador entre las líneas con setSeparator o cambiando el valor predeterminado en la creación de instancias de LinesAndIndex. No he hecho pruebas exhaustivas sobre esto, pero hasta ahora me funciona. Cuando usé HTML, el mnemónico no funcionó, así que creé esto. Si tienes una mejor manera de lograr esto, corrige el código.

import com.sun.java.swing.plaf.windows.WindowsLabelUI; 
    import com.sun.java.swing.plaf.windows.WindowsLookAndFeel; 
    import java.awt.Color; 
    import java.awt.FontMetrics; 
    import java.awt.Graphics; 
    import java.awt.Insets; 
    import java.awt.Rectangle; 
    import java.util.ArrayList; 
    import java.util.List; 
    import javax.swing.Icon; 
    import javax.swing.JComponent; 
    import javax.swing.JLabel; 
    import javax.swing.UIManager; 
    import javax.swing.plaf.LabelUI; 
    import javax.swing.plaf.basic.BasicGraphicsUtils; 
    import javax.swing.plaf.basic.BasicHTML; 
    import javax.swing.text.View; 

    public class MultiLineLabelUI extends WindowsLabelUI { 
     private static MultiLineLabelUI multiLineLabelUI; 
     private LinesAndIndex lai = new LinesAndIndex(','); 
     private Rectangle paintIconR = new Rectangle(); 
     private Rectangle paintTextR = new Rectangle(); 
     public static LabelUI createUI(JComponent c) { 
      if (multiLineLabelUI == null) { 
       multiLineLabelUI = new MultiLineLabelUI(); 
      } 
      return multiLineLabelUI; 
     } 
     private int getBaseline(JComponent c, int y, int ascent, int w, int h) { 
      View view = (View) c.getClientProperty(BasicHTML.propertyKey); 
      if (view != null) { 
       int baseline = BasicHTML.getHTMLBaseline(view, w, h); 
       if (baseline < 0) { 
        return baseline; 
       } 
       return y + baseline; 
      } 
      return y + ascent; 
     } 
     public char getSeparator() { 
      return lai.getSeparator(); 
     } 
     public void setSeparator(char ch) { 
      lai.setSeparator(ch); 
     } 
     private String layout(JLabel label, FontMetrics fm, 
       int width, int height, int lineCnt, int curLine, String text) { 
      Insets insets = label.getInsets(null); 
      Icon icon = (label.isEnabled()) ? label.getIcon() 
        : label.getDisabledIcon(); 
      Rectangle paintViewR = new Rectangle(); 
      paintViewR.width = width - (insets.left + insets.right); 
      paintViewR.height = (height - (insets.top + insets.bottom))/lineCnt; 
      paintViewR.x = insets.left; 
      paintViewR.y = insets.top + (paintViewR.height * curLine); 
      paintIconR.x = 0; 
      paintIconR.y = 0; 
      paintIconR.width = 0; 
      paintIconR.height = 0; 
      paintTextR.x = 0; 
      paintTextR.y = 0; 
      paintTextR.width = 0; 
      paintTextR.height = 0; 
      return layoutCL(label, fm, text, icon, paintViewR, paintIconR, 
        paintTextR); 
     } 
     protected void paintEnabledText(JLabel l, Graphics g, 
       String s, int textX, int textY, int curLine) { 
      int mnemonicIndex = lai.getMnemonicIndex(); 
      // W2K Feature: Check to see if the Underscore should be rendered. 
      if (WindowsLookAndFeel.isMnemonicHidden() == true) { 
       mnemonicIndex = -1; 
      } 
      if (curLine != lai.getMnemonicLineIndex()) { 
       mnemonicIndex = -1; 
      } 

      g.setColor(l.getForeground()); 
      BasicGraphicsUtils.drawStringUnderlineCharAt(g, s, mnemonicIndex, 
        textX, textY); 
     } 
     protected void paintDisabledText(JLabel l, Graphics g, 
       String s, int textX, int textY, int curLine) { 
      int mnemonicIndex = lai.getMnemonicIndex(); 
      // W2K Feature: Check to see if the Underscore should be rendered. 
      if (WindowsLookAndFeel.isMnemonicHidden() == true) { 
       mnemonicIndex = -1; 
      } 
      if (curLine != lai.getMnemonicLineIndex()) { 
       mnemonicIndex = -1; 
      } 
      if (UIManager.getColor("Label.disabledForeground") instanceof Color 
        && UIManager.getColor("Label.disabledShadow") instanceof Color) { 
       g.setColor(UIManager.getColor("Label.disabledShadow")); 
       BasicGraphicsUtils.drawStringUnderlineCharAt(g, s, mnemonicIndex, 
         textX + 1, textY + 1); 
       g.setColor(UIManager.getColor("Label.disabledForeground")); 
       BasicGraphicsUtils.drawStringUnderlineCharAt(g, s, mnemonicIndex, 
         textX, textY); 
      } else { 
       Color background = l.getBackground(); 
       g.setColor(background.brighter()); 
       BasicGraphicsUtils.drawStringUnderlineCharAt(g, s, mnemonicIndex, 
         textX + 1, textY + 1); 
       g.setColor(background.darker()); 
       BasicGraphicsUtils.drawStringUnderlineCharAt(g, s, mnemonicIndex, 
         textX, textY); 
      } 
     } 
     @Override 
     public void paint(Graphics g, JComponent c) { 
      JLabel label = (JLabel) c; 
      String text = label.getText(); 
      Icon icon = (label.isEnabled()) 
        ? label.getIcon() 
        : label.getDisabledIcon(); 

      if ((icon == null) && (text == null)) { 
       return; 
      } 
      char mnemonic = (char) label.getDisplayedMnemonic(); 
      lai.splitText(text, mnemonic); 
      List<String> lines = lai.getLines(); 

      FontMetrics fm = label.getFontMetrics(g.getFont()); 
      String[] clippedText = new String[lines.size()]; 
      for (int i = 0; i < lines.size(); i++) { 
       clippedText[i] = layout(label, fm, c.getWidth(), c.getHeight(), 
         lines.size(), i, lines.get(i)); 

       if (icon != null && i == 0) { 
        icon.paintIcon(c, g, paintIconR.x, paintIconR.y); 
       } 

       if (text != null) { 
        int textX = paintTextR.x; 
        int textY = paintTextR.y + fm.getAscent(); 

        if (label.isEnabled()) { 
         paintEnabledText(label, g, clippedText[i], textX, 
           textY, i); 
        } else { 
         paintDisabledText(label, g, clippedText[i], textX, 
           textY, i); 
        } 
       } 
      } 
     } 
     @Override 
     public int getBaseline(JComponent c, int width, int height) { 
      super.getBaseline(c, width, height); 
      JLabel label = (JLabel) c; 
      String text = label.getText(); 
      if (text == null || "".equals(text) || label.getFont() == null) { 
       return -1; 
      } 
      char mnemonic = (char) label.getDisplayedMnemonic(); 
      lai.splitText(text, mnemonic); 
      List<String> lines = lai.getLines(); 
      FontMetrics fm = label.getFontMetrics(label.getFont()); 
      String[] clippedText = new String[lines.size()]; 
      for (int i = 0; i < lines.size(); i++) { 
       clippedText[i] = layout(label, fm, width, height, lines.size(), i, 
         lines.get(i)); 
      } 
      return getBaseline(label, paintTextR.y, fm.getAscent(), 
        paintTextR.width, paintTextR.height); 
     } 

     private static class LinesAndIndex { 
      private char sep; 
      private List<String> lines; 
      private int mnemonicLineIndex; 
      private int mnemonicIndex; 
      LinesAndIndex(char sep) { 
       mnemonicLineIndex = -1; 
       mnemonicIndex = -1; 
       lines = new ArrayList<String>(); 
       this.sep = sep; 
      } 
      public char getSeparator() { 
       return sep; 
      } 
      public void setSeparator(char sep) { 
       this.sep = sep; 
      } 
      public List<String> getLines() { 
       return lines; 
      } 
      public int getMnemonicLineIndex() { 
       return mnemonicLineIndex; 
      } 
      public int getMnemonicIndex() { 
       return mnemonicIndex; 
      } 
      public void splitText(String text, char mnemonic) { 
       if (text == null) { 
        return; 
       } 
       lines.clear(); 
       mnemonicLineIndex = -1; 
       mnemonicIndex = -1; 
       char um = Character.toUpperCase(mnemonic); 
       char lm = Character.toLowerCase(mnemonic); 
       int umi = Integer.MAX_VALUE; 
       int lmi = Integer.MAX_VALUE; 
       int umli = -1; 
       int lmli = -1; 
       for (int i = 0, j = 0, k = 0; i < text.length(); i++) { 
        if (text.charAt(i) == sep) { 
         lines.add(text.substring(j, i)); 
         j = i + 1; 
         k++; 
        } else if (text.charAt(i) == um) { 
         if (umi == Integer.MAX_VALUE) { 
          umi = i - j; 
          umli = k; 
         } 
        } else if (text.charAt(i) == lm) { 
         if (lmi == Integer.MAX_VALUE) { 
          lmi = i - j; 
          lmli = k; 
         } 
        } 
        if (i == text.length() - 1) { 
         lines.add(text.substring(j, i + 1)); 
        } 
       } 
       mnemonicLineIndex = (lmi < umi) ? lmli : umli; 
       mnemonicIndex = (lmi < umi) ? lmi : umi; 
      } 
     } 

    } 
Cuestiones relacionadas