BasicLabelUI.java 16.8 KB
Newer Older
Tom Tromey committed
1
/* BasicLabelUI.java
2
 Copyright (C) 2002, 2004, 2006, Free Software Foundation, Inc.
Tom Tromey committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

 This file is part of GNU Classpath.

 GNU Classpath 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, or (at your option)
 any later version.

 GNU Classpath 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 GNU Classpath; see the file COPYING.  If not, write to the
 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 02110-1301 USA.

 Linking this library statically or dynamically with other modules is
 making a combined work based on this library.  Thus, the terms and
 conditions of the GNU General Public License cover the whole
 combination.

 As a special exception, the copyright holders of this library give you
 permission to link this library with independent modules to produce an
 executable, regardless of the license terms of these independent
 modules, and to copy and distribute the resulting executable under
 terms of your choice, provided that you also meet, for each linked
 independent module, the terms and conditions of the license of that
 module.  An independent module is a module which is not derived from
 or based on this library.  If you modify this library, you may extend
 this exception to your version of the library, but you are not
 obligated to do so.  If you do not wish to do so, delete this
 exception statement from your version. */
Tom Tromey committed
37 38 39

package javax.swing.plaf.basic;

40
import java.awt.Component;
Tom Tromey committed
41
import java.awt.Dimension;
42
import java.awt.Font;
Tom Tromey committed
43 44 45 46
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
47
import java.awt.Toolkit;
48 49
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
Tom Tromey committed
50 51 52
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

53 54
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
Tom Tromey committed
55
import javax.swing.Icon;
56
import javax.swing.InputMap;
Tom Tromey committed
57 58
import javax.swing.JComponent;
import javax.swing.JLabel;
59
import javax.swing.KeyStroke;
60
import javax.swing.LookAndFeel;
Tom Tromey committed
61 62 63
import javax.swing.SwingUtilities;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.LabelUI;
64
import javax.swing.text.View;
Tom Tromey committed
65 66 67 68 69

/**
 * This is the Basic Look and Feel class for the JLabel.  One BasicLabelUI
 * object is used to paint all JLabels that utilize the Basic Look and Feel.
 */
