Java/Swing Components/Label

Материал из Java эксперт
Перейти к: навигация, поиск

A JLabel that can be underlined, implements Scrollable

  
/*
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public
    License as published by the Free Software Foundation; either
    version 2 of the license, or (at your option) any later version.
*/

import javax.swing.*;
import java.awt.*;
/**
    A <tt>JLabel</tt> that can be underlined, implements <tt>Scrollable</tt>,
    may have a tooltip text equal to its text and exposes a few convenience methods
    for <tt>setText()</tt>.
 
    @author 
    @version $Revision: 1.3 $ $Date: 2003/08/18 07:47:20 $
*/
public class ExtendedJLabel extends JLabel implements Scrollable {
    private boolean underlined = false;
    private boolean autoTooltip = false;
    /**
        Constructor.
     */
    public ExtendedJLabel() {
    }
    /**
        Constructor.
        @param text the label text.
     */
    public ExtendedJLabel(String text) {
        super(text);
    }
    
    public Dimension getPreferredScrollableViewportSize() {
        return getSize();
    }
    public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
        return getWidth() / 10;
    }
    
    public boolean getScrollableTracksViewportWidth() {
        return false;
    }
    
    public boolean getScrollableTracksViewportHeight() {
        return false;
    }
    
    public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
        return 10;
    }
    
    /**
        Check whether this label is underlined.
        @return underlined or not
     */
    public boolean isUnderlined() {
        return underlined;
    }
    
    /**
        Set whether this label is underlined.
        @param underlined underlined or not
     */
    public void setUnderlined(boolean underlined) {
        this.underlined = underlined;
        repaint();
    }
    
    /**
        Check whether the tooltip text is automatically equal
        to the text of this label or not.
        @return equal or not
     */
    public boolean getAutoTooltip() {
        return autoTooltip;
    }
    /**
        Set whether the tooltip text is automatically equal
        to the text of this label or not.
        @param autoTooltip equal or not
     */
    public void setAutoTooltip(boolean autoTooltip) {
        this.autoTooltip = autoTooltip;
        setToolTipText(getText());
    }
    
    public void setText(String text) {
        super.setText(text);
        if (autoTooltip) {
            setToolTipText(text);
        }
    }
    
    /**
        Convenience method for calling <tt>setText()</tt> with a <tt>short</tt>.
        @param number the <tt>short</tt>
     */
    public void setText(short number) {
        setText(String.valueOf(number));
    }
    /**
        Convenience method for calling <tt>setText()</tt> with a <tt>int</tt>.
        @param number the <tt>int</tt>
     */
    public void setText(int number) {
        setText(String.valueOf(number));
    }
    /**
        Convenience method for calling <tt>setText()</tt> with a <tt>double</tt>.
        @param number the <tt>double</tt>
     */
    public void setText(double number) {
        setText(String.valueOf(number));
    }
    /**
        Convenience method for calling <tt>setText()</tt> with a <tt>float</tt>.
        @param number the <tt>float</tt>
     */
    public void setText(float number) {
        setText(String.valueOf(number));
    }
    /**
        Convenience method for calling <tt>setText()</tt> with a <tt>long</tt>.
        @param number the <tt>long</tt>
     */
    public void setText(long number) {
        setText(String.valueOf(number));
    }
    public void paint(Graphics g) {
        super.paint(g);
        
        if (underlined) {
            Insets i = getInsets();
            FontMetrics fm = g.getFontMetrics();
            Rectangle textRect = new Rectangle();
            Rectangle viewRect = new Rectangle(i.left, i.top, getWidth() - (i.right + i.left), getHeight() - (i.bottom + i.top) );
            SwingUtilities.layoutCompoundLabel(
                                this,
                                fm,
                                getText(),
                                getIcon(),
                                getVerticalAlignment(),
                                getHorizontalAlignment(),
                                getVerticalTextPosition(),
                                getHorizontalTextPosition(),
                                viewRect,
                                new Rectangle(),
                                textRect,
                                getText() == null ? 0 : ((Integer)UIManager.get("Button.textIconGap")).intValue()
                          );

            int offset = 2;
            if (UIManager.getLookAndFeel().isNativeLookAndFeel() && System.getProperty("os.name").startsWith("Windows")) {
                offset = 1;
            }
            g.fillRect(textRect.x + ((Integer)UIManager.get("Button.textShiftOffset")).intValue() ,
                       textRect.y + fm.getAscent() + ((Integer)UIManager.get("Button.textShiftOffset")).intValue() + offset,
                       textRect.width,
                       1);
        }
    }
}





