swingutilities2.java

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

JAVA
1,148
字号
            for (int counter = lsbCache.length - 1; counter >= 0; counter--) {                lsbCache[counter] = UNSET;            }        }        public int getLeftSideBearing(char aChar) {            int index = aChar - MIN_CHAR_INDEX;            assert (index >= 0 && index < (MAX_CHAR_INDEX - MIN_CHAR_INDEX));            byte lsb = lsbCache[index];            if (lsb == UNSET) {                oneChar[0] = aChar;                GlyphVector gv = font.createGlyphVector(frc, oneChar);                lsb = (byte)gv.getGlyphPixelBounds(0, frc, 0f, 0f).x;                lsbCache[index] = lsb;            }            return lsb;        }        public boolean equals(Object entry) {            if (entry == this) {                return true;            }            if (!(entry instanceof LSBCacheEntry)) {                return false;            }            LSBCacheEntry oEntry = (LSBCacheEntry)entry;            return (font.equals(oEntry.font) &&                    frc.equals(oEntry.frc));        }        public int hashCode() {            int result = 17;            if (font != null) {                result = 37 * result + font.hashCode();            }            if (frc != null) {                result = 37 * result + frc.hashCode();            }            return result;        }    }    /*     * here goes the fix for 4856343 [Problem with applet interaction     * with system selection clipboard]     *      * NOTE. In case isTrustedContext() no checking     * are to be performed     */    /**     * checks the security permissions for accessing system clipboard     *      * for untrusted context (see isTrustedContext) checks the     * permissions for the current event being handled     *     */    public static boolean canAccessSystemClipboard() {        boolean canAccess = false;        if (!GraphicsEnvironment.isHeadless()) {            SecurityManager sm = System.getSecurityManager();            if (sm == null) {                canAccess = true;            } else {                try {                    sm.checkSystemClipboardAccess();                    canAccess = true;                  } catch (SecurityException e) {                }                if (canAccess && ! isTrustedContext()) {                    canAccess = canCurrentEventAccessSystemClipboard(true);                }            }        }        return canAccess;    }    /**     * Returns true if EventQueue.getCurrentEvent() has the permissions to     * access the system clipboard     */    public static boolean canCurrentEventAccessSystemClipboard() {        return  isTrustedContext()            || canCurrentEventAccessSystemClipboard(false);    }        /**     * Returns true if the given event has permissions to access the     * system clipboard     *      * @param e AWTEvent to check     */    public static boolean canEventAccessSystemClipboard(AWTEvent e) {        return isTrustedContext()             || canEventAccessSystemClipboard(e, false);    }        /**     * returns canAccessSystemClipboard field from InputEvent     *     * @param ie InputEvent to get the field from      */    private static synchronized boolean inputEvent_canAccessSystemClipboard(InputEvent ie) {        if (inputEvent_CanAccessSystemClipboard_Field == null) {             inputEvent_CanAccessSystemClipboard_Field =                (Field)AccessController.doPrivileged(                    new java.security.PrivilegedAction() {                        public Object run() {                            Field field = null;                            try {                                field = InputEvent.class.                                    getDeclaredField("canAccessSystemClipboard");                                field.setAccessible(true);                                return field;                            } catch (SecurityException e) {                            } catch (NoSuchFieldException e) {                            }                            return null;                        }                    });        }        if (inputEvent_CanAccessSystemClipboard_Field == null) {             return false;        }        boolean ret = false;        try {            ret = inputEvent_CanAccessSystemClipboard_Field.                getBoolean(ie);        } catch(IllegalAccessException e) {        }         return ret;    }    /**     * Returns true if the given event is corrent gesture for     * accessing clipboard     *      * @param ie InputEvent to check     */    private static boolean isAccessClipboardGesture(InputEvent ie) {        boolean allowedGesture = false;        if (ie instanceof KeyEvent) { //we can validate only keyboard gestures            KeyEvent ke = (KeyEvent)ie;            int keyCode = ke.getKeyCode();            int keyModifiers = ke.getModifiers();            switch(keyCode) {            case KeyEvent.VK_C:            case KeyEvent.VK_V:            case KeyEvent.VK_X:                allowedGesture = (keyModifiers == InputEvent.CTRL_MASK);                break;            case KeyEvent.VK_INSERT:                allowedGesture = (keyModifiers == InputEvent.CTRL_MASK ||                                  keyModifiers == InputEvent.SHIFT_MASK);                break;            case KeyEvent.VK_COPY:            case KeyEvent.VK_PASTE:            case KeyEvent.VK_CUT:                allowedGesture = true;                break;            case KeyEvent.VK_DELETE:                allowedGesture = ( keyModifiers == InputEvent.SHIFT_MASK);                break;            }        }         return allowedGesture;    }    /**     * Returns true if e has the permissions to     * access the system clipboard and if it is allowed gesture (if     * checkGesture is true)     *     * @param e AWTEvent to check     * @param checkGesture boolean     */    private static boolean canEventAccessSystemClipboard(AWTEvent e,                                                         boolean checkGesture) {        if (EventQueue.isDispatchThread()) {             /*             * Checking event permissions makes sense only for event             * dispathing thread              */            if (e instanceof InputEvent                 && (! checkGesture || isAccessClipboardGesture((InputEvent)e))) {                return inputEvent_canAccessSystemClipboard((InputEvent)e);            } else {                 return false;            }        } else {            return true;        }    }    /**     * Returns true if EventQueue.getCurrentEvent() has the permissions to     * access the system clipboard and if it is allowed gesture (if     * checkGesture true)     *      * @param checkGesture boolean      */    private static boolean canCurrentEventAccessSystemClipboard(boolean                                                                checkGesture) {        AWTEvent event = EventQueue.getCurrentEvent();        return canEventAccessSystemClipboard(event, checkGesture);    }    /**     * see RFE 5012841 [Per AppContect security permissions] for the     * details     *     */     private static boolean isTrustedContext() {        return (System.getSecurityManager() == null)             || (AppContext.getAppContext().                get(UntrustedClipboardAccess) == null);    }    public static String displayPropertiesToCSS(Font font, Color fg) {        StringBuffer rule = new StringBuffer("body {");        if (font != null) {            rule.append(" font-family: ");            rule.append(font.getFamily());            rule.append(" ; ");            rule.append(" font-size: ");            rule.append(font.getSize());            rule.append("pt ;");            if (font.isBold()) {                rule.append(" font-weight: 700 ; ");            }            if (font.isItalic()) {                rule.append(" font-style: italic ; ");            }        }        if (fg != null) {            rule.append(" color: #");            if (fg.getRed() < 16) {                rule.append('0');            }            rule.append(Integer.toHexString(fg.getRed()));            if (fg.getGreen() < 16) {                rule.append('0');            }            rule.append(Integer.toHexString(fg.getGreen()));            if (fg.getBlue() < 16) {                rule.append('0');            }            rule.append(Integer.toHexString(fg.getBlue()));            rule.append(" ; ");        }        rule.append(" }");        return rule.toString();    }    /**     * Utility method that creates a <code>UIDefaults.LazyValue</code> that     * creates an <code>ImageIcon</code> <code>UIResource</code> for the     * specified image file name. The image is loaded using     * <code>getResourceAsStream</code>, starting with a call to that method     * on the base class parameter. If it cannot be found, searching will     * continue through the base class' inheritance hierarchy, up to and     * including <code>rootClass</code>.     *     * @param baseClass the first class to use in searching for the resource     * @param rootClass an ancestor of <code>baseClass</code> to finish the     *                  search at     * @param imageFile the name of the file to be found     * @return a lazy value that creates the <code>ImageIcon</code>     *         <code>UIResource</code> for the image,     *         or null if it cannot be found     */    public static Object makeIcon(final Class<?> baseClass,                                  final Class<?> rootClass,                                  final String imageFile) {        return new UIDefaults.LazyValue() {            public Object createValue(UIDefaults table) {                /* Copy resource into a byte array.  This is                 * necessary because several browsers consider                 * Class.getResource a security risk because it                 * can be used to load additional classes.                 * Class.getResourceAsStream just returns raw                 * bytes, which we can convert to an image.                 */                byte[] buffer = (byte[])                    java.security.AccessController.doPrivileged(                        new java.security.PrivilegedAction() {                    public Object run() {                        try {                            InputStream resource = null;                            Class<?> srchClass = baseClass;                            while (srchClass != null) {                                resource = srchClass.getResourceAsStream(imageFile);                                if (resource != null || srchClass == rootClass) {                                    break;                                }                                srchClass = srchClass.getSuperclass();                            }                            if (resource == null) {                                return null;                             }                            BufferedInputStream in =                                 new BufferedInputStream(resource);                            ByteArrayOutputStream out =                                 new ByteArrayOutputStream(1024);                            byte[] buffer = new byte[1024];                            int n;                            while ((n = in.read(buffer)) > 0) {                                out.write(buffer, 0, n);                            }                            in.close();                            out.flush();                            return out.toByteArray();                        } catch (IOException ioe) {                            System.err.println(ioe.toString());                        }                        return null;                    }                });                if (buffer == null) {                    return null;                }                if (buffer.length == 0) {                    System.err.println("warning: " + imageFile +                                        " is zero-length");                    return null;                }                return new IconUIResource(new ImageIcon(buffer));            }        };    }    /**     * Sets the {@code SKIP_CLICK_COUNT} client property on the component     * if it is an instance of {@code JTextComponent} with a     * {@code DefaultCaret}. This property, used for text components acting     * as editors in a table or tree, tells {@code DefaultCaret} how many     * clicks to skip before starting selection.     */    public static void setSkipClickCount(Component comp, int count) {        if (comp instanceof JTextComponent                && ((JTextComponent) comp).getCaret() instanceof DefaultCaret) {            ((JTextComponent) comp).putClientProperty(SKIP_CLICK_COUNT, count);        }    }    /**     * Return the MouseEvent's click count, possibly reduced by the value of     * the component's {@code SKIP_CLICK_COUNT} client property. Clears     * the {@code SKIP_CLICK_COUNT} property if the mouse event's click count     * is 1. In order for clearing of the property to work correctly, there     * must be a mousePressed implementation on the caller with this     * call as the first line.     */    public static int getAdjustedClickCount(JTextComponent comp, MouseEvent e) {        int cc = e.getClickCount();        if (cc == 1) {            comp.putClientProperty(SKIP_CLICK_COUNT, null);        } else {            Integer sub = (Integer) comp.getClientProperty(SKIP_CLICK_COUNT);            if (sub != null) {                return cc - sub;            }        }        return cc;    }}

⌨️ 快捷键说明

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