70
public class BasicLabelUI extends LabelUI implements PropertyChangeListener
Tom Tromey committed
71 72 73 74 75
{
  /** The labelUI that is shared by all labels. */
  protected static BasicLabelUI labelUI;

  /**
76 77 78 79 80 81 82 83
   * These fields hold the rectangles for the whole label,
   * the icon and the text.
   */
  private Rectangle vr;
  private Rectangle ir;
  private Rectangle tr;

  /**
84 85 86 87 88
   * A cached Insets object for reuse in the label layout methods.
   */
  private Insets cachedInsets;

  /**
Tom Tromey committed
89 90 91 92 93
   * Creates a new BasicLabelUI object.
   */
  public BasicLabelUI()
  {
    super();
94 95 96
    vr = new Rectangle();
    ir = new Rectangle();
    tr = new Rectangle();
Tom Tromey committed
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
  }

  /**
   * Creates and returns a UI for the label. Since one UI is shared by  all
   * labels, this means creating only if necessary and returning the  shared
   * UI.
   *
   * @param c The {@link JComponent} that a UI is being created for.
   *
   * @return A label UI for the Basic Look and Feel.
   */
  public static ComponentUI createUI(JComponent c)
  {
    if (labelUI == null)
      labelUI = new BasicLabelUI();
    return labelUI;
  }

  /**
   * Returns the preferred size of this component as calculated by the
   * {@link #layoutCL(JLabel, FontMetrics, String, Icon, Rectangle, Rectangle, 
   * Rectangle)} method.
   *
   * @param c This {@link JComponent} to get a preferred size for.
   *
   * @return The preferred size.
   */
Tom Tromey committed
124
  public Dimension getPreferredSize(JComponent c)
Tom Tromey committed
125
  {
Tom Tromey committed
126 127
    JLabel lab = (JLabel) c;
    Insets insets = lab.getInsets();
128 129 130 131 132 133 134 135 136 137 138 139
    int insetsX = insets.left + insets.right;
    int insetsY = insets.top + insets.bottom;
    Icon icon = lab.getIcon();
    String text = lab.getText();
    Dimension ret;
    if (icon == null && text == null)
      ret = new Dimension(insetsX, insetsY);
    else if (icon != null && text == null)
      ret = new Dimension(icon.getIconWidth() + insetsX,
                          icon.getIconHeight() + insetsY);
    else
      {
140
        FontMetrics fm = getFontMetrics(lab);
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
        ir.x = 0;
        ir.y = 0;
        ir.width = 0;
        ir.height = 0;
        tr.x = 0;
        tr.y = 0;
        tr.width = 0;
        tr.height = 0;
        vr.x = 0;
        vr.y = 0;
        vr.width = Short.MAX_VALUE;
        vr.height = Short.MAX_VALUE;
        layoutCL(lab, fm, text, icon, vr, ir, tr);
        Rectangle cr = SwingUtilities.computeUnion(tr.x, tr.y, tr.width,
                                                   tr.height, ir);
        ret = new Dimension(cr.width + insetsX, cr.height + insetsY);
      }
    return ret;
Tom Tromey committed
159
  }
Tom Tromey committed
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190

  /**
   * This method returns the minimum size of the {@link JComponent} given. If
   * this method returns null, then it is up to the Layout Manager to give
   * this component a minimum size.
   *
   * @param c The {@link JComponent} to get a minimum size for.
   *
   * @return The minimum size.
   */
  public Dimension getMinimumSize(JComponent c)
  {
    return getPreferredSize(c);
  }

  /**
   * This method returns the maximum size of the {@link JComponent} given. If
   * this method returns null, then it is up to the Layout Manager to give
   * this component a maximum size.
   *
   * @param c The {@link JComponent} to get a maximum size for.
   *
   * @return The maximum size.
   */
  public Dimension getMaximumSize(JComponent c)
  {
    return getPreferredSize(c);
  }

  /**
   * The method that paints the label according to its current state.
Tom Tromey committed
191
   * 
Tom Tromey committed
192 193 194 195 196 197 198
   * @param g The {@link Graphics} object to paint with.
   * @param c The {@link JComponent} to paint.
   */
  public void paint(Graphics g, JComponent c)
  {
    JLabel b = (JLabel) c;
    Icon icon = (b.isEnabled()) ? b.getIcon() : b.getDisabledIcon();
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    String text = b.getText();
    if (icon != null || (text != null && ! text.equals("")))
      {
        FontMetrics fm = getFontMetrics(b);
        Insets i = c.getInsets(cachedInsets);
        vr.x = i.left;
        vr.y = i.right;
        vr.width = c.getWidth() - i.left - i.right;
        vr.height = c.getHeight() - i.top - i.bottom;
        ir.x = 0;
        ir.y = 0;
        ir.width = 0;
        ir.height = 0;
        tr.x = 0;
        tr.y = 0;
        tr.width = 0;
        tr.height = 0;
Tom Tromey committed
216

217
        text = layoutCL(b, fm, text, icon, vr, ir, tr);
Tom Tromey committed
218

219 220
        if (icon != null)
          icon.paintIcon(b, g, ir.x, ir.y);       
Tom Tromey committed
221

222
        if (text != null && ! text.equals(""))
223
          {
224 225 226 227 228 229 230 231
            Object htmlRenderer = b.getClientProperty(BasicHTML.propertyKey);
            if (htmlRenderer == null)
              {
                if (b.isEnabled())
                  paintEnabledText(b, g, text, tr.x, tr.y + fm.getAscent());
                else
                  paintDisabledText(b, g, text, tr.x, tr.y + fm.getAscent());
              }
232
            else
233 234 235
              {
                ((View) htmlRenderer).paint(g, tr);
              }
236 237
          }
      }
Tom Tromey committed
238 239 240 241
  }

  /**
   * This method is simply calls SwingUtilities's layoutCompoundLabel.
Tom Tromey committed
242
   * 
Tom Tromey committed
243 244 245 246 247 248 249
   * @param label The label to lay out.
   * @param fontMetrics The FontMetrics for the font used.
   * @param text The text to paint.
   * @param icon The icon to draw.
   * @param viewR The entire viewable rectangle.
   * @param iconR The icon bounds rectangle.
   * @param textR The text bounds rectangle.
Tom Tromey committed
250
   * 
Tom Tromey committed
251 252
   * @return A possibly clipped version of the text.
   */
Tom Tromey committed
253 254
  protected String layoutCL(JLabel label, FontMetrics fontMetrics, String text,
      Icon icon, Rectangle viewR, Rectangle iconR, Rectangle textR)
Tom Tromey committed
255 256
  {
    return SwingUtilities.layoutCompoundLabel(label, fontMetrics, text, icon,
Tom Tromey committed
257 258 259
        label.getVerticalAlignment(), label.getHorizontalAlignment(), label
            .getVerticalTextPosition(), label.getHorizontalTextPosition(),
        viewR, iconR, textR, label.getIconTextGap());
Tom Tromey committed
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
  }

  /**
   * Paints the text if the label is disabled. By default, this paints the
   * clipped text returned by layoutCompoundLabel using the
   * background.brighter() color. It also paints the same text using the
   * background.darker() color one pixel to the right and one pixel down.
   *
   * @param l The {@link JLabel} being painted.
   * @param g The {@link Graphics} object to paint with.
   * @param s The String to paint.
   * @param textX The x coordinate of the start of the baseline.
   * @param textY The y coordinate of the start of the baseline.
   */
  protected void paintDisabledText(JLabel l, Graphics g, String s, int textX,
Tom Tromey committed
275
      int textY)
Tom Tromey committed
276 277 278 279 280 281 282
  {
    g.setColor(l.getBackground().brighter());

    int mnemIndex = l.getDisplayedMnemonicIndex();

    if (mnemIndex != -1)
      BasicGraphicsUtils.drawStringUnderlineCharAt(g, s, mnemIndex, textX,
Tom Tromey committed
283
          textY);
Tom Tromey committed
284 285 286 287 288 289
    else
      g.drawString(s, textX, textY);

    g.setColor(l.getBackground().darker());
    if (mnemIndex != -1)
      BasicGraphicsUtils.drawStringUnderlineCharAt(g, s, mnemIndex, textX + 1,
Tom Tromey committed
290
          textY + 1);
Tom Tromey committed
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    else
      g.drawString(s, textX + 1, textY + 1);
  }

  /**
   * Paints the text if the label is enabled. The text is painted using the
   * foreground color.
   *
   * @param l The {@link JLabel} being painted.
   * @param g The {@link Graphics} object to paint with.
   * @param s The String to paint.
   * @param textX The x coordinate of the start of the baseline.
   * @param textY The y coordinate of the start of the baseline.
   */
  protected void paintEnabledText(JLabel l, Graphics g, String s, int textX,
306
                                  int textY)
Tom Tromey committed
307 308 309 310 311 312 313
  {
    g.setColor(l.getForeground());

    int mnemIndex = l.getDisplayedMnemonicIndex();

    if (mnemIndex != -1)
      BasicGraphicsUtils.drawStringUnderlineCharAt(g, s, mnemIndex, textX,
Tom Tromey committed
314
          textY);
Tom Tromey committed
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
    else
      g.drawString(s, textX, textY);
  }

  /**
   * This method installs the UI for the given {@link JComponent}.  This
   * method will install the component, defaults, listeners,  and keyboard
   * actions.
   *
   * @param c The {@link JComponent} that this UI is being installed on.
   */
  public void installUI(JComponent c)
  {
    super.installUI(c);
    if (c instanceof JLabel)
Tom Tromey committed
330 331 332 333 334 335 336 337
    {
      JLabel l = (JLabel) c;

      installComponents(l);
      installDefaults(l);
      installListeners(l);
      installKeyboardActions(l);
    }
Tom Tromey committed
338 339 340 341 342 343 344 345 346 347 348 349 350
  }

  /**
   * This method uninstalls the UI for the given {@link JComponent}. This
   * method will uninstall the component, defaults, listeners,  and keyboard
   * actions.
   *
   * @param c The {@link JComponent} that this UI is being installed on.
   */
  public void uninstallUI(JComponent c)
  {
    super.uninstallUI(c);
    if (c instanceof JLabel)
Tom Tromey committed
351 352 353 354 355 356 357 358
    {
      JLabel l = (JLabel) c;

      uninstallKeyboardActions(l);
      uninstallListeners(l);
      uninstallDefaults(l);
      uninstallComponents(l);
    }
Tom Tromey committed
359 360 361 362 363 364 365 366 367
  }

  /**
   * This method installs the components for this {@link JLabel}.
   *
   * @param c The {@link JLabel} to install components for.
   */
  protected void installComponents(JLabel c)
  {
368
    BasicHTML.updateRenderer(c, c.getText());
Tom Tromey committed
369 370 371 372 373 374 375 376 377
  }

  /**
   * This method uninstalls the components for this {@link JLabel}.
   *
   * @param c The {@link JLabel} to uninstall components for.
   */
  protected void uninstallComponents(JLabel c)
  {
378 379
    c.putClientProperty(BasicHTML.propertyKey, null);
    c.putClientProperty(BasicHTML.documentBaseKey, null);
Tom Tromey committed
380 381 382 383 384 385 386 387 388 389
  }

  /**
   * This method installs the defaults that are defined in  the Basic look and
   * feel for this {@link JLabel}.
   *
   * @param c The {@link JLabel} to install defaults for.
   */
  protected void installDefaults(JLabel c)
  {
390 391
    LookAndFeel.installColorsAndFont(c, "Label.background", "Label.foreground",
                                     "Label.font");
Tom Tromey committed
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
    //XXX: There are properties we don't use called disabledForeground
    //and disabledShadow.
  }

  /**
   * This method uninstalls the defaults that are defined in the Basic look
   * and feel for this {@link JLabel}.
   *
   * @param c The {@link JLabel} to uninstall defaults for.
   */
  protected void uninstallDefaults(JLabel c)
  {
    c.setForeground(null);
    c.setBackground(null);
    c.setFont(null);
  }

  /**
410
   * Installs the keyboard actions for the given {@link JLabel}.
Tom Tromey committed
411 412 413 414 415
   *
   * @param l The {@link JLabel} to install keyboard actions for.
   */
  protected void installKeyboardActions(JLabel l)
  {
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
    Component c = l.getLabelFor();
    if (c != null)
      {
        int mnemonic = l.getDisplayedMnemonic();
        if (mnemonic > 0)
          {
            // add a keystroke for the given mnemonic mapping to 'press';
            InputMap keyMap = new InputMap();
            keyMap.put(KeyStroke.getKeyStroke(mnemonic, KeyEvent.VK_ALT), 
                "press");
            SwingUtilities.replaceUIInputMap(l, 
                JComponent.WHEN_IN_FOCUSED_WINDOW, keyMap);
            
            // add an action to focus the component when 'press' happens
            ActionMap map = new ActionMap();
            map.put("press", new AbstractAction() {
              public void actionPerformed(ActionEvent event)
              {
                JLabel label = (JLabel) event.getSource();
                Component c = label.getLabelFor();
                if (c != null)
                  c.requestFocus();
              }
            });
            SwingUtilities.replaceUIActionMap(l, map);
          }
      }   
Tom Tromey committed
443 444 445 446 447 448 449 450 451
  }

  /**
   * This method uninstalls the keyboard actions for the given {@link JLabel}.
   *
   * @param l The {@link JLabel} to uninstall keyboard actions for.
   */
  protected void uninstallKeyboardActions(JLabel l)
  {
452 453 454
    SwingUtilities.replaceUIActionMap(l, null);
    SwingUtilities.replaceUIInputMap(l, JComponent.WHEN_IN_FOCUSED_WINDOW, 
                                     null);
Tom Tromey committed
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
  }

  /**
   * This method installs the listeners for the  given {@link JLabel}. The UI
   * delegate only listens to  the label.
   *
   * @param c The {@link JLabel} to install listeners for.
   */
  protected void installListeners(JLabel c)
  {
    c.addPropertyChangeListener(this);
  }

  /**
   * This method uninstalls the listeners for the given {@link JLabel}. The UI
   * delegate only listens to the label.
   *
   * @param c The {@link JLabel} to uninstall listeners for.
   */
  protected void uninstallListeners(JLabel c)
  {
    c.removePropertyChangeListener(this);
  }

  /**
   * This method is called whenever any JLabel's that use this UI has one of
   * their properties change.
   *
   * @param e The {@link PropertyChangeEvent} that describes the change.
   */
  public void propertyChange(PropertyChangeEvent e)
  {
487 488 489 490 491 492
    if (e.getPropertyName().equals("text"))
      {
        String text = (String) e.getNewValue();
        JLabel l = (JLabel) e.getSource();
        BasicHTML.updateRenderer(l, text);
      }
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
    else if (e.getPropertyName().equals("displayedMnemonic"))
      {
        // update the key to action mapping
        JLabel label = (JLabel) e.getSource();
        if (label.getLabelFor() != null)
          {
            int oldMnemonic = ((Integer) e.getOldValue()).intValue();
            int newMnemonic = ((Integer) e.getNewValue()).intValue();
            InputMap keyMap = label.getInputMap(
                JComponent.WHEN_IN_FOCUSED_WINDOW);
            keyMap.put(KeyStroke.getKeyStroke(oldMnemonic, 
                KeyEvent.ALT_DOWN_MASK), null);
            keyMap.put(KeyStroke.getKeyStroke(newMnemonic, 
                KeyEvent.ALT_DOWN_MASK), "press");
          }
      }
    else if (e.getPropertyName().equals("labelFor"))
      {
        JLabel label = (JLabel) e.getSource();
        InputMap keyMap = label.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        int mnemonic = label.getDisplayedMnemonic();
        if (mnemonic > 0)
          keyMap.put(KeyStroke.getKeyStroke(mnemonic, KeyEvent.ALT_DOWN_MASK), 
              "press");       
      }
Tom Tromey committed
518
  }
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541

  /**
   * Fetches a font metrics object for the specified label. This first
   * tries to get it from the label object itself by calling
   * {@link Component#getFontMetrics(Font)}, and if that does not work
   * (for instance, when we are in the initialization and have no parent yet),
   * it asks the Toolkit for a font metrics object.
   *
   * @param l the label
   *
   * @return a suitable font metrics object
   */
  private FontMetrics getFontMetrics(JLabel l)
  {
    Font font = l.getFont();
    FontMetrics fm = l.getFontMetrics(font);
    if (fm == null)
      {
        Toolkit tk = Toolkit.getDefaultToolkit();
        fm = tk.getFontMetrics(font);
      }
    return fm;
  }
Tom Tromey committed
542
}