Bevel Text

  
 
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.FontUIResource;
public class jexpBevelText extends JComponent implements SwingConstants {
  RenderingLabel leftShadeLabel = new RenderingLabel();
  RenderingLabel contentLabel = new RenderingLabel();
  RenderingLabel rightShadeLabel = new RenderingLabel();
  boolean raisedBevel= true;
  int depthX = 1;
  int depthY = 1;
  RenderingHints renderingHints;
  String text  = "jexp";
  Color foregroundColor;
  Color defaultForeground = new Color(132, 132, 204);
  Font font = new FontUIResource(Font.decode("Dialog-Plain-28"));;
  public jexpBevelText() {
    setLayout(null);
    add(contentLabel);
    add(leftShadeLabel);
    add(rightShadeLabel);
    reSize();
    setToolTipText(getToolTipText());
    setFont(font);
    setBackground(getBackground());
    setForeground(getForeground());
    setText(getText());
    setSize(getPreferredSize());
    setEnabled(isEnabled());
    setOpaque(isOpaque());
    setHorizontalAlignment(0);
    renderingHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    renderingHints.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
  }
  public jexpBevelText(String s) {
    this();
    setText(s);
    setSize(getPreferredSize());
  }
  public void setToolTipText(String s) {
    super.setToolTipText(s);
    leftShadeLabel.setToolTipText(s);
    contentLabel.setToolTipText(s);
    rightShadeLabel.setToolTipText(s);
  }
  public void updateUI() {
    super.updateUI();
    leftShadeLabel.updateUI();
    contentLabel.updateUI();
    rightShadeLabel.updateUI();
    setBackground(getBackground());
    setForeground(getForeground());
    setFont(font);
  }
  public void setRaisedBevel(boolean flag) {
    raisedBevel = flag;
    setForeground(getForeground());
  }
  public boolean isRaisedBevel() {
    return raisedBevel;
  }
  public void setDepthX(int depth) {
    depthX = depth;
    setSize(getSize());
  }
  public int getDepthX() {
    return depthX;
  }
  public void setDepthY(int depth) {
    depthY = depth;
    setSize(getSize());
  }
  public int getDepthY() {
    return depthY;
  }
  public Color getBackground() {
    return super.getBackground();
  }
  public void setBackground(Color newColor) {
    Color backgroundColor = newColor;
    if (backgroundColor == null || (backgroundColor instanceof ColorUIResource))
      backgroundColor = UIManager.getColor("control");
    super.setBackground(backgroundColor);
  }
  public Color getForeground() {
    return foregroundColor;
  }
  public void setForeground(Color newColor) {
    foregroundColor = newColor;
    if (foregroundColor == null || (foregroundColor instanceof ColorUIResource)) {
      foregroundColor = new ColorUIResource(defaultForeground);
      newColor = defaultForeground;
    }
    contentLabel.setForeground(newColor);
    if (raisedBevel) {
      leftShadeLabel.setForeground(Color.white);
      rightShadeLabel.setForeground(newColor.darker().darker().darker());
    } else {
      leftShadeLabel.setForeground(newColor.darker().darker().darker());
      rightShadeLabel.setForeground(Color.white);
    }
  }
  public Font getFont() {
    if (font == null || (font instanceof FontUIResource))
      font = new FontUIResource(Font.decode("Dialog-Plain-28"));
    return font;
  }
  public void setFont(Font newFont) {
    font = newFont;
    leftShadeLabel.setFont(font);
    contentLabel.setFont(font);
    rightShadeLabel.setFont(font);
  }
  public void setEnabled(boolean enabled) {
    super.setEnabled(enabled);
    leftShadeLabel.setEnabled(enabled);
    contentLabel.setEnabled(enabled);
    rightShadeLabel.setEnabled(enabled);
  }
  public void setOpaque(boolean flag) {
    super.setOpaque(flag);
    leftShadeLabel.setOpaque(false);
    contentLabel.setOpaque(false);
    rightShadeLabel.setOpaque(false);
    updateUI();
  }
  public void setVisible(boolean isVisible) {
    super.setVisible(isVisible);
    leftShadeLabel.setVisible(isVisible);
    contentLabel.setVisible(isVisible);
    rightShadeLabel.setVisible(isVisible);
  }
  public void setText(String s) {
    text = s;
    leftShadeLabel.setText(s);
    contentLabel.setText(s);
    rightShadeLabel.setText(s);
  }
  public String getText() {
    return text;
  }
  public Dimension getPreferredSize() {
    JLabel jlabel = new JLabel();
    jlabel.setFont(getFont());
    jlabel.setBorder(getBorder());
    if (renderingHints == null) {
      jlabel.setText(getText() + "m");
      Dimension dimension = jlabel.getPreferredSize();
      dimension.width += depthX * 2;
      dimension.height += depthY * 2;
      return dimension;
    } else {
      Dimension dimension1 = jlabel.getPreferredSize();
      dimension1.width += depthX * 2;
      dimension1.height += depthY * 2;
      boolean flag = true;
      boolean flag1 = true;
      FontRenderContext fontrendercontext = new FontRenderContext(null, flag, flag1);
      dimension1.width += getFont().getStringBounds(getText() + "m", fontrendercontext).getWidth();
      Rectangle2D rectangle2d = getFont().getMaxCharBounds(fontrendercontext);
      dimension1.height += rectangle2d.getHeight();
      return dimension1;
    }
  }
  public Dimension getMinimumSize() {
    return getPreferredSize();
  }
  public void setBorder(Border border) {
    super.setBorder(border);
    setSize(getSize());
  }
  private void reSize() {
    Insets insets = new Insets(0, 0, 0, 0);
    Border border = getBorder();
    if (border != null)
      insets = border.getBorderInsets(this);
    leftShadeLabel.setLocation(insets.top, insets.left);
    contentLabel.setLocation(insets.top + depthX, insets.left + depthY);
    rightShadeLabel.setLocation(insets.top + depthX * 2, insets.left + depthY * 2);
  }
  public void setBounds(int x, int y, int width, int height) {
    super.setBounds(x, y, width, height);
    reSize();
    Insets insets = new Insets(0, 0, 0, 0);
    Border border = getBorder();
    if (border != null)
      insets = border.getBorderInsets(this);
    int w = width - depthX * 2 - insets.left - insets.right;
    int h = height - depthY * 2 - insets.top - insets.bottom;
    leftShadeLabel.setSize(w, h);
    contentLabel.setSize(w, h);
    rightShadeLabel.setSize(w, h);
  }
  public void setBounds(Rectangle rectangle) {
    setBounds(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
  }
  public void setSize(int w, int h) {
    super.setSize(w, h);
    reSize();
    Insets insets = new Insets(0, 0, 0, 0);
    Border border = getBorder();
    if (border != null)
      insets = border.getBorderInsets(this);
    int width = w - depthX * 2 - insets.left - insets.right;
    int height = h - depthY * 2 - insets.top - insets.bottom;
    leftShadeLabel.setSize(width, height);
    contentLabel.setSize(width, height);
    rightShadeLabel.setSize(width, height);
  }
  public void setSize(Dimension dimension) {
    setSize(dimension.width, dimension.height);
  }
  public final void paintInterface(Graphics g1) {
    if (isOpaque()) {
      g1.setColor(getBackground());
      g1.fillRect(0, 0, getWidth(), getHeight());
    }
    super.paint(g1);
  }
  public void setHorizontalAlignment(int i) {
    leftShadeLabel.setHorizontalAlignment(i);
    contentLabel.setHorizontalAlignment(i);
    rightShadeLabel.setHorizontalAlignment(i);
  }
  public int getHorizontalAlignment() {
    return leftShadeLabel.getHorizontalAlignment();
  }
  public void setVerticalAlignment(int i) {
    leftShadeLabel.setVerticalAlignment(i);
    contentLabel.setVerticalAlignment(i);
    rightShadeLabel.setVerticalAlignment(i);
  }
  public int getVerticalAlignment() {
    return leftShadeLabel.getVerticalAlignment();
  }
  private void setHorizontalTextPosition(int i) {
    leftShadeLabel.setHorizontalTextPosition(i);
    contentLabel.setHorizontalTextPosition(i);
    rightShadeLabel.setHorizontalTextPosition(i);
  }
  private int getHorizontalTextPosition() {
    return leftShadeLabel.getHorizontalTextPosition();
  }
  private void setVerticalTextPosition(int i) {
    if (rightShadeLabel != null) {
      leftShadeLabel.setVerticalTextPosition(i);
      contentLabel.setVerticalTextPosition(i);
      rightShadeLabel.setVerticalTextPosition(i);
    }
  }
  class RenderingLabel extends JLabel {
    public void paint(Graphics g1) {
      if (renderingHints != null && (g1 instanceof Graphics2D)) {
        Graphics2D graphics2d = (Graphics2D) g1;
        graphics2d.setRenderingHints(renderingHints);
      }
      super.paint(g1);
    }
  }
  private int getVerticalTextPosition() {
    return leftShadeLabel.getVerticalTextPosition();
  }
  public static void main(String[] args) {
    JFrame f = new JFrame();
    jexpBevelText j = new jexpBevelText();
    j.setForeground(Color.RED);
    f.getContentPane().add(j, "Center");
    f.setSize(400, 600);
    f.setVisible(true);
  }
}





Gradient Label

 
/*
 *  soapUI, copyright (C) 2004-2009 eviware.ru 
 *
 *  soapUI is free software; you can redistribute it and/or modify it under the 
 *  terms of version 2.1 of the GNU Lesser General Public License as published by 
 *  the Free Software Foundation.
 *
 *  soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without 
 *  even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 *  See the GNU Lesser General Public License for more details at gnu.org.
 */

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import javax.swing.JLabel;
public class GradientLabel extends JLabel
{
  // ------------------------------ FIELDS ------------------------------
  private Color start;
  private Color end;
  // --------------------------- CONSTRUCTORS ---------------------------
  public GradientLabel( String text )
  {
    super( text );
    start = Color.LIGHT_GRAY;
    end = getBackground();
  }
  public GradientLabel( String text, Color start, Color end )
  {
    super( text );
    this.start = start;
    this.end = end;
  }
  // -------------------------- OTHER METHODS --------------------------
  public void paint( Graphics g )
  {
    int width = getWidth();
    int height = getHeight();
    // Create the gradient paint
    GradientPaint paint = new GradientPaint( 0, 0, start, width, height, end, true );
    // we need to cast to Graphics2D for this operation
    Graphics2D g2d = ( Graphics2D )g;
    // save the old paint
    Paint oldPaint = g2d.getPaint();
    // set the paint to use for this operation
    g2d.setPaint( paint );
    // fill the background using the paint
    g2d.fillRect( 0, 0, width, height );
    // restore the original paint
    g2d.setPaint( oldPaint );
    super.paint( g );
  }
}





Hyperlink Label

 
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
public class JHyperlinkLabel extends JLabel {
  private Color underlineColor = null;
  public JHyperlinkLabel(String label) {
    super(label);
    setForeground(Color.BLUE.darker());
    setCursor(new Cursor(Cursor.HAND_CURSOR));
    addMouseListener(new HyperlinkLabelMouseAdapter());
  }
  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(underlineColor == null ? getForeground() : underlineColor);
    Insets insets = getInsets();
    int left = insets.left;
    if (getIcon() != null)
      left += getIcon().getIconWidth() + getIconTextGap();
    g.drawLine(left, getHeight() - 1 - insets.bottom, (int) getPreferredSize().getWidth()
        - insets.right, getHeight() - 1 - insets.bottom);
  }
  public class HyperlinkLabelMouseAdapter extends MouseAdapter {
    @Override
    public void mouseClicked(MouseEvent e) {
      System.out.println(getText());
    }
  }
  public Color getUnderlineColor() {
    return underlineColor;
  }
  public void setUnderlineColor(Color underlineColor) {
    this.underlineColor = underlineColor;
  }
}





Label 3D

  
/*
Swing Hacks Tips and Tools for Killer GUIs
By Joshua Marinacci, Chris Adamson
First Edition June 2005  
Series: Hacks
ISBN: 0-596-00907-0
Pages: 542
website: http://www.oreilly.ru/catalog/swinghks/
*/
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.LineMetrics;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class RichJLabel extends JLabel {
  private int tracking;
  public RichJLabel(String text, int tracking) {
    super(text);
    this.tracking = tracking;
  }
  private int left_x, left_y, right_x, right_y;
  private Color left_color, right_color;
  public void setLeftShadow(int x, int y, Color color) {
    left_x = x;
    left_y = y;
    left_color = color;
  }
  public void setRightShadow(int x, int y, Color color) {
    right_x = x;
    right_y = y;
    right_color = color;
  }
  public Dimension getPreferredSize() {
    String text = getText();
    FontMetrics fm = this.getFontMetrics(getFont());
    int w = fm.stringWidth(text);
    w += (text.length() - 1) * tracking;
    w += left_x + right_x;
    int h = fm.getHeight();
    h += left_y + right_y;
    return new Dimension(w, h);
  }
  public void paintComponent(Graphics g) {
    ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
        RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    char[] chars = getText().toCharArray();
    FontMetrics fm = this.getFontMetrics(getFont());
    int h = fm.getAscent();
    LineMetrics lm = fm.getLineMetrics(getText(), g);
    g.setFont(getFont());
    int x = 0;
    for (int i = 0; i < chars.length; i++) {
      char ch = chars[i];
      int w = fm.charWidth(ch) + tracking;
      g.setColor(left_color);
      g.drawString("" + chars[i], x - left_x, h - left_y);
      g.setColor(right_color);
      g.drawString("" + chars[i], x + right_x, h + right_y);
      g.setColor(getForeground());
      g.drawString("" + chars[i], x, h);
      x += w;
    }
  }
  public static void main(String[] args) {
    RichJLabel label = new RichJLabel("www.jexp.ru", 0);
    label.setLeftShadow(1, 1, Color.white);
    label.setRightShadow(1, 1, Color.white);
    label.setForeground(Color.blue);
    label.setFont(label.getFont().deriveFont(140f));
    label.setLeftShadow(5,5,Color.white);
    label.setRightShadow(-3,-3, new Color(0xccccff));
    label.setForeground(new Color(0x8888ff));
    label.setFont(label.getFont().deriveFont(140f));
    
    
    JFrame frame = new JFrame("RichJLabel hack");
    frame.getContentPane().add(label);
    frame.pack();
    frame.setVisible(true);
  }
  public static void p(String str) {
    System.out.println(str);
  }
}





