swingutilities2.java

来自「JAVA的一些源码 JAVA2 STANDARD EDITION DEVELO」· Java 代码 · 共 1,148 行 · 第 1/3 页

JAVA
1,148
字号
/* * @(#)SwingUtilities2.java	1.29 06/04/18 * * Copyright 2005 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */package com.sun.java.swing;import java.security.*;import java.lang.reflect.*;import java.awt.*;import java.awt.event.*;import java.awt.font.*;import java.awt.geom.*;import java.awt.print.PrinterGraphics;import java.text.AttributedCharacterIterator;import javax.swing.*;import javax.swing.plaf.*;import javax.swing.text.Highlighter;import javax.swing.text.JTextComponent;import javax.swing.text.DefaultHighlighter;import javax.swing.text.DefaultCaret;import javax.swing.table.TableCellRenderer;import sun.swing.PrintColorUIResource;import sun.print.ProxyPrintGraphics;import sun.awt.AppContext;import sun.font.FontDesignMetrics;import sun.java2d.SunGraphics2D;import sun.security.action.GetPropertyAction;import sun.security.util.SecurityConstants;import java.io.*;/** * A collection of utility methods for Swing. * <p> * <b>WARNING:</b> While this class is public, it should not be treated as * public API and its API may change in incompatable ways between dot dot * releases and even patch releases. You should not rely on this class even * existing. * * @version 1.29 04/18/06 */public class SwingUtilities2 {    // Maintain a cache of CACHE_SIZE fonts and the left side bearing    // of the characters falling into the range MIN_CHAR_INDEX to    // MAX_CHAR_INDEX. The values in fontCache are created as needed.    private static LSBCacheEntry[] fontCache;    // Windows defines 6 font desktop properties, we will therefore only    // cache the metrics for 6 fonts.    private static final int CACHE_SIZE = 6;    // nextIndex in fontCache to insert a font into.    private static int nextIndex;    // LSBCacheEntry used to search in fontCache to see if we already    // have an entry for a particular font    private static LSBCacheEntry searchKey;    // getLeftSideBearing will consult all characters that fall in the    // range MIN_CHAR_INDEX to MAX_CHAR_INDEX.    private static final int MIN_CHAR_INDEX = (int)'W';    private static final int MAX_CHAR_INDEX = (int)'W' + 1;    private static final FontRenderContext DEFAULT_FRC = new FontRenderContext(                             null, false, false);    /**     * FontRenderContext with antialiased turned on.     */    public static final FontRenderContext AA_FRC;    //    // To determine if a JComponent should use AA text the following is    // used:    // 1. Is the system property 'swing.aatext' defined, return the value of    //    the system property.    // 2. Use the JComponent client property AA_TEXT_PROPERTY_KEY.  To     //    avoid having this property persist between look and feels changes    //    the value of this property is set to false in JComponent.setUI    //    /**     * Whether or not text is drawn anti-aliased.  This is only used if     * <code>AA_TEXT_DEFINED</code> is true.     */    private static final boolean AA_TEXT;    /**     * Whether or not the system property 'swing.aatext' is defined.     */    private static final boolean AA_TEXT_DEFINED;    /**     * Key used in client properties to indicate whether or not the component     * should use aa text.     */    public static final Object AA_TEXT_PROPERTY_KEY =                          new StringBuffer("AATextPropertyKey");    /**     * Used to tell a text component, being used as an editor for table     * or tree, how many clicks it took to start editing.     */    private static final StringBuilder SKIP_CLICK_COUNT =        new StringBuilder("skipClickCount");    /**     * Whether or not the system proprety 'sun.swing.enableImprovedDragGesture'     * is defined, indicating that we should enable the fix for 4521075     * and start drag recognition on the first press without requiring a     * selection.     */    public static final boolean DRAG_FIX;    // security stuff    private static Field inputEvent_CanAccessSystemClipboard_Field = null;    private static final String UntrustedClipboardAccess =         "UNTRUSTED_CLIPBOARD_ACCESS_KEY";    static {        fontCache = new LSBCacheEntry[CACHE_SIZE];        Object aa = java.security.AccessController.doPrivileged(               new GetPropertyAction("swing.aatext"));        AA_TEXT_DEFINED = (aa != null);        AA_TEXT = "true".equals(aa);        AA_FRC = new FontRenderContext(null, true, false);        Object dragFix = java.security.AccessController.doPrivileged(            new GetPropertyAction("sun.swing.enableImprovedDragGesture"));        DRAG_FIX = (dragFix != null);    }    //    // WARNING WARNING WARNING WARNING WARNING WARNING    // Many of the following methods are invoked from older API.     // As this older API was not passed a Component, a null Component may    // now be passsed in.  For example, SwingUtilities.computeStringWidth    // is implemented to call SwingUtilities2.stringWidth, the    // SwingUtilities variant does not take a JComponent, as such    // SwingUtilities2.stringWidth can be passed a null Component.    // In other words, if you add new functionality to these methods you    // need to gracefully handle null.    //    /**     * Returns whether or not text should be drawn antialiased.     *     * @param c JComponent to test.     * @return Whether or not text should be drawn antialiased for the     *         specified component.     */    private static boolean drawTextAntialiased(JComponent c) {        if (!AA_TEXT_DEFINED) {            if (c != null) {                // Check if the component wants aa text                return ((Boolean)c.getClientProperty(                                  AA_TEXT_PROPERTY_KEY)).booleanValue();            }            // No component, assume aa is off            return false;        }        // 'swing.aatext' was defined, use its value.        return AA_TEXT;    }    /**     * Returns whether or not text should be drawn antialiased.     *     * @param aaText Whether or not aa text has been turned on for the     *        component.     * @return Whether or not text should be drawn antialiased.     */    public static boolean drawTextAntialiased(boolean aaText) {        if (!AA_TEXT_DEFINED) {            // 'swing.aatext' wasn't defined, use the components aa text value.            return aaText;        }        // 'swing.aatext' was defined, use its value.        return AA_TEXT;    }    /**     * Returns the left side bearing of the first character of string. The     * left side bearing is calculated from the passed in     * FontMetrics.  If the passed in String is less than one     * character, this will throw a StringIndexOutOfBoundsException exception.     *     * @param c JComponent that will display the string     * @param fm FontMetrics used to measure the String width     * @param string String to get the left side bearing for.     */    public static int getLeftSideBearing(JComponent c, FontMetrics fm,                                         String string) {        return getLeftSideBearing(c, fm, string.charAt(0));    }    /**     * Returns the left side bearing of the first character of string. The     * left side bearing is calculated from the passed in FontMetrics.     *     * @param c JComponent that will display the string     * @param fm FontMetrics used to measure the String width     * @param char Character to get the left side bearing for.     */    public static int getLeftSideBearing(JComponent c, FontMetrics fm,                                         char firstChar) {        int charIndex = (int)firstChar;        if (charIndex < MAX_CHAR_INDEX && charIndex >= MIN_CHAR_INDEX) {            byte[] lsbs = null;            FontRenderContext frc = getFRC(c, fm);            Font font = fm.getFont();            synchronized(SwingUtilities2.class) {                LSBCacheEntry entry = null;                if (searchKey == null) {                    searchKey = new LSBCacheEntry(frc, font);                }                else {                    searchKey.reset(frc, font);                }                // See if we already have an entry for this pair                for (LSBCacheEntry cacheEntry : fontCache) {                    if (searchKey.equals(cacheEntry)) {                        entry = cacheEntry;                        break;                    }                }                if (entry == null) {                    // No entry for this pair, add it.                    entry = searchKey;                    fontCache[nextIndex] = searchKey;                    searchKey = null;                    nextIndex = (nextIndex + 1) % CACHE_SIZE;                }                return entry.getLeftSideBearing(firstChar);            }        }        return 0;    }    /**     * Returns the FontMetrics for the current Font of the passed     * in Graphics.  This method is used when a Graphics     * is available, typically when painting.  If a Graphics is not     * available the JComponent method of the same name should be used.     * <p>     * Callers should pass in a non-null JComponent, the exception     * to this is if a JComponent is not readily available at the time of     * painting.     * <p>     * This does not necessarily return the FontMetrics from the     * Graphics.     *     * @param c JComponent requesting FontMetrics, may be null     * @param g Graphics Graphics     */    public static FontMetrics getFontMetrics(JComponent c, Graphics g) {        return getFontMetrics(c, g, g.getFont());    }    /**     * Returns the FontMetrics for the specified Font.     * This method is used when a Graphics is available, typically when     * painting.  If a Graphics is not available the JComponent method of     * the same name should be used.     * <p>     * Callers should pass in a non-null JComonent, the exception     * to this is if a JComponent is not readily available at the time of     * painting.     * <p>     * This does not necessarily return the FontMetrics from the     * Graphics.     *     * @param c JComponent requesting FontMetrics, may be null     * @param c Graphics Graphics     * @param font Font to get FontMetrics for     */    public static FontMetrics getFontMetrics(JComponent c, Graphics g,                                             Font font) {        if (c != null) {            // Note: We assume that we're using the FontMetrics            // from the widget to layout out text, otherwise we can get            // mismatches when printing.            return c.getFontMetrics(font);        }        return Toolkit.getDefaultToolkit().getFontMetrics(font);    }    /**     * Returns the width of the passed in String.     *     * @param c JComponent that will display the string, may be null     * @param fm FontMetrics used to measure the String width     * @param string String to get the width of     */    public static int stringWidth(JComponent c, FontMetrics fm, String string){        return fm.stringWidth(string);    }    /**     * Clips the passed in String to the space provided.     *     * @param c JComponent that will display the string, may be null     * @param fm FontMetrics used to measure the String width     * @param string String to display     * @param availTextWidth Amount of space that the string can be drawn in     * @return Clipped string that can fit in the provided space.     */    public static String clipStringIfNecessary(JComponent c, FontMetrics fm,                                               String string,                                               int availTextWidth) {        if ((string == null) || (string.equals("")))  {            return "";        }        int textWidth = SwingUtilities2.stringWidth(c, fm, string);        if (textWidth > availTextWidth) {            return SwingUtilities2.clipString(c, fm, string, availTextWidth);        }        return string;    }    /**     * Clips the passed in String to the space provided.  NOTE: this assumes     * the string does not fit in the available space.     *     * @param c JComponent that will display the string, may be null     * @param fm FontMetrics used to measure the String width     * @param string String to display     * @param availTextWidth Amount of space that the string can be drawn in     * @return Clipped string that can fit in the provided space.     */    public static String clipString(JComponent c, FontMetrics fm,                                    String string, int availTextWidth) {        // c may be null here.        String clipString = "...";        int width = SwingUtilities2.stringWidth(c, fm, clipString);        // NOTE: This does NOT work for surrogate pairs and other fun        // stuff        int nChars = 0;        for(int max = string.length(); nChars < max; nChars++) {            width += fm.charWidth(string.charAt(nChars));            if (width > availTextWidth) {                break;            }        }        string = string.substring(0, nChars) + clipString;        return string;    }    /**     * Returns the FontRenderContext for the passed in FontMetrics or     * for the passed in JComponent if FontMetrics is null     */    private static FontRenderContext getFRC(JComponent c, FontMetrics fm) {        // c may be null.        if (fm instanceof FontDesignMetrics) {            return ((FontDesignMetrics)fm).getFRC();        }        if (fm == null && c != null) {            //we do it this way because we need first case to             //work as fast as possible            return getFRC(c, c.getFontMetrics(c.getFont()));        }        // PENDING: This shouldn't really happen, but if it does we        // should try and handle AA as necessary.        assert false;        return DEFAULT_FRC;    }    /**     * Draws the string at the specified location.     *     * @param c JComponent that will display the string, may be null     * @param g Graphics to draw the text to     * @param text String to display

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?