Label with large font and ANTIALIAS paint

  
/*
Swing Hacks Tips and Tools for Killer GUIs
By Joshua Marinacci, Chris Adamson
First Edition June 2005  
Series: Hacks
ISBN: 0-596-00907-0
Pages: 542
website: http://www.oreilly.ru/catalog/swinghks/
*/
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.LineMetrics;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class RichJLabel extends JLabel {
  private int tracking;
  public RichJLabel(String text, int tracking) {
    super(text);
    this.tracking = tracking;
  }
  private int left_x, left_y, right_x, right_y;
  private Color left_color, right_color;
  public void setLeftShadow(int x, int y, Color color) {
    left_x = x;
    left_y = y;
    left_color = color;
  }
  public void setRightShadow(int x, int y, Color color) {
    right_x = x;
    right_y = y;
    right_color = color;
  }
  public Dimension getPreferredSize() {
    String text = getText();
    FontMetrics fm = this.getFontMetrics(getFont());
    int w = fm.stringWidth(text);
    w += (text.length() - 1) * tracking;
    w += left_x + right_x;
    int h = fm.getHeight();
    h += left_y + right_y;
    return new Dimension(w, h);
  }
  public void paintComponent(Graphics g) {
    ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
        RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    char[] chars = getText().toCharArray();
    FontMetrics fm = this.getFontMetrics(getFont());
    int h = fm.getAscent();
    LineMetrics lm = fm.getLineMetrics(getText(), g);
    g.setFont(getFont());
    int x = 0;
    for (int i = 0; i < chars.length; i++) {
      char ch = chars[i];
      int w = fm.charWidth(ch) + tracking;
      g.setColor(left_color);
      g.drawString("" + chars[i], x - left_x, h - left_y);
      g.setColor(right_color);
      g.drawString("" + chars[i], x + right_x, h + right_y);
      g.setColor(getForeground());
      g.drawString("" + chars[i], x, h);
      x += w;
    }
  }
  public static void main(String[] args) {
    RichJLabel label = new RichJLabel("www.jexp.ru", 0);
    label.setLeftShadow(1, 1, Color.white);
    label.setRightShadow(1, 1, Color.white);
    label.setForeground(Color.blue);
    label.setFont(label.getFont().deriveFont(140f));
    JFrame frame = new JFrame("RichJLabel hack");
    frame.getContentPane().add(label);
    frame.pack();
    frame.setVisible(true);
  }
  public static void p(String str) {
    System.out.println(str);
  }
}





Link Label

  
/**
 * The utillib library.
 * More information is available at http://www.jinchess.ru/.
 * Copyright (C) 2002 Alexander Maryanovsky.
 * All rights reserved.
 *
 * The utillib library is free software; you can redistribute
 * it and/or modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * The utillib library is distributed in the hope that it will
 * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
 * General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with utillib library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;

/**
 * An extension of JLabel which looks like a link and responds appropriately
 * when clicked. Note that this class will only work with Swing 1.1.1 and later.
 * Note that because of the way this class is implemented, getText() will not
 * return correct values, user <code>getNormalText</code> instead.
 */
public class LinkLabel extends JLabel{

  /**
   * The normal text set by the user.
   */
  private String text;


  /**
   * Creates a new LinkLabel with the given text.
   */
  public LinkLabel(String text){
    super(text);
    setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    enableEvents(MouseEvent.MOUSE_EVENT_MASK);
  }


  /**
   * Sets the text of the label.
   */
  public void setText(String text){
    super.setText("<html><font color=\"#0000CF\"><u>"+text+"</u></font></html>"); //$NON-NLS-1$ //$NON-NLS-2$
    this.text = text;
  }


  /**
   * Returns the text set by the user.
   */
  public String getNormalText(){
    return text;
  }


  /**
   * Processes mouse events and responds to clicks.
   */
  protected void processMouseEvent(MouseEvent evt){
    super.processMouseEvent(evt);
    if (evt.getID() == MouseEvent.MOUSE_CLICKED)
      fireActionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, getNormalText()));
  }


  /**
   * Adds an ActionListener to the list of listeners receiving notifications
   * when the label is clicked.
   */
  public void addActionListener(ActionListener listener){
    listenerList.add(ActionListener.class, listener);
  }


  /**
   * Removes the given ActionListener from the list of listeners receiving
   * notifications when the label is clicked.
   */
  public void removeActionListener(ActionListener listener){
    listenerList.remove(ActionListener.class, listener);
  }


  /**
   * Fires an ActionEvent to all interested listeners.
   */
  protected void fireActionPerformed(ActionEvent evt){
    Object [] listeners = listenerList.getListenerList();
    for (int i = 0; i < listeners.length; i += 2){
      if (listeners[i] == ActionListener.class){
        ActionListener listener = (ActionListener)listeners[i+1];
        listener.actionPerformed(evt);
      }
    }
  }

}





MultiLine Label

  
// This example is from the book _Java in a Nutshell_ by David Flanagan.
//Written by David Flanagan. Copyright (c) 1996 O"Reilly & Associates.
//You may study, use, modify, and distribute this example for any purpose.
//This example is provided WITHOUT WARRANTY either expressed or implied.
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.util.StringTokenizer;
public class MultiLineLabel extends Canvas {
  public static final int LEFT = 0; // Alignment constants
  public static final int CENTER = 1;
  public static final int RIGHT = 2;
  protected String[] lines; // The lines of text to display
  protected int num_lines; // The number of lines
  protected int margin_width; // Left and right margins
  protected int margin_height; // Top and bottom margins
  protected int line_height; // Total height of the font
  protected int line_ascent; // Font height above baseline
  protected int[] line_widths; // How wide each line is
  protected int max_width; // The width of the widest line
  protected int alignment = LEFT; // The alignment of the text.
  // This method breaks a specified label up into an array of lines.
  // It uses the StringTokenizer utility class.
  protected void newLabel(String label) {
    StringTokenizer t = new StringTokenizer(label, "\n");
    num_lines = t.countTokens();
    lines = new String[num_lines];
    line_widths = new int[num_lines];
    for (int i = 0; i < num_lines; i++)
      lines[i] = t.nextToken();
  }
  // This method figures out how the font is, and how wide each
  // line of the label is, and how wide the widest line is.
  protected void measure() {
    FontMetrics fm = getFontMetrics(getFont());
    // If we don"t have font metrics yet, just return.
    if (fm == null)
      return;
    line_height = fm.getHeight();
    line_ascent = fm.getAscent();
    max_width = 0;
    for (int i = 0; i < num_lines; i++) {
      line_widths[i] = fm.stringWidth(lines[i]);
      if (line_widths[i] > max_width)
        max_width = line_widths[i];
    }
  }
  // Here are four versions of the cosntrutor.
  // Break the label up into separate lines, and save the other info.
  public MultiLineLabel(String label, int margin_width, int margin_height,
      int alignment) {
    newLabel(label);
    this.margin_width = margin_width;
    this.margin_height = margin_height;
    this.alignment = alignment;
  }
  public MultiLineLabel(String label, int margin_width, int margin_height) {
    this(label, margin_width, margin_height, LEFT);
  }
  public MultiLineLabel(String label, int alignment) {
    this(label, 10, 10, alignment);
  }
  public MultiLineLabel(String label) {
    this(label, 10, 10, LEFT);
  }
  // Methods to set the various attributes of the component
  public void setLabel(String label) {
    newLabel(label);
    measure();
    repaint();
  }
  public void setFont(Font f) {
    super.setFont(f);
    measure();
    repaint();
  }
  public void setForeground(Color c) {
    super.setForeground(c);
    repaint();
  }
  public void setAlignment(int a) {
    alignment = a;
    repaint();
  }
  public void setMarginWidth(int mw) {
    margin_width = mw;
    repaint();
  }
  public void setMarginHeight(int mh) {
    margin_height = mh;
    repaint();
  }
  public int getAlignment() {
    return alignment;
  }
  public int getMarginWidth() {
    return margin_width;
  }
  public int getMarginHeight() {
    return margin_height;
  }
  // This method is invoked after our Canvas is first created
  // but before it can actually be displayed. After we"ve
  // invoked our superclass"s addNotify() method, we have font
  // metrics and can successfully call measure() to figure out
  // how big the label is.
  public void addNotify() {
    super.addNotify();
    measure();
  }
  // This method is called by a layout manager when it wants to
  // know how big we"d like to be.
  public Dimension getPreferredSize() {
    return new Dimension(max_width + 2 * margin_width, num_lines
        * line_height + 2 * margin_height);
  }
  // This method is called when the layout manager wants to know
  // the bare minimum amount of space we need to get by.
  public Dimension getMinimumSize() {
    return new Dimension(max_width, num_lines * line_height);
  }
  // This method draws the label (applets use the same method).
  // Note that it handles the margins and the alignment, but that
  // it doesn"t have to worry about the color or font--the superclass
  // takes care of setting those in the Graphics object we"re passed.
  public void paint(Graphics g) {
    int x, y;
    Dimension d = getSize();
    y = line_ascent + (d.height - num_lines * line_height) / 2;
    for (int i = 0; i < num_lines; i++, y += line_height) {
      switch (alignment) {
      case LEFT:
        x = margin_width;
        break;
      case CENTER:
      default:
        x = (d.width - line_widths[i]) / 2;
        break;
      case RIGHT:
        x = d.width - margin_width - line_widths[i];
        break;
      }
      g.drawString(lines[i], x, y);
    }
  }
}





Multi Line Label extends JComponent

  
/*
 * IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
 * 
 * http://izpack.org/
 * http://izpack.codehaus.org/
 * 
 * Copyright 1997,2002 Elmar Grom
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 *     
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import javax.swing.*;
import java.awt.*;
import java.util.Vector;
/*---------------------------------------------------------------------------*/
/**
 * <BR>
 * <code>MultiLineLabel</code> may be used in place of javax.swing.JLabel. <BR>
 * <BR>
 * This class implements a component that is capable of displaying multiple lines of text. Line
 * breaks are inserted automatically whenever a line of text extends beyond the predefined maximum
 * line length. Line breaks will only be inserted between words, except where a single word is
 * longer than the maximum line length. Line breaks may be forced at any location in the text by
 * inserting a newline (\n). White space that is not valuable (i.e. is placed at the beginning of a
 * new line or at the very beginning or end of the text) is removed. <br>
 * <br>
 * <b>Note:</b> you can set the maximum width of the label either through one of the constructors
 * or you can call <code>setMaxWidth()</code> explicitly. If this is not set,
 * <code>MultiLineLabel</code> will derive its width from the parent component.
 *
 * @author Elmar Grom
 * @version 1.0 / 04-13-02
 */
/*---------------------------------------------------------------------------*
 * Reviving some old code here that was written before there was swing.
 * The original was written to work with awt. I had to do some masaging to
 * make it a JComponent and I hope it behaves like a reasonably good mannered
 * swing component.
 *---------------------------------------------------------------------------*/
public class MultiLineLabel extends JComponent
{
    /**
     *
     */
    private static final long serialVersionUID = 4051045255031894837L;
    public static final int LEFT = 0; // alignment constants
    public static final int CENTER = 1;
    public static final int RIGHT = 2;
    public static final int DEFAULT_MARGIN = 10;
    public static final int DEFAULT_ALIGN = LEFT;
    public static final int LEAST_ALLOWED = 200; // default setting for
    // maxAllowed
    private static final int FOUND = 0; // constants for string search.
    private static final int NOT_FOUND = 1;
    private static final int NOT_DONE = 0;
    private static final int DONE = 1;
    private static final char[] WHITE_SPACE = {" ", "\n", "\t"};
    private static final char[] SPACES = {" ", "\t"};
    private static final char NEW_LINE = "\n";
    protected Vector<String> line = new Vector<String>();// text lines to display
    protected String labelText; // text lines to display
    protected int numLines; // the number of lines
    protected int marginHeight; // top and bottom margins
    protected int marginWidth; // left and right margins
    protected int lineHeight; // total height of the font
    protected int lineAscent; // font height above the baseline
    protected int lineDescent; // font hight below the baseline
    protected int[] lineWidth; // width of each line
    protected int maxWidth; // width of the widest line
    private int maxAllowed = LEAST_ALLOWED; // max width allowed to use
    private boolean maxAllowedSet = false; // signals if the max allowed width
    // has been explicitly set
    protected int alignment = LEFT; // default text alignment
    /*-------------------------------------------------------------------*/
    /**
     * Constructor
     *
     * @param text       the text to be displayed
     * @param horMargin  the horizontal margin for the label
     * @param vertMargin the vertical margin for the label
     * @param maxWidth   the maximum allowed width of the text
     * @param justify    the text alignment for the label
     */
    /*-------------------------------------------------------------------*
     * <detailed description / implementation details if applicable>
     *-------------------------------------------------------------------*/
    public MultiLineLabel(String text, int horMargin, int vertMargin, int maxWidth, int justify)
    {
        this.labelText = text;
        this.marginWidth = horMargin;
        this.marginHeight = vertMargin;
        this.maxAllowed = maxWidth;
        this.maxAllowedSet = true;
        this.alignment = justify;
    }
    /*-------------------------------------------------------------------*/
    /**
     * Constructor using default max-width and alignment.
     *
     * @param label        the text to be displayed
     * @param marginWidth  the horizontal margin for the label
     * @param marginHeight the vertical margin for the label
     */
    /*-------------------------------------------------------------------*
     * <detailed description / implementation details if applicable>
     *-------------------------------------------------------------------*/
    public MultiLineLabel(String label, int marginWidth, int marginHeight)
    {
        this.labelText = label;
        this.marginWidth = marginWidth;
        this.marginHeight = marginHeight;
    }
    /*-------------------------------------------------------------------*/
    /**
     * Constructor using default max-width, and margin.
     *
     * @param label     the text to be displayed
     * @param alignment the text alignment for the label
     */
    /*-------------------------------------------------------------------*
     * <detailed description / implementation details if applicable>
     *-------------------------------------------------------------------*/
    public MultiLineLabel(String label, int alignment)
    {
        this.labelText = label;
        this.alignment = alignment;
    }
    /*-------------------------------------------------------------------*/
    /**
     * Constructor using default max-width, alignment, and margin.
     *
     * @param label the text to be displayed
     */
    /*-------------------------------------------------------------------*
     * <detailed description / implementation details if applicable>
     *-------------------------------------------------------------------*/
    public MultiLineLabel(String label)
    {
        this.labelText = label;
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method searches the target string for occurences of any of the characters in the source
     * string. The return value is the position of the first hit. Based on the mode parameter the
     * hit position is either the position where any of the source characters first was found or the
     * first position where none of the source characters where found.
     *
     * @param target the text to be searched
     * @param start  the start position for the search
     * @param source the list of characters to be searched for
     * @param mode   the search mode FOUND = reports first found NOT_FOUND = reports first not found
     * @return position of the first occurence
     */
    /*-------------------------------------------------------------------*
     * <detailed description / implementation details if applicable>
     *-------------------------------------------------------------------*/
    int getPosition(String target, int start, char[] source, int mode)
    {
        int status;
        int position;
        int scan;
        int targetEnd;
        int sourceLength;
        char temp;
        targetEnd = (target.length() - 1);
        sourceLength = source.length;
        position = start;
        if (mode == FOUND)
        {
            status = NOT_DONE;
            while (status != DONE)
            {
                position++;
                if (!(position < targetEnd)) // end of string reached, the
                // next
                { // statement would cause a runtime error
                    return (targetEnd);
                }
                temp = target.charAt(position);
                for (scan = 0; scan < sourceLength; scan++) // walk through the
                // source
                { // string and compare each char
                    if (source[scan] == temp)
                    {
                        status = DONE;
                    }
                }
            }
            return (position);
        }
        else if (mode == NOT_FOUND)
        {
            status = NOT_DONE;
            while (status != DONE)
            {
                position++;
                if (!(position < targetEnd)) // end of string reached, the
                // next
                { // statement would cause a runtime error
                    return (targetEnd);
                }
                temp = target.charAt(position);
                status = DONE;
                for (scan = 0; scan < sourceLength; scan++) // walk through the
                // source
                { // string and compare each char
                    if (source[scan] == temp)
                    {
                        status = NOT_DONE;
                    }
                }
            }
            return (position);
        }
        return (0);
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method scans the input string until the max allowed width is reached. The return value
     * indicates the position just before this happens.
     *
     * @param word word to break
     * @return position character position just before the string is too long
     */
    /*-------------------------------------------------------------------*
     * <detailed description / implementation details if applicable>
     *-------------------------------------------------------------------*/
    int breakWord(String word, FontMetrics fm)
    {
        int width;
        int currentPos;
        int endPos;
        width = 0;
        currentPos = 0;
        endPos = word.length() - 1;
        // make sure we don"t end up with a negative position
        if (endPos <= 0)
        {
            return (currentPos);
        }
        // seek the position where the word first is longer than allowed
        while ((width < maxAllowed) && (currentPos < endPos))
        {
            currentPos++;
            width = fm.stringWidth(labelText.substring(0, currentPos));
        }
        // adjust to get the chatacter just before (this should make it a bit
        // shorter than allowed!)
        if (currentPos != endPos)
        {
            currentPos--;
        }
        return (currentPos);
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method breaks the label text up into multiple lines of text. Line breaks are established
     * based on the maximum available space. A new line is started whenever a line break is
     * encountered, even if the permissible length is not yet reached. Words are broken only if a
     * single word happens to be longer than one line.
     */
    /*-------------------------------------------------------------------*/
    private void divideLabel()
    {
        int width;
        int startPos;
        int currentPos;
        int lastPos;
        int endPos;
        line.clear();
        FontMetrics fm = this.getFontMetrics(this.getFont());
        startPos = 0;
        currentPos = startPos;
        lastPos = currentPos;
        endPos = (labelText.length() - 1);
        while (currentPos < endPos)
        {
            width = 0;
            // ----------------------------------------------------------------
            // find the first substring that occupies more than the granted
            // space.
            // Break at the end of the string or a line break
            // ----------------------------------------------------------------
            while ((width < maxAllowed) && (currentPos < endPos)
                    && (labelText.charAt(currentPos) != NEW_LINE))
            {
                lastPos = currentPos;
                currentPos = getPosition(labelText, currentPos, WHITE_SPACE, FOUND);
                width = fm.stringWidth(labelText.substring(startPos, currentPos));
            }
            // ----------------------------------------------------------------
            // if we have a line break we want to copy everything up to
            // currentPos
            // ----------------------------------------------------------------
            if (labelText.charAt(currentPos) == NEW_LINE)
            {
                lastPos = currentPos;
            }
            // ----------------------------------------------------------------
            // if we are at the end of the string we want to copy everything up
            // to
            // the last character. Since there seems to be a problem to get the
            // last
            // character if the substring definition ends at the very last
            // character
            // we have to call a different substring function than normal.
            // ----------------------------------------------------------------
            if (currentPos == endPos && width <= maxAllowed)
            {
                lastPos = currentPos;
                String s = labelText.substring(startPos);
                line.addElement(s);
            }
            // ----------------------------------------------------------------
            // in all other cases copy the substring that we have found to fit
            // and
            // add it as a new line of text to the line vector.
            // ----------------------------------------------------------------
            else
            {
                // ------------------------------------------------------------
                // make sure it"s not a single word. If so we must break it at
                // the
                // proper location.
                // ------------------------------------------------------------
                if (lastPos == startPos)
                {
                    lastPos = startPos + breakWord(labelText.substring(startPos, currentPos), fm);
                }
                String s = labelText.substring(startPos, lastPos);
                line.addElement(s);
            }
            // ----------------------------------------------------------------
            // seek for the end of the white space to cut out any unnecessary
            // spaces
            // and tabs and set the new start condition.
            // ----------------------------------------------------------------
            startPos = getPosition(labelText, lastPos, SPACES, NOT_FOUND);
            currentPos = startPos;
        }
        numLines = line.size();
        lineWidth = new int[numLines];
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method finds the font size, each line width and the widest line.
     */
    /*-------------------------------------------------------------------*/
    protected void measure()
    {
        if (!maxAllowedSet)
        {
            maxAllowed = getParent().getSize().width;
        }
        // return if width is too small
        if (maxAllowed < (20))
        {
            return;
        }
        FontMetrics fm = this.getFontMetrics(this.getFont());
        // return if no font metrics available
        if (fm == null)
        {
            return;
        }
        divideLabel();
        this.lineHeight = fm.getHeight();
        this.lineDescent = fm.getDescent();
        this.maxWidth = 0;
        for (int i = 0; i < numLines; i++)
        {
            this.lineWidth[i] = fm.stringWidth(this.line.elementAt(i));
            if (this.lineWidth[i] > this.maxWidth)
            {
                this.maxWidth = this.lineWidth[i];
            }
        }
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method draws the label.
     *
     * @param graphics the device context
     */
    /*-------------------------------------------------------------------*/
    public void paint(Graphics graphics)
    {
        int x;
        int y;
        measure();
        Dimension d = this.getSize();
        y = lineAscent + (d.height - (numLines * lineHeight)) / 2;
        for (int i = 0; i < numLines; i++)
        {
            y += lineHeight;
            switch (alignment)
            {
                case LEFT:
                    x = marginWidth;
                    break;
                case CENTER:
                    x = (d.width - lineWidth[i]) / 2;
                    break;
                case RIGHT:
                    x = d.width - marginWidth - lineWidth[i];
                    break;
                default:
                    x = (d.width - lineWidth[i]) / 2;
            }
            graphics.drawString(line.elementAt(i), x, y);
        }
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method may be used to set the label text
     *
     * @param labelText the text to be displayed
     */
    /*-------------------------------------------------------------------*/
    public void setText(String labelText)
    {
        this.labelText = labelText;
        repaint();
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method may be used to set the font that should be used to draw the label
     *
     * @param font font to be used within the label
     */
    /*-------------------------------------------------------------------*/
    public void setFont(Font font)
    {
        super.setFont(font);
        repaint();
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method may be used to set the color in which the text should be drawn
     *
     * @param color the text color
     */
    /*-------------------------------------------------------------------*/
    public void setColor(Color color)
    {
        super.setForeground(color);
        repaint();
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method may be used to set the text alignment for the label
     *
     * @param alignment the alignment, possible values are LEFT, CENTER, RIGHT
     */
    /*-------------------------------------------------------------------*/
    public void setJustify(int alignment)
    {
        this.alignment = alignment;
        repaint();
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method may be used to set the max allowed line width
     *
     * @param width the max allowed line width in pixels
     */
    /*-------------------------------------------------------------------*/
    public void setMaxWidth(int width)
    {
        this.maxAllowed = width;
        this.maxAllowedSet = true;
        repaint();
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method may be used to set the horizontal margin
     *
     * @param margin the margin to the left and to the right of the label
     */
    /*-------------------------------------------------------------------*/
    public void setMarginWidth(int margin)
    {
        this.marginWidth = margin;
        repaint();
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method may be used to set the vertical margin for the label
     *
     * @param margin the margin on the top and bottom of the label
     */
    /*-------------------------------------------------------------------*/
    public void setMarginHeight(int margin)
    {
        this.marginHeight = margin;
        repaint();
    }
    /*-------------------------------------------------------------------*/
    /**
     * Moves and resizes this component. The new location of the top-left corner is specified by
     * <code>x</code> and <code>y</code>, and the new size is specified by <code>width</code>
     * and <code>height</code>.
     *
     * @param x      The new x-coordinate of this component.
     * @param y      The new y-coordinate of this component.
     * @param width  The new width of this component.
     * @param height The new height of this component.
     */
    /*-------------------------------------------------------------------*/
    public void setBounds(int x, int y, int width, int height)
    {
        super.setBounds(x, y, width, height);
        this.maxAllowed = width;
        this.maxAllowedSet = true;
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method may be used to retrieve the text alignment for the label
     *
     * @return alignment the text alignment currently in use for the label
     */
    /*-------------------------------------------------------------------*/
    public int getAlignment()
    {
        return (this.alignment);
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method may be used to retrieve the horizontal margin for the label
     *
     * @return marginWidth the margin currently in use to the left and right of the label
     */
    /*-------------------------------------------------------------------*/
    public int getMarginWidth()
    {
        return (this.marginWidth);
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method may be used to retrieve the vertical margin for the label
     *
     * @return marginHeight the margin currently in use on the top and bottom of the label
     */
    /*-------------------------------------------------------------------*/
    public int getMarginHeight()
    {
        return (this.marginHeight);
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method is typically used by the layout manager, it reports the necessary space to
     * display the label comfortably.
     */
    /*-------------------------------------------------------------------*/
    public Dimension getPreferredSize()
    {
        measure();
        return (new Dimension(maxAllowed, (numLines * (lineHeight + lineAscent + lineDescent))
                + (2 * marginHeight)));
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method is typically used by the layout manager, it reports the absolute minimum space
     * required to display the entire label.
     */
    /*-------------------------------------------------------------------*/
    public Dimension getMinimumSize()
    {
        measure();
        return (new Dimension(maxAllowed, (numLines * (lineHeight + lineAscent + lineDescent))
                + (2 * marginHeight)));
    }
    /*-------------------------------------------------------------------*/
    /**
     * This method is called by the system after this object is first created.
     */
    /*-------------------------------------------------------------------*/
    public void addNotify()
    {
        super.addNotify(); // invoke the superclass
    }
}
/*---------------------------------------------------------------------------*/





Multi Line Label extends JPanel

  
/*
 This file is part of the BlueJ program. 
 Copyright (C) 1999-2009  Michael K�lling and John Rosenberg 
 
 This program is free software; you can redistribute it and/or 
 modify it under the terms of the GNU General Public License 
 as published by the Free Software Foundation; either version 2 
 of the License, or (at your option) any later version. 
 
 This program is distributed in the hope that it will be useful, 
 but WITHOUT ANY WARRANTY; without even the implied warranty of 
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 GNU General Public License for more details. 
 
 You should have received a copy of the GNU General Public License 
 along with this program; if not, write to the Free Software 
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA. 
 
 This file is subject to the Classpath exception as provided in the  
 LICENSE.txt file that accompanied this code.
 */
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Font;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
 ** @version $Id: MultiLineLabel.java 6164 2009-02-19 18:11:32Z polle $
 ** @author Justin Tan
 ** A multi-line Label-like AWT component.
 **/
public class MultiLineLabel extends JPanel
{
    protected int fontAttributes = Font.PLAIN;
    protected float alignment;
    protected Color col = null;
  protected int spacing = 0;
    
    /**
     ** Constructor - make a multiline label
     **/
    public MultiLineLabel(String text, float alignment)
    {
        this.alignment = alignment;
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        if(text != null)
            setText(text);
    }
    /**
     ** Constructor, defaults to centered text
     **/
    public MultiLineLabel(String text)
    {
        this(text, LEFT_ALIGNMENT);
    }
    /**
     * Constructor, empty with the given alignment
     */
    public MultiLineLabel(float alignment)
    {
        this(null, alignment);
    }
    /**
     * Constructor, empty with the given alignment and line spacing
     */
    public MultiLineLabel(float alignment, int spacing)
    {
        this(null, alignment);
        this.spacing = spacing;
    }
    /**
     ** Constructor - make an empty multiline label
     **/
    public MultiLineLabel()
    {
        this(null, LEFT_ALIGNMENT);
    }
  
    public void setText(String text)
    {
        // clear the existing lines from the panel
        removeAll();
        addText(text);
    }
  
    public void addText(String text)
    {
        addText(text, 12);
    }
    
    public void addText(String text, int size)
    {
        if(spacing > 0)
            add(Box.createVerticalStrut(spacing));
        String strs[] = splitLines(text);
        JLabel l;
        Font font = new Font("SansSerif", fontAttributes, size);
        for (int i = 0; strs != null && i < strs.length; i++) {
            l = new JLabel(strs[i]);
            l.setFont(font);
            l.setAlignmentX(alignment);
            if (col != null)
                l.setForeground(col);
            add(l);
        }   
    }
    /**
     * Splits "string" by "Delimiter"
     * 
     * @param str - the string to be split
     * @param delimiter - the field delimiter within str
     * @returns an array of Strings
     */
    public static String[] split(String str, String delimiter)
    {
        List<String> strings = new ArrayList<String>();
        int start = 0;
        int len = str.length();
        int dlen = delimiter.length();
        int offset = str.lastIndexOf(delimiter); // First of all, find the
        // Last occurance of the Delimiter
        // Stop empty delimiters
        if (dlen < 1)
            return null;
        else if (offset < 0) // one element
        {
            String[] result = {str};
            return result;
        }
        //
        // Append the delimiter onto the end if it doesn"t already exit
        //
        if (len > offset + dlen) {
            str += delimiter;
            len += dlen;
        }
        do {
            // Get the new Offset
            offset = str.indexOf(delimiter, start);
            strings.add(str.substring(start, offset));
            // Get the new Start position
            start = offset + dlen;
        } while ((start < len) && (offset != -1));
        // Convert the list into an Array of Strings
        String result[] = new String[strings.size()];
        strings.toArray(result);
        return result;
    }
    /**
     * Splits "string" into lines (stripping end-of-line characters)
     * 
     * @param str - the string to be split
     * @returns an array of Strings
     */
    public static String[] splitLines(String str)
    {
        return (str == null ? null : split(str, "\n"));
    }
    public void addText(String text, boolean bold, boolean italic)
    {
        int oldAttributes = fontAttributes;
        setBold(bold);
        setItalic(italic);
        addText(text);
        fontAttributes = oldAttributes;
    }
    public void setForeground(Color col)
    {
        this.col = col;    
        Component[] components = this.getComponents();
        for (int i = 0; i < components.length; i++) {
      Component component = components[i];
      component.setForeground(col);
    }
    }
      
    public void setItalic(boolean italic)
    {
        if(italic)
           fontAttributes |= Font.ITALIC;
        else
            fontAttributes &= ~Font.ITALIC;
    }
  
    public void setBold(boolean bold)
    {
        if(bold)
            fontAttributes |= Font.BOLD;
        else
            fontAttributes &= ~Font.BOLD;
    }
}





URL Label

  
//The contents of this file are subject to the Mozilla Public License Version 1.1
//(the "License"); you may not use this file except in compliance with the 
//License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
//
//Software distributed under the License is distributed on an "AS IS" basis,
//WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 
//for the specific language governing rights and
//limitations under the License.
//
//The Original Code is "The Columba Project"
//
//The Initial Developers of the Original Code are Frederik Dietz and Timo Stich.
//Portions created by Frederik Dietz and Timo Stich are Copyright (C) 2003. 
//
//All Rights Reserved.
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.net.URL;
import javax.swing.JLabel;
public class URLLabel extends JLabel {
  boolean entered = false;
  boolean mousehover;
  public URLLabel(URL url) {
    this(url, url.toString());
  }
  public URLLabel(URL url, String str) {
    super(str);
    setForeground(Color.blue);
    mousehover = false;
  }
  public void mouseEntered(MouseEvent e) {
    setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    entered = true;
    if (mousehover) {
      repaint();
    }
  }
  public void mouseExited(MouseEvent e) {
    setCursor(Cursor.getDefaultCursor());
    entered = false;
    if (mousehover) {
      repaint();
    }
  }
  public void mousePressed(MouseEvent e) {
  }
  public void mouseReleased(MouseEvent e) {
  }
  public void paint(Graphics g) {
    super.paint(g);
    if (entered || !mousehover) {
      Rectangle r = g.getClipBounds();
      g.drawLine(0, r.height - this.getFontMetrics(this.getFont()).getDescent(), this
          .getFontMetrics(this.getFont()).stringWidth(this.getText()), r.height
          - this.getFontMetrics(this.getFont()).getDescent());
    }
  }
}





Vertical Label UI

  
/*
 * The contents of this file are subject to the Sapient Public License
 * Version 1.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 * http://carbon.sf.net/License.html.
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 *
 * The Original Code is The Carbon Component Framework.
 *
 * The Initial Developer of the Original Code is Sapient Corporation
 *
 * Copyright (C) 2003 Sapient Corporation. All Rights Reserved.
 */

import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.plaf.basic.BasicLabelUI;
/**
 * <p>This is the template for Classes.</p>
 *
 *
 * @since carbon 1.0
 * @author Greg Hinkle, January 2002
 * @version $Revision: 1.4 $($Author: dvoet $ / $Date: 2003/05/05 21:21:27 $)
 * @copyright 2002 Sapient
 */
public class VerticalLabelUI extends BasicLabelUI {
    static {
        labelUI = new VerticalLabelUI(false);
    }
    protected boolean clockwise;

    public VerticalLabelUI(boolean clockwise) {
        super();
        this.clockwise = clockwise;
    }

    public Dimension getPreferredSize(JComponent c) {
        Dimension dim = super.getPreferredSize(c);
        return new Dimension( dim.height, dim.width );
    }
    private static Rectangle paintIconR = new Rectangle();
    private static Rectangle paintTextR = new Rectangle();
    private static Rectangle paintViewR = new Rectangle();
    private static Insets paintViewInsets = new Insets(0, 0, 0, 0);
    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;
        }
        FontMetrics fm = g.getFontMetrics();
        paintViewInsets = c.getInsets(paintViewInsets);
        paintViewR.x = paintViewInsets.left;
        paintViewR.y = paintViewInsets.top;
        // Use inverted height & width
        paintViewR.height = c.getWidth() - (paintViewInsets.left + paintViewInsets.right);
        paintViewR.width = c.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);
        paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0;
        paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0;
        String clippedText =
            layoutCL(label, fm, text, icon, paintViewR, paintIconR, paintTextR);
        Graphics2D g2 = (Graphics2D) g;
        AffineTransform tr = g2.getTransform();
        if (clockwise) {
            g2.rotate( Math.PI / 2 );
            g2.translate( 0, - c.getWidth() );
        } else {
            g2.rotate( - Math.PI / 2 );
            g2.translate( - c.getHeight(), 0 );
        }
        if (icon != null) {
            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, textX, textY);
            } else {
                paintDisabledText(label, g, clippedText, textX, textY);
            }
        }
        g2.setTransform( tr );
    }
}