code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.metal; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.plaf.*; import javax.swing.*; import javax.swing.plaf.basic.*; import javax.swing.text.DefaultEditorKit; import java.awt.Color; import java.awt.event.KeyEvent; import java.lang.reflect.*; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.security.AccessController; import java.security.PrivilegedAction; import sun.awt.*; import sun.security.action.GetPropertyAction; import sun.swing.DefaultLayoutStyle; import sun.swing.SwingLazyValue; import sun.swing.SwingUtilities2; /** {@collect.stats} * The Java Look and Feel, otherwise known as Metal. * <p> * Each of the {@code ComponentUI}s provided by {@code * MetalLookAndFeel} derives its behavior from the defaults * table. Unless otherwise noted each of the {@code ComponentUI} * implementations in this package document the set of defaults they * use. Unless otherwise noted the defaults are installed at the time * {@code installUI} is invoked, and follow the recommendations * outlined in {@code LookAndFeel} for installing defaults. * <p> * {@code MetalLookAndFeel} derives it's color palette and fonts from * {@code MetalTheme}. The default theme is {@code OceanTheme}. The theme * can be changed using the {@code setCurrentTheme} method, refer to it * for details on changing the theme. Prior to 1.5 the default * theme was {@code DefaultMetalTheme}. The system property * {@code "swing.metalTheme"} can be set to {@code "steel"} to indicate * the default should be {@code DefaultMetalTheme}. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @see MetalTheme * @see DefaultMetalTheme * @see OceanTheme * * @author Steve Wilson */ public class MetalLookAndFeel extends BasicLookAndFeel { private static boolean METAL_LOOK_AND_FEEL_INITED = false; private static MetalTheme currentTheme; private static boolean isOnlyOneContext = true; private static AppContext cachedAppContext; /** {@collect.stats} * True if checked for windows yet. */ private static boolean checkedWindows; /** {@collect.stats} * True if running on Windows. */ private static boolean isWindows; /** {@collect.stats} * Set to true first time we've checked swing.useSystemFontSettings. */ private static boolean checkedSystemFontSettings; /** {@collect.stats} * True indicates we should use system fonts, unless the developer has * specified otherwise with Application.useSystemFontSettings. */ private static boolean useSystemFonts; /** {@collect.stats} * Returns true if running on Windows. */ static boolean isWindows() { if (!checkedWindows) { OSInfo.OSType osType = AccessController.doPrivileged(OSInfo.getOSTypeAction()); if (osType == OSInfo.OSType.WINDOWS) { isWindows = true; String systemFonts = AccessController.doPrivileged( new GetPropertyAction("swing.useSystemFontSettings")); useSystemFonts = (systemFonts != null && (Boolean.valueOf(systemFonts).booleanValue())); } checkedWindows = true; } return isWindows; } /** {@collect.stats} * Returns true if system fonts should be used, this is only useful * for windows. */ static boolean useSystemFonts() { if (isWindows() && useSystemFonts) { if (METAL_LOOK_AND_FEEL_INITED) { Object value = UIManager.get( "Application.useSystemFontSettings"); return (value == null || Boolean.TRUE.equals(value)); } // If an instanceof MetalLookAndFeel hasn't been inited yet, we // don't want to trigger loading of a UI by asking the UIManager // for a property, assume the user wants system fonts. This will // be properly adjusted when install is invoked on the // MetalTheme return true; } return false; } /** {@collect.stats} * Returns true if the high contrast theme should be used as the default * theme. */ private static boolean useHighContrastTheme() { if (isWindows() && useSystemFonts()) { Boolean highContrast = (Boolean)Toolkit.getDefaultToolkit(). getDesktopProperty("win.highContrast.on"); return (highContrast == null) ? false : highContrast. booleanValue(); } return false; } /** {@collect.stats} * Returns true if we're using the Ocean Theme. */ static boolean usingOcean() { return (getCurrentTheme() instanceof OceanTheme); } /** {@collect.stats} * Returns the name of this look and feel. This returns * {@code "Metal"}. * * @return the name of this look and feel */ public String getName() { return "Metal"; } /** {@collect.stats} * Returns an identifier for this look and feel. This returns * {@code "Metal"}. * * @return the identifier of this look and feel */ public String getID() { return "Metal"; } /** {@collect.stats} * Returns a short description of this look and feel. This returns * {@code "The Java(tm) Look and Feel"}. * @return a short description for the look and feel */ public String getDescription() { return "The Java(tm) Look and Feel"; } /** {@collect.stats} * Returns {@code false}; {@code MetalLookAndFeel} is not a native * look and feel. * * @return {@code false} */ public boolean isNativeLookAndFeel() { return false; } /** {@collect.stats} * Returns {@code true}; {@code MetalLookAndFeel} can be run on * any platform. * * @return {@code true} */ public boolean isSupportedLookAndFeel() { return true; } /** {@collect.stats} * Returns {@code true}; metal can provide {@code Window} * decorations. * * @return {@code true} * * @see JDialog#setDefaultLookAndFeelDecorated * @see JFrame#setDefaultLookAndFeelDecorated * @see JRootPane#setWindowDecorationStyle * @since 1.4 */ public boolean getSupportsWindowDecorations() { return true; } /** {@collect.stats} * Populates {@code table} with mappings from {@code uiClassID} to * the fully qualified name of the ui class. {@code * MetalLookAndFeel} registers an entry for each of the classes in * the package {@code javax.swing.plaf.metal} that are named * MetalXXXUI. The string {@code XXX} is one of Swing's uiClassIDs. For * the {@code uiClassIDs} that do not have a class in metal, the * corresponding class in {@code javax.swing.plaf.basic} is * used. For example, metal does not have a class named {@code * "MetalColorChooserUI"}, as such, {@code * javax.swing.plaf.basic.BasicColorChooserUI} is used. * * @param table the {@code UIDefaults} instance the entries are * added to * @throws NullPointerException if {@code table} is {@code null} * * @see javax.swing.plaf.basic.BasicLookAndFeel#initClassDefaults */ protected void initClassDefaults(UIDefaults table) { super.initClassDefaults(table); final String metalPackageName = "javax.swing.plaf.metal."; Object[] uiDefaults = { "ButtonUI", metalPackageName + "MetalButtonUI", "CheckBoxUI", metalPackageName + "MetalCheckBoxUI", "ComboBoxUI", metalPackageName + "MetalComboBoxUI", "DesktopIconUI", metalPackageName + "MetalDesktopIconUI", "FileChooserUI", metalPackageName + "MetalFileChooserUI", "InternalFrameUI", metalPackageName + "MetalInternalFrameUI", "LabelUI", metalPackageName + "MetalLabelUI", "PopupMenuSeparatorUI", metalPackageName + "MetalPopupMenuSeparatorUI", "ProgressBarUI", metalPackageName + "MetalProgressBarUI", "RadioButtonUI", metalPackageName + "MetalRadioButtonUI", "ScrollBarUI", metalPackageName + "MetalScrollBarUI", "ScrollPaneUI", metalPackageName + "MetalScrollPaneUI", "SeparatorUI", metalPackageName + "MetalSeparatorUI", "SliderUI", metalPackageName + "MetalSliderUI", "SplitPaneUI", metalPackageName + "MetalSplitPaneUI", "TabbedPaneUI", metalPackageName + "MetalTabbedPaneUI", "TextFieldUI", metalPackageName + "MetalTextFieldUI", "ToggleButtonUI", metalPackageName + "MetalToggleButtonUI", "ToolBarUI", metalPackageName + "MetalToolBarUI", "ToolTipUI", metalPackageName + "MetalToolTipUI", "TreeUI", metalPackageName + "MetalTreeUI", "RootPaneUI", metalPackageName + "MetalRootPaneUI", }; table.putDefaults(uiDefaults); } /** {@collect.stats} * Populates {@code table} with system colors. The following values are * added to {@code table}: * <table border="1" cellpadding="1" cellspacing="0" * summary="Metal's system color mapping" * valign="top" > * <tr valign="top" align="left"> * <th bgcolor="#CCCCFF" align="left">Key * <th bgcolor="#CCCCFF" align="left">Value * <tr valign="top" align="left"> * <td>"desktop" * <td>{@code theme.getDesktopColor()} * <tr valign="top" align="left"> * <td>"activeCaption" * <td>{@code theme.getWindowTitleBackground()} * <tr valign="top" align="left"> * <td>"activeCaptionText" * <td>{@code theme.getWindowTitleForeground()} * <tr valign="top" align="left"> * <td>"activeCaptionBorder" * <td>{@code theme.getPrimaryControlShadow()} * <tr valign="top" align="left"> * <td>"inactiveCaption" * <td>{@code theme.getWindowTitleInactiveBackground()} * <tr valign="top" align="left"> * <td>"inactiveCaptionText" * <td>{@code theme.getWindowTitleInactiveForeground()} * <tr valign="top" align="left"> * <td>"inactiveCaptionBorder" * <td>{@code theme.getControlShadow()} * <tr valign="top" align="left"> * <td>"window" * <td>{@code theme.getWindowBackground()} * <tr valign="top" align="left"> * <td>"windowBorder" * <td>{@code theme.getControl()} * <tr valign="top" align="left"> * <td>"windowText" * <td>{@code theme.getUserTextColor()} * <tr valign="top" align="left"> * <td>"menu" * <td>{@code theme.getMenuBackground()} * <tr valign="top" align="left"> * <td>"menuText" * <td>{@code theme.getMenuForeground()} * <tr valign="top" align="left"> * <td>"text" * <td>{@code theme.getWindowBackground()} * <tr valign="top" align="left"> * <td>"textText" * <td>{@code theme.getUserTextColor()} * <tr valign="top" align="left"> * <td>"textHighlight" * <td>{@code theme.getTextHighlightColor()} * <tr valign="top" align="left"> * <td>"textHighlightText" * <td>{@code theme.getHighlightedTextColor()} * <tr valign="top" align="left"> * <td>"textInactiveText" * <td>{@code theme.getInactiveSystemTextColor()} * <tr valign="top" align="left"> * <td>"control" * <td>{@code theme.getControl()} * <tr valign="top" align="left"> * <td>"controlText" * <td>{@code theme.getControlTextColor()} * <tr valign="top" align="left"> * <td>"controlHighlight" * <td>{@code theme.getControlHighlight()} * <tr valign="top" align="left"> * <td>"controlLtHighlight" * <td>{@code theme.getControlHighlight()} * <tr valign="top" align="left"> * <td>"controlShadow" * <td>{@code theme.getControlShadow()} * <tr valign="top" align="left"> * <td>"controlDkShadow" * <td>{@code theme.getControlDarkShadow()} * <tr valign="top" align="left"> * <td>"scrollbar" * <td>{@code theme.getControl()} * <tr valign="top" align="left"> * <td>"info" * <td>{@code theme.getPrimaryControl()} * <tr valign="top" align="left"> * <td>"infoText" * <td>{@code theme.getPrimaryControlInfo()} * </table> * The value {@code theme} corresponds to the current {@code MetalTheme}. * * @param table the {@code UIDefaults} object the values are added to * @throws NullPointerException if {@code table} is {@code null} */ protected void initSystemColorDefaults(UIDefaults table) { MetalTheme theme = getCurrentTheme(); Color control = theme.getControl(); Object[] systemColors = { "desktop", theme.getDesktopColor(), /* Color of the desktop background */ "activeCaption", theme.getWindowTitleBackground(), /* Color for captions (title bars) when they are active. */ "activeCaptionText", theme.getWindowTitleForeground(), /* Text color for text in captions (title bars). */ "activeCaptionBorder", theme.getPrimaryControlShadow(), /* Border color for caption (title bar) window borders. */ "inactiveCaption", theme.getWindowTitleInactiveBackground(), /* Color for captions (title bars) when not active. */ "inactiveCaptionText", theme.getWindowTitleInactiveForeground(), /* Text color for text in inactive captions (title bars). */ "inactiveCaptionBorder", theme.getControlShadow(), /* Border color for inactive caption (title bar) window borders. */ "window", theme.getWindowBackground(), /* Default color for the interior of windows */ "windowBorder", control, /* ??? */ "windowText", theme.getUserTextColor(), /* ??? */ "menu", theme.getMenuBackground(), /* Background color for menus */ "menuText", theme.getMenuForeground(), /* Text color for menus */ "text", theme.getWindowBackground(), /* Text background color */ "textText", theme.getUserTextColor(), /* Text foreground color */ "textHighlight", theme.getTextHighlightColor(), /* Text background color when selected */ "textHighlightText", theme.getHighlightedTextColor(), /* Text color when selected */ "textInactiveText", theme.getInactiveSystemTextColor(), /* Text color when disabled */ "control", control, /* Default color for controls (buttons, sliders, etc) */ "controlText", theme.getControlTextColor(), /* Default color for text in controls */ "controlHighlight", theme.getControlHighlight(), /* Specular highlight (opposite of the shadow) */ "controlLtHighlight", theme.getControlHighlight(), /* Highlight color for controls */ "controlShadow", theme.getControlShadow(), /* Shadow color for controls */ "controlDkShadow", theme.getControlDarkShadow(), /* Dark shadow color for controls */ "scrollbar", control, /* Scrollbar background (usually the "track") */ "info", theme.getPrimaryControl(), /* ToolTip Background */ "infoText", theme.getPrimaryControlInfo() /* ToolTip Text */ }; table.putDefaults(systemColors); } /** {@collect.stats} * Initialize the defaults table with the name of the ResourceBundle * used for getting localized defaults. */ private void initResourceBundle(UIDefaults table) { table.addResourceBundle( "com.sun.swing.internal.plaf.metal.resources.metal" ); } /** {@collect.stats} * Populates {@code table} with the defaults for metal. * * @param table the {@code UIDefaults} to add the values to * @throws NullPointerException if {@code table} is {@code null} */ protected void initComponentDefaults(UIDefaults table) { super.initComponentDefaults( table ); initResourceBundle(table); Color acceleratorForeground = getAcceleratorForeground(); Color acceleratorSelectedForeground = getAcceleratorSelectedForeground(); Color control = getControl(); Color controlHighlight = getControlHighlight(); Color controlShadow = getControlShadow(); Color controlDarkShadow = getControlDarkShadow(); Color controlTextColor = getControlTextColor(); Color focusColor = getFocusColor(); Color inactiveControlTextColor = getInactiveControlTextColor(); Color menuBackground = getMenuBackground(); Color menuSelectedBackground = getMenuSelectedBackground(); Color menuDisabledForeground = getMenuDisabledForeground(); Color menuSelectedForeground = getMenuSelectedForeground(); Color primaryControl = getPrimaryControl(); Color primaryControlDarkShadow = getPrimaryControlDarkShadow(); Color primaryControlShadow = getPrimaryControlShadow(); Color systemTextColor = getSystemTextColor(); Insets zeroInsets = new InsetsUIResource(0, 0, 0, 0); Integer zero = new Integer(0); Object textFieldBorder = new SwingLazyValue("javax.swing.plaf.metal.MetalBorders", "getTextFieldBorder"); Object dialogBorder = new MetalLazyValue( "javax.swing.plaf.metal.MetalBorders$DialogBorder"); Object questionDialogBorder = new MetalLazyValue( "javax.swing.plaf.metal.MetalBorders$QuestionDialogBorder"); Object fieldInputMap = new UIDefaults.LazyInputMap(new Object[] { "ctrl C", DefaultEditorKit.copyAction, "ctrl V", DefaultEditorKit.pasteAction, "ctrl X", DefaultEditorKit.cutAction, "COPY", DefaultEditorKit.copyAction, "PASTE", DefaultEditorKit.pasteAction, "CUT", DefaultEditorKit.cutAction, "control INSERT", DefaultEditorKit.copyAction, "shift INSERT", DefaultEditorKit.pasteAction, "shift DELETE", DefaultEditorKit.cutAction, "shift LEFT", DefaultEditorKit.selectionBackwardAction, "shift KP_LEFT", DefaultEditorKit.selectionBackwardAction, "shift RIGHT", DefaultEditorKit.selectionForwardAction, "shift KP_RIGHT", DefaultEditorKit.selectionForwardAction, "ctrl LEFT", DefaultEditorKit.previousWordAction, "ctrl KP_LEFT", DefaultEditorKit.previousWordAction, "ctrl RIGHT", DefaultEditorKit.nextWordAction, "ctrl KP_RIGHT", DefaultEditorKit.nextWordAction, "ctrl shift LEFT", DefaultEditorKit.selectionPreviousWordAction, "ctrl shift KP_LEFT", DefaultEditorKit.selectionPreviousWordAction, "ctrl shift RIGHT", DefaultEditorKit.selectionNextWordAction, "ctrl shift KP_RIGHT", DefaultEditorKit.selectionNextWordAction, "ctrl A", DefaultEditorKit.selectAllAction, "HOME", DefaultEditorKit.beginLineAction, "END", DefaultEditorKit.endLineAction, "shift HOME", DefaultEditorKit.selectionBeginLineAction, "shift END", DefaultEditorKit.selectionEndLineAction, "BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "ctrl H", DefaultEditorKit.deletePrevCharAction, "DELETE", DefaultEditorKit.deleteNextCharAction, "ctrl DELETE", DefaultEditorKit.deleteNextWordAction, "ctrl BACK_SPACE", DefaultEditorKit.deletePrevWordAction, "RIGHT", DefaultEditorKit.forwardAction, "LEFT", DefaultEditorKit.backwardAction, "KP_RIGHT", DefaultEditorKit.forwardAction, "KP_LEFT", DefaultEditorKit.backwardAction, "ENTER", JTextField.notifyAction, "ctrl BACK_SLASH", "unselect"/*DefaultEditorKit.unselectAction*/, "control shift O", "toggle-componentOrientation"/*DefaultEditorKit.toggleComponentOrientation*/ }); Object passwordInputMap = new UIDefaults.LazyInputMap(new Object[] { "ctrl C", DefaultEditorKit.copyAction, "ctrl V", DefaultEditorKit.pasteAction, "ctrl X", DefaultEditorKit.cutAction, "COPY", DefaultEditorKit.copyAction, "PASTE", DefaultEditorKit.pasteAction, "CUT", DefaultEditorKit.cutAction, "control INSERT", DefaultEditorKit.copyAction, "shift INSERT", DefaultEditorKit.pasteAction, "shift DELETE", DefaultEditorKit.cutAction, "shift LEFT", DefaultEditorKit.selectionBackwardAction, "shift KP_LEFT", DefaultEditorKit.selectionBackwardAction, "shift RIGHT", DefaultEditorKit.selectionForwardAction, "shift KP_RIGHT", DefaultEditorKit.selectionForwardAction, "ctrl LEFT", DefaultEditorKit.beginLineAction, "ctrl KP_LEFT", DefaultEditorKit.beginLineAction, "ctrl RIGHT", DefaultEditorKit.endLineAction, "ctrl KP_RIGHT", DefaultEditorKit.endLineAction, "ctrl shift LEFT", DefaultEditorKit.selectionBeginLineAction, "ctrl shift KP_LEFT", DefaultEditorKit.selectionBeginLineAction, "ctrl shift RIGHT", DefaultEditorKit.selectionEndLineAction, "ctrl shift KP_RIGHT", DefaultEditorKit.selectionEndLineAction, "ctrl A", DefaultEditorKit.selectAllAction, "HOME", DefaultEditorKit.beginLineAction, "END", DefaultEditorKit.endLineAction, "shift HOME", DefaultEditorKit.selectionBeginLineAction, "shift END", DefaultEditorKit.selectionEndLineAction, "BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "ctrl H", DefaultEditorKit.deletePrevCharAction, "DELETE", DefaultEditorKit.deleteNextCharAction, "RIGHT", DefaultEditorKit.forwardAction, "LEFT", DefaultEditorKit.backwardAction, "KP_RIGHT", DefaultEditorKit.forwardAction, "KP_LEFT", DefaultEditorKit.backwardAction, "ENTER", JTextField.notifyAction, "ctrl BACK_SLASH", "unselect"/*DefaultEditorKit.unselectAction*/, "control shift O", "toggle-componentOrientation"/*DefaultEditorKit.toggleComponentOrientation*/ }); Object multilineInputMap = new UIDefaults.LazyInputMap(new Object[] { "ctrl C", DefaultEditorKit.copyAction, "ctrl V", DefaultEditorKit.pasteAction, "ctrl X", DefaultEditorKit.cutAction, "COPY", DefaultEditorKit.copyAction, "PASTE", DefaultEditorKit.pasteAction, "CUT", DefaultEditorKit.cutAction, "control INSERT", DefaultEditorKit.copyAction, "shift INSERT", DefaultEditorKit.pasteAction, "shift DELETE", DefaultEditorKit.cutAction, "shift LEFT", DefaultEditorKit.selectionBackwardAction, "shift KP_LEFT", DefaultEditorKit.selectionBackwardAction, "shift RIGHT", DefaultEditorKit.selectionForwardAction, "shift KP_RIGHT", DefaultEditorKit.selectionForwardAction, "ctrl LEFT", DefaultEditorKit.previousWordAction, "ctrl KP_LEFT", DefaultEditorKit.previousWordAction, "ctrl RIGHT", DefaultEditorKit.nextWordAction, "ctrl KP_RIGHT", DefaultEditorKit.nextWordAction, "ctrl shift LEFT", DefaultEditorKit.selectionPreviousWordAction, "ctrl shift KP_LEFT", DefaultEditorKit.selectionPreviousWordAction, "ctrl shift RIGHT", DefaultEditorKit.selectionNextWordAction, "ctrl shift KP_RIGHT", DefaultEditorKit.selectionNextWordAction, "ctrl A", DefaultEditorKit.selectAllAction, "HOME", DefaultEditorKit.beginLineAction, "END", DefaultEditorKit.endLineAction, "shift HOME", DefaultEditorKit.selectionBeginLineAction, "shift END", DefaultEditorKit.selectionEndLineAction, "UP", DefaultEditorKit.upAction, "KP_UP", DefaultEditorKit.upAction, "DOWN", DefaultEditorKit.downAction, "KP_DOWN", DefaultEditorKit.downAction, "PAGE_UP", DefaultEditorKit.pageUpAction, "PAGE_DOWN", DefaultEditorKit.pageDownAction, "shift PAGE_UP", "selection-page-up", "shift PAGE_DOWN", "selection-page-down", "ctrl shift PAGE_UP", "selection-page-left", "ctrl shift PAGE_DOWN", "selection-page-right", "shift UP", DefaultEditorKit.selectionUpAction, "shift KP_UP", DefaultEditorKit.selectionUpAction, "shift DOWN", DefaultEditorKit.selectionDownAction, "shift KP_DOWN", DefaultEditorKit.selectionDownAction, "ENTER", DefaultEditorKit.insertBreakAction, "BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "ctrl H", DefaultEditorKit.deletePrevCharAction, "DELETE", DefaultEditorKit.deleteNextCharAction, "ctrl DELETE", DefaultEditorKit.deleteNextWordAction, "ctrl BACK_SPACE", DefaultEditorKit.deletePrevWordAction, "RIGHT", DefaultEditorKit.forwardAction, "LEFT", DefaultEditorKit.backwardAction, "KP_RIGHT", DefaultEditorKit.forwardAction, "KP_LEFT", DefaultEditorKit.backwardAction, "TAB", DefaultEditorKit.insertTabAction, "ctrl BACK_SLASH", "unselect"/*DefaultEditorKit.unselectAction*/, "ctrl HOME", DefaultEditorKit.beginAction, "ctrl END", DefaultEditorKit.endAction, "ctrl shift HOME", DefaultEditorKit.selectionBeginAction, "ctrl shift END", DefaultEditorKit.selectionEndAction, "ctrl T", "next-link-action", "ctrl shift T", "previous-link-action", "ctrl SPACE", "activate-link-action", "control shift O", "toggle-componentOrientation"/*DefaultEditorKit.toggleComponentOrientation*/ }); Object scrollPaneBorder = new SwingLazyValue("javax.swing.plaf.metal.MetalBorders$ScrollPaneBorder"); Object buttonBorder = new SwingLazyValue("javax.swing.plaf.metal.MetalBorders", "getButtonBorder"); Object toggleButtonBorder = new SwingLazyValue("javax.swing.plaf.metal.MetalBorders", "getToggleButtonBorder"); Object titledBorderBorder = new SwingLazyValue( "javax.swing.plaf.BorderUIResource$LineBorderUIResource", new Object[] {controlShadow}); Object desktopIconBorder = new SwingLazyValue( "javax.swing.plaf.metal.MetalBorders", "getDesktopIconBorder"); Object menuBarBorder = new SwingLazyValue( "javax.swing.plaf.metal.MetalBorders$MenuBarBorder"); Object popupMenuBorder = new SwingLazyValue( "javax.swing.plaf.metal.MetalBorders$PopupMenuBorder"); Object menuItemBorder = new SwingLazyValue( "javax.swing.plaf.metal.MetalBorders$MenuItemBorder"); Object menuItemAcceleratorDelimiter = "-"; Object toolBarBorder = new SwingLazyValue("javax.swing.plaf.metal.MetalBorders$ToolBarBorder"); Object progressBarBorder = new SwingLazyValue( "javax.swing.plaf.BorderUIResource$LineBorderUIResource", new Object[] {controlDarkShadow, new Integer(1)}); Object toolTipBorder = new SwingLazyValue( "javax.swing.plaf.BorderUIResource$LineBorderUIResource", new Object[] {primaryControlDarkShadow}); Object toolTipBorderInactive = new SwingLazyValue( "javax.swing.plaf.BorderUIResource$LineBorderUIResource", new Object[] {controlDarkShadow}); Object focusCellHighlightBorder = new SwingLazyValue( "javax.swing.plaf.BorderUIResource$LineBorderUIResource", new Object[] {focusColor}); Object tabbedPaneTabAreaInsets = new InsetsUIResource(4, 2, 0, 6); Object tabbedPaneTabInsets = new InsetsUIResource(0, 9, 1, 9); final Object[] internalFrameIconArgs = new Object[1]; internalFrameIconArgs[0] = new Integer(16); Object[] defaultCueList = new Object[] { "OptionPane.errorSound", "OptionPane.informationSound", "OptionPane.questionSound", "OptionPane.warningSound" }; MetalTheme theme = getCurrentTheme(); Object menuTextValue = new FontActiveValue(theme, MetalTheme.MENU_TEXT_FONT); Object controlTextValue = new FontActiveValue(theme, MetalTheme.CONTROL_TEXT_FONT); Object userTextValue = new FontActiveValue(theme, MetalTheme.USER_TEXT_FONT); Object windowTitleValue = new FontActiveValue(theme, MetalTheme.WINDOW_TITLE_FONT); Object subTextValue = new FontActiveValue(theme, MetalTheme.SUB_TEXT_FONT); Object systemTextValue = new FontActiveValue(theme, MetalTheme.SYSTEM_TEXT_FONT); // // DEFAULTS TABLE // Object[] defaults = { // *** Auditory Feedback "AuditoryCues.defaultCueList", defaultCueList, // this key defines which of the various cues to render // This is disabled until sound bugs can be resolved. "AuditoryCues.playList", null, // defaultCueList, // Text (Note: many are inherited) "TextField.border", textFieldBorder, "TextField.font", userTextValue, "PasswordField.border", textFieldBorder, // passwordField.font should actually map to // win.ansiFixed.font.height on windows. "PasswordField.font", userTextValue, "PasswordField.echoChar", (char)0x2022, // TextArea.font should actually map to win.ansiFixed.font.height // on windows. "TextArea.font", userTextValue, "TextPane.background", table.get("window"), "TextPane.font", userTextValue, "EditorPane.background", table.get("window"), "EditorPane.font", userTextValue, "TextField.focusInputMap", fieldInputMap, "PasswordField.focusInputMap", passwordInputMap, "TextArea.focusInputMap", multilineInputMap, "TextPane.focusInputMap", multilineInputMap, "EditorPane.focusInputMap", multilineInputMap, // FormattedTextFields "FormattedTextField.border", textFieldBorder, "FormattedTextField.font", userTextValue, "FormattedTextField.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl C", DefaultEditorKit.copyAction, "ctrl V", DefaultEditorKit.pasteAction, "ctrl X", DefaultEditorKit.cutAction, "COPY", DefaultEditorKit.copyAction, "PASTE", DefaultEditorKit.pasteAction, "CUT", DefaultEditorKit.cutAction, "control INSERT", DefaultEditorKit.copyAction, "shift INSERT", DefaultEditorKit.pasteAction, "shift DELETE", DefaultEditorKit.cutAction, "shift LEFT", DefaultEditorKit.selectionBackwardAction, "shift KP_LEFT", DefaultEditorKit.selectionBackwardAction, "shift RIGHT", DefaultEditorKit.selectionForwardAction, "shift KP_RIGHT", DefaultEditorKit.selectionForwardAction, "ctrl LEFT", DefaultEditorKit.previousWordAction, "ctrl KP_LEFT", DefaultEditorKit.previousWordAction, "ctrl RIGHT", DefaultEditorKit.nextWordAction, "ctrl KP_RIGHT", DefaultEditorKit.nextWordAction, "ctrl shift LEFT", DefaultEditorKit.selectionPreviousWordAction, "ctrl shift KP_LEFT", DefaultEditorKit.selectionPreviousWordAction, "ctrl shift RIGHT", DefaultEditorKit.selectionNextWordAction, "ctrl shift KP_RIGHT", DefaultEditorKit.selectionNextWordAction, "ctrl A", DefaultEditorKit.selectAllAction, "HOME", DefaultEditorKit.beginLineAction, "END", DefaultEditorKit.endLineAction, "shift HOME", DefaultEditorKit.selectionBeginLineAction, "shift END", DefaultEditorKit.selectionEndLineAction, "BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "ctrl H", DefaultEditorKit.deletePrevCharAction, "DELETE", DefaultEditorKit.deleteNextCharAction, "ctrl DELETE", DefaultEditorKit.deleteNextWordAction, "ctrl BACK_SPACE", DefaultEditorKit.deletePrevWordAction, "RIGHT", DefaultEditorKit.forwardAction, "LEFT", DefaultEditorKit.backwardAction, "KP_RIGHT", DefaultEditorKit.forwardAction, "KP_LEFT", DefaultEditorKit.backwardAction, "ENTER", JTextField.notifyAction, "ctrl BACK_SLASH", "unselect", "control shift O", "toggle-componentOrientation", "ESCAPE", "reset-field-edit", "UP", "increment", "KP_UP", "increment", "DOWN", "decrement", "KP_DOWN", "decrement", }), // Buttons "Button.defaultButtonFollowsFocus", Boolean.FALSE, "Button.disabledText", inactiveControlTextColor, "Button.select", controlShadow, "Button.border", buttonBorder, "Button.font", controlTextValue, "Button.focus", focusColor, "Button.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "SPACE", "pressed", "released SPACE", "released" }), "CheckBox.disabledText", inactiveControlTextColor, "Checkbox.select", controlShadow, "CheckBox.font", controlTextValue, "CheckBox.focus", focusColor, "CheckBox.icon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getCheckBoxIcon"), "CheckBox.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "SPACE", "pressed", "released SPACE", "released" }), // margin is 2 all the way around, BasicBorders.RadioButtonBorder // (checkbox uses RadioButtonBorder) is 2 all the way around too. "CheckBox.totalInsets", new Insets(4, 4, 4, 4), "RadioButton.disabledText", inactiveControlTextColor, "RadioButton.select", controlShadow, "RadioButton.icon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getRadioButtonIcon"), "RadioButton.font", controlTextValue, "RadioButton.focus", focusColor, "RadioButton.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "SPACE", "pressed", "released SPACE", "released" }), // margin is 2 all the way around, BasicBorders.RadioButtonBorder // is 2 all the way around too. "RadioButton.totalInsets", new Insets(4, 4, 4, 4), "ToggleButton.select", controlShadow, "ToggleButton.disabledText", inactiveControlTextColor, "ToggleButton.focus", focusColor, "ToggleButton.border", toggleButtonBorder, "ToggleButton.font", controlTextValue, "ToggleButton.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "SPACE", "pressed", "released SPACE", "released" }), // File View "FileView.directoryIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getTreeFolderIcon"), "FileView.fileIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getTreeLeafIcon"), "FileView.computerIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getTreeComputerIcon"), "FileView.hardDriveIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getTreeHardDriveIcon"), "FileView.floppyDriveIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getTreeFloppyDriveIcon"), // File Chooser "FileChooser.detailsViewIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getFileChooserDetailViewIcon"), "FileChooser.homeFolderIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getFileChooserHomeFolderIcon"), "FileChooser.listViewIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getFileChooserListViewIcon"), "FileChooser.newFolderIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getFileChooserNewFolderIcon"), "FileChooser.upFolderIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getFileChooserUpFolderIcon"), "FileChooser.lookInLabelMnemonic", new Integer(KeyEvent.VK_I), "FileChooser.fileNameLabelMnemonic", new Integer(KeyEvent.VK_N), "FileChooser.filesOfTypeLabelMnemonic", new Integer(KeyEvent.VK_T), "FileChooser.usesSingleFilePane", Boolean.TRUE, "FileChooser.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ESCAPE", "cancelSelection", "F2", "editFileName", "F5", "refresh", "BACK_SPACE", "Go Up", "ENTER", "approveSelection", "ctrl ENTER", "approveSelection" }), // ToolTip "ToolTip.font", systemTextValue, "ToolTip.border", toolTipBorder, "ToolTip.borderInactive", toolTipBorderInactive, "ToolTip.backgroundInactive", control, "ToolTip.foregroundInactive", controlDarkShadow, "ToolTip.hideAccelerator", Boolean.FALSE, // ToolTipManager "ToolTipManager.enableToolTipMode", "activeApplication", // Slider Defaults "Slider.font", controlTextValue, "Slider.border", null, "Slider.foreground", primaryControlShadow, "Slider.focus", focusColor, "Slider.focusInsets", zeroInsets, "Slider.trackWidth", new Integer( 7 ), "Slider.majorTickLength", new Integer( 6 ), "Slider.horizontalThumbIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getHorizontalSliderThumbIcon"), "Slider.verticalThumbIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getVerticalSliderThumbIcon"), "Slider.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "positiveUnitIncrement", "KP_RIGHT", "positiveUnitIncrement", "DOWN", "negativeUnitIncrement", "KP_DOWN", "negativeUnitIncrement", "PAGE_DOWN", "negativeBlockIncrement", "ctrl PAGE_DOWN", "negativeBlockIncrement", "LEFT", "negativeUnitIncrement", "KP_LEFT", "negativeUnitIncrement", "UP", "positiveUnitIncrement", "KP_UP", "positiveUnitIncrement", "PAGE_UP", "positiveBlockIncrement", "ctrl PAGE_UP", "positiveBlockIncrement", "HOME", "minScroll", "END", "maxScroll" }), // Progress Bar "ProgressBar.font", controlTextValue, "ProgressBar.foreground", primaryControlShadow, "ProgressBar.selectionBackground", primaryControlDarkShadow, "ProgressBar.border", progressBarBorder, "ProgressBar.cellSpacing", zero, "ProgressBar.cellLength", new Integer(1), // Combo Box "ComboBox.background", control, "ComboBox.foreground", controlTextColor, "ComboBox.selectionBackground", primaryControlShadow, "ComboBox.selectionForeground", controlTextColor, "ComboBox.font", controlTextValue, "ComboBox.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ESCAPE", "hidePopup", "PAGE_UP", "pageUpPassThrough", "PAGE_DOWN", "pageDownPassThrough", "HOME", "homePassThrough", "END", "endPassThrough", "DOWN", "selectNext", "KP_DOWN", "selectNext", "alt DOWN", "togglePopup", "alt KP_DOWN", "togglePopup", "alt UP", "togglePopup", "alt KP_UP", "togglePopup", "SPACE", "spacePopup", "ENTER", "enterPressed", "UP", "selectPrevious", "KP_UP", "selectPrevious" }), // Internal Frame Defaults "InternalFrame.icon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getInternalFrameDefaultMenuIcon"), "InternalFrame.border", new SwingLazyValue("javax.swing.plaf.metal.MetalBorders$InternalFrameBorder"), "InternalFrame.optionDialogBorder", new SwingLazyValue("javax.swing.plaf.metal.MetalBorders$OptionDialogBorder"), "InternalFrame.paletteBorder", new SwingLazyValue("javax.swing.plaf.metal.MetalBorders$PaletteBorder"), "InternalFrame.paletteTitleHeight", new Integer(11), "InternalFrame.paletteCloseIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory$PaletteCloseIcon"), "InternalFrame.closeIcon", new SwingLazyValue( "javax.swing.plaf.metal.MetalIconFactory", "getInternalFrameCloseIcon", internalFrameIconArgs), "InternalFrame.maximizeIcon", new SwingLazyValue( "javax.swing.plaf.metal.MetalIconFactory", "getInternalFrameMaximizeIcon", internalFrameIconArgs), "InternalFrame.iconifyIcon", new SwingLazyValue( "javax.swing.plaf.metal.MetalIconFactory", "getInternalFrameMinimizeIcon", internalFrameIconArgs), "InternalFrame.minimizeIcon", new SwingLazyValue( "javax.swing.plaf.metal.MetalIconFactory", "getInternalFrameAltMaximizeIcon", internalFrameIconArgs), "InternalFrame.titleFont", windowTitleValue, "InternalFrame.windowBindings", null, // Internal Frame Auditory Cue Mappings "InternalFrame.closeSound", "sounds/FrameClose.wav", "InternalFrame.maximizeSound", "sounds/FrameMaximize.wav", "InternalFrame.minimizeSound", "sounds/FrameMinimize.wav", "InternalFrame.restoreDownSound", "sounds/FrameRestoreDown.wav", "InternalFrame.restoreUpSound", "sounds/FrameRestoreUp.wav", // Desktop Icon "DesktopIcon.border", desktopIconBorder, "DesktopIcon.font", controlTextValue, "DesktopIcon.foreground", controlTextColor, "DesktopIcon.background", control, "DesktopIcon.width", new Integer(160), "Desktop.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl F5", "restore", "ctrl F4", "close", "ctrl F7", "move", "ctrl F8", "resize", "RIGHT", "right", "KP_RIGHT", "right", "shift RIGHT", "shrinkRight", "shift KP_RIGHT", "shrinkRight", "LEFT", "left", "KP_LEFT", "left", "shift LEFT", "shrinkLeft", "shift KP_LEFT", "shrinkLeft", "UP", "up", "KP_UP", "up", "shift UP", "shrinkUp", "shift KP_UP", "shrinkUp", "DOWN", "down", "KP_DOWN", "down", "shift DOWN", "shrinkDown", "shift KP_DOWN", "shrinkDown", "ESCAPE", "escape", "ctrl F9", "minimize", "ctrl F10", "maximize", "ctrl F6", "selectNextFrame", "ctrl TAB", "selectNextFrame", "ctrl alt F6", "selectNextFrame", "shift ctrl alt F6", "selectPreviousFrame", "ctrl F12", "navigateNext", "shift ctrl F12", "navigatePrevious" }), // Titled Border "TitledBorder.font", controlTextValue, "TitledBorder.titleColor", systemTextColor, "TitledBorder.border", titledBorderBorder, // Label "Label.font", controlTextValue, "Label.foreground", systemTextColor, "Label.disabledForeground", getInactiveSystemTextColor(), // List "List.font", controlTextValue, "List.focusCellHighlightBorder", focusCellHighlightBorder, "List.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl C", "copy", "ctrl V", "paste", "ctrl X", "cut", "COPY", "copy", "PASTE", "paste", "CUT", "cut", "control INSERT", "copy", "shift INSERT", "paste", "shift DELETE", "cut", "UP", "selectPreviousRow", "KP_UP", "selectPreviousRow", "shift UP", "selectPreviousRowExtendSelection", "shift KP_UP", "selectPreviousRowExtendSelection", "ctrl shift UP", "selectPreviousRowExtendSelection", "ctrl shift KP_UP", "selectPreviousRowExtendSelection", "ctrl UP", "selectPreviousRowChangeLead", "ctrl KP_UP", "selectPreviousRowChangeLead", "DOWN", "selectNextRow", "KP_DOWN", "selectNextRow", "shift DOWN", "selectNextRowExtendSelection", "shift KP_DOWN", "selectNextRowExtendSelection", "ctrl shift DOWN", "selectNextRowExtendSelection", "ctrl shift KP_DOWN", "selectNextRowExtendSelection", "ctrl DOWN", "selectNextRowChangeLead", "ctrl KP_DOWN", "selectNextRowChangeLead", "LEFT", "selectPreviousColumn", "KP_LEFT", "selectPreviousColumn", "shift LEFT", "selectPreviousColumnExtendSelection", "shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl shift LEFT", "selectPreviousColumnExtendSelection", "ctrl shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl LEFT", "selectPreviousColumnChangeLead", "ctrl KP_LEFT", "selectPreviousColumnChangeLead", "RIGHT", "selectNextColumn", "KP_RIGHT", "selectNextColumn", "shift RIGHT", "selectNextColumnExtendSelection", "shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl shift RIGHT", "selectNextColumnExtendSelection", "ctrl shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl RIGHT", "selectNextColumnChangeLead", "ctrl KP_RIGHT", "selectNextColumnChangeLead", "HOME", "selectFirstRow", "shift HOME", "selectFirstRowExtendSelection", "ctrl shift HOME", "selectFirstRowExtendSelection", "ctrl HOME", "selectFirstRowChangeLead", "END", "selectLastRow", "shift END", "selectLastRowExtendSelection", "ctrl shift END", "selectLastRowExtendSelection", "ctrl END", "selectLastRowChangeLead", "PAGE_UP", "scrollUp", "shift PAGE_UP", "scrollUpExtendSelection", "ctrl shift PAGE_UP", "scrollUpExtendSelection", "ctrl PAGE_UP", "scrollUpChangeLead", "PAGE_DOWN", "scrollDown", "shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl PAGE_DOWN", "scrollDownChangeLead", "ctrl A", "selectAll", "ctrl SLASH", "selectAll", "ctrl BACK_SLASH", "clearSelection", "SPACE", "addToSelection", "ctrl SPACE", "toggleAndAnchor", "shift SPACE", "extendTo", "ctrl shift SPACE", "moveSelectionTo" }), // ScrollBar "ScrollBar.background", control, "ScrollBar.highlight", controlHighlight, "ScrollBar.shadow", controlShadow, "ScrollBar.darkShadow", controlDarkShadow, "ScrollBar.thumb", primaryControlShadow, "ScrollBar.thumbShadow", primaryControlDarkShadow, "ScrollBar.thumbHighlight", primaryControl, "ScrollBar.width", new Integer( 17 ), "ScrollBar.allowsAbsolutePositioning", Boolean.TRUE, "ScrollBar.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "positiveUnitIncrement", "KP_RIGHT", "positiveUnitIncrement", "DOWN", "positiveUnitIncrement", "KP_DOWN", "positiveUnitIncrement", "PAGE_DOWN", "positiveBlockIncrement", "LEFT", "negativeUnitIncrement", "KP_LEFT", "negativeUnitIncrement", "UP", "negativeUnitIncrement", "KP_UP", "negativeUnitIncrement", "PAGE_UP", "negativeBlockIncrement", "HOME", "minScroll", "END", "maxScroll" }), // ScrollPane "ScrollPane.border", scrollPaneBorder, "ScrollPane.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "unitScrollRight", "KP_RIGHT", "unitScrollRight", "DOWN", "unitScrollDown", "KP_DOWN", "unitScrollDown", "LEFT", "unitScrollLeft", "KP_LEFT", "unitScrollLeft", "UP", "unitScrollUp", "KP_UP", "unitScrollUp", "PAGE_UP", "scrollUp", "PAGE_DOWN", "scrollDown", "ctrl PAGE_UP", "scrollLeft", "ctrl PAGE_DOWN", "scrollRight", "ctrl HOME", "scrollHome", "ctrl END", "scrollEnd" }), // Tabbed Pane "TabbedPane.font", controlTextValue, "TabbedPane.tabAreaBackground", control, "TabbedPane.background", controlShadow, "TabbedPane.light", control, "TabbedPane.focus", primaryControlDarkShadow, "TabbedPane.selected", control, "TabbedPane.selectHighlight", controlHighlight, "TabbedPane.tabAreaInsets", tabbedPaneTabAreaInsets, "TabbedPane.tabInsets", tabbedPaneTabInsets, "TabbedPane.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "navigateRight", "KP_RIGHT", "navigateRight", "LEFT", "navigateLeft", "KP_LEFT", "navigateLeft", "UP", "navigateUp", "KP_UP", "navigateUp", "DOWN", "navigateDown", "KP_DOWN", "navigateDown", "ctrl DOWN", "requestFocusForVisibleComponent", "ctrl KP_DOWN", "requestFocusForVisibleComponent", }), "TabbedPane.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl PAGE_DOWN", "navigatePageDown", "ctrl PAGE_UP", "navigatePageUp", "ctrl UP", "requestFocus", "ctrl KP_UP", "requestFocus", }), // Table "Table.font", userTextValue, "Table.focusCellHighlightBorder", focusCellHighlightBorder, "Table.scrollPaneBorder", scrollPaneBorder, "Table.dropLineColor", focusColor, "Table.dropLineShortColor", primaryControlDarkShadow, "Table.gridColor", controlShadow, // grid line color "Table.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl C", "copy", "ctrl V", "paste", "ctrl X", "cut", "COPY", "copy", "PASTE", "paste", "CUT", "cut", "control INSERT", "copy", "shift INSERT", "paste", "shift DELETE", "cut", "RIGHT", "selectNextColumn", "KP_RIGHT", "selectNextColumn", "shift RIGHT", "selectNextColumnExtendSelection", "shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl shift RIGHT", "selectNextColumnExtendSelection", "ctrl shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl RIGHT", "selectNextColumnChangeLead", "ctrl KP_RIGHT", "selectNextColumnChangeLead", "LEFT", "selectPreviousColumn", "KP_LEFT", "selectPreviousColumn", "shift LEFT", "selectPreviousColumnExtendSelection", "shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl shift LEFT", "selectPreviousColumnExtendSelection", "ctrl shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl LEFT", "selectPreviousColumnChangeLead", "ctrl KP_LEFT", "selectPreviousColumnChangeLead", "DOWN", "selectNextRow", "KP_DOWN", "selectNextRow", "shift DOWN", "selectNextRowExtendSelection", "shift KP_DOWN", "selectNextRowExtendSelection", "ctrl shift DOWN", "selectNextRowExtendSelection", "ctrl shift KP_DOWN", "selectNextRowExtendSelection", "ctrl DOWN", "selectNextRowChangeLead", "ctrl KP_DOWN", "selectNextRowChangeLead", "UP", "selectPreviousRow", "KP_UP", "selectPreviousRow", "shift UP", "selectPreviousRowExtendSelection", "shift KP_UP", "selectPreviousRowExtendSelection", "ctrl shift UP", "selectPreviousRowExtendSelection", "ctrl shift KP_UP", "selectPreviousRowExtendSelection", "ctrl UP", "selectPreviousRowChangeLead", "ctrl KP_UP", "selectPreviousRowChangeLead", "HOME", "selectFirstColumn", "shift HOME", "selectFirstColumnExtendSelection", "ctrl shift HOME", "selectFirstRowExtendSelection", "ctrl HOME", "selectFirstRow", "END", "selectLastColumn", "shift END", "selectLastColumnExtendSelection", "ctrl shift END", "selectLastRowExtendSelection", "ctrl END", "selectLastRow", "PAGE_UP", "scrollUpChangeSelection", "shift PAGE_UP", "scrollUpExtendSelection", "ctrl shift PAGE_UP", "scrollLeftExtendSelection", "ctrl PAGE_UP", "scrollLeftChangeSelection", "PAGE_DOWN", "scrollDownChangeSelection", "shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl shift PAGE_DOWN", "scrollRightExtendSelection", "ctrl PAGE_DOWN", "scrollRightChangeSelection", "TAB", "selectNextColumnCell", "shift TAB", "selectPreviousColumnCell", "ENTER", "selectNextRowCell", "shift ENTER", "selectPreviousRowCell", "ctrl A", "selectAll", "ctrl SLASH", "selectAll", "ctrl BACK_SLASH", "clearSelection", "ESCAPE", "cancel", "F2", "startEditing", "SPACE", "addToSelection", "ctrl SPACE", "toggleAndAnchor", "shift SPACE", "extendTo", "ctrl shift SPACE", "moveSelectionTo", "F8", "focusHeader" }), "Table.ascendingSortIcon", SwingUtilities2.makeIcon(getClass(), MetalLookAndFeel.class, "icons/sortUp.png"), "Table.descendingSortIcon", SwingUtilities2.makeIcon(getClass(), MetalLookAndFeel.class, "icons/sortDown.png"), "TableHeader.font", userTextValue, "TableHeader.cellBorder", new SwingLazyValue( "javax.swing.plaf.metal.MetalBorders$TableHeaderBorder"), // MenuBar "MenuBar.border", menuBarBorder, "MenuBar.font", menuTextValue, "MenuBar.windowBindings", new Object[] { "F10", "takeFocus" }, // Menu "Menu.border", menuItemBorder, "Menu.borderPainted", Boolean.TRUE, "Menu.menuPopupOffsetX", zero, "Menu.menuPopupOffsetY", zero, "Menu.submenuPopupOffsetX", new Integer(-4), "Menu.submenuPopupOffsetY", new Integer(-3), "Menu.font", menuTextValue, "Menu.selectionForeground", menuSelectedForeground, "Menu.selectionBackground", menuSelectedBackground, "Menu.disabledForeground", menuDisabledForeground, "Menu.acceleratorFont", subTextValue, "Menu.acceleratorForeground", acceleratorForeground, "Menu.acceleratorSelectionForeground", acceleratorSelectedForeground, "Menu.checkIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getMenuItemCheckIcon"), "Menu.arrowIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getMenuArrowIcon"), // Menu Item "MenuItem.border", menuItemBorder, "MenuItem.borderPainted", Boolean.TRUE, "MenuItem.font", menuTextValue, "MenuItem.selectionForeground", menuSelectedForeground, "MenuItem.selectionBackground", menuSelectedBackground, "MenuItem.disabledForeground", menuDisabledForeground, "MenuItem.acceleratorFont", subTextValue, "MenuItem.acceleratorForeground", acceleratorForeground, "MenuItem.acceleratorSelectionForeground", acceleratorSelectedForeground, "MenuItem.acceleratorDelimiter", menuItemAcceleratorDelimiter, "MenuItem.checkIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getMenuItemCheckIcon"), "MenuItem.arrowIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getMenuItemArrowIcon"), // Menu Item Auditory Cue Mapping "MenuItem.commandSound", "sounds/MenuItemCommand.wav", // OptionPane. "OptionPane.windowBindings", new Object[] { "ESCAPE", "close" }, // Option Pane Auditory Cue Mappings "OptionPane.informationSound", "sounds/OptionPaneInformation.wav", "OptionPane.warningSound", "sounds/OptionPaneWarning.wav", "OptionPane.errorSound", "sounds/OptionPaneError.wav", "OptionPane.questionSound", "sounds/OptionPaneQuestion.wav", // Option Pane Special Dialog Colors, used when MetalRootPaneUI // is providing window manipulation widgets. "OptionPane.errorDialog.border.background", new ColorUIResource(153, 51, 51), "OptionPane.errorDialog.titlePane.foreground", new ColorUIResource(51, 0, 0), "OptionPane.errorDialog.titlePane.background", new ColorUIResource(255, 153, 153), "OptionPane.errorDialog.titlePane.shadow", new ColorUIResource(204, 102, 102), "OptionPane.questionDialog.border.background", new ColorUIResource(51, 102, 51), "OptionPane.questionDialog.titlePane.foreground", new ColorUIResource(0, 51, 0), "OptionPane.questionDialog.titlePane.background", new ColorUIResource(153, 204, 153), "OptionPane.questionDialog.titlePane.shadow", new ColorUIResource(102, 153, 102), "OptionPane.warningDialog.border.background", new ColorUIResource(153, 102, 51), "OptionPane.warningDialog.titlePane.foreground", new ColorUIResource(102, 51, 0), "OptionPane.warningDialog.titlePane.background", new ColorUIResource(255, 204, 153), "OptionPane.warningDialog.titlePane.shadow", new ColorUIResource(204, 153, 102), // OptionPane fonts are defined below // Separator "Separator.background", getSeparatorBackground(), "Separator.foreground", getSeparatorForeground(), // Popup Menu "PopupMenu.border", popupMenuBorder, // Popup Menu Auditory Cue Mappings "PopupMenu.popupSound", "sounds/PopupMenuPopup.wav", "PopupMenu.font", menuTextValue, // CB & RB Menu Item "CheckBoxMenuItem.border", menuItemBorder, "CheckBoxMenuItem.borderPainted", Boolean.TRUE, "CheckBoxMenuItem.font", menuTextValue, "CheckBoxMenuItem.selectionForeground", menuSelectedForeground, "CheckBoxMenuItem.selectionBackground", menuSelectedBackground, "CheckBoxMenuItem.disabledForeground", menuDisabledForeground, "CheckBoxMenuItem.acceleratorFont", subTextValue, "CheckBoxMenuItem.acceleratorForeground", acceleratorForeground, "CheckBoxMenuItem.acceleratorSelectionForeground", acceleratorSelectedForeground, "CheckBoxMenuItem.checkIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getCheckBoxMenuItemIcon"), "CheckBoxMenuItem.arrowIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getMenuItemArrowIcon"), "CheckBoxMenuItem.commandSound", "sounds/MenuItemCommand.wav", "RadioButtonMenuItem.border", menuItemBorder, "RadioButtonMenuItem.borderPainted", Boolean.TRUE, "RadioButtonMenuItem.font", menuTextValue, "RadioButtonMenuItem.selectionForeground", menuSelectedForeground, "RadioButtonMenuItem.selectionBackground", menuSelectedBackground, "RadioButtonMenuItem.disabledForeground", menuDisabledForeground, "RadioButtonMenuItem.acceleratorFont", subTextValue, "RadioButtonMenuItem.acceleratorForeground", acceleratorForeground, "RadioButtonMenuItem.acceleratorSelectionForeground", acceleratorSelectedForeground, "RadioButtonMenuItem.checkIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getRadioButtonMenuItemIcon"), "RadioButtonMenuItem.arrowIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getMenuItemArrowIcon"), "RadioButtonMenuItem.commandSound", "sounds/MenuItemCommand.wav", "Spinner.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "UP", "increment", "KP_UP", "increment", "DOWN", "decrement", "KP_DOWN", "decrement", }), "Spinner.arrowButtonInsets", zeroInsets, "Spinner.border", textFieldBorder, "Spinner.arrowButtonBorder", buttonBorder, "Spinner.font", controlTextValue, // SplitPane "SplitPane.dividerSize", new Integer(10), "SplitPane.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "UP", "negativeIncrement", "DOWN", "positiveIncrement", "LEFT", "negativeIncrement", "RIGHT", "positiveIncrement", "KP_UP", "negativeIncrement", "KP_DOWN", "positiveIncrement", "KP_LEFT", "negativeIncrement", "KP_RIGHT", "positiveIncrement", "HOME", "selectMin", "END", "selectMax", "F8", "startResize", "F6", "toggleFocus", "ctrl TAB", "focusOutForward", "ctrl shift TAB", "focusOutBackward" }), "SplitPane.centerOneTouchButtons", Boolean.FALSE, "SplitPane.dividerFocusColor", primaryControl, // Tree // Tree.font was mapped to system font pre 1.4.1 "Tree.font", userTextValue, "Tree.textBackground", getWindowBackground(), "Tree.selectionBorderColor", focusColor, "Tree.openIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getTreeFolderIcon"), "Tree.closedIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getTreeFolderIcon"), "Tree.leafIcon", new SwingLazyValue("javax.swing.plaf.metal.MetalIconFactory", "getTreeLeafIcon"), "Tree.expandedIcon", new SwingLazyValue( "javax.swing.plaf.metal.MetalIconFactory", "getTreeControlIcon", new Object[] {Boolean.valueOf(MetalIconFactory.DARK)}), "Tree.collapsedIcon", new SwingLazyValue( "javax.swing.plaf.metal.MetalIconFactory", "getTreeControlIcon", new Object[] {Boolean.valueOf( MetalIconFactory.LIGHT )}), "Tree.line", primaryControl, // horiz lines "Tree.hash", primaryControl, // legs "Tree.rowHeight", zero, "Tree.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "ADD", "expand", "SUBTRACT", "collapse", "ctrl C", "copy", "ctrl V", "paste", "ctrl X", "cut", "COPY", "copy", "PASTE", "paste", "CUT", "cut", "control INSERT", "copy", "shift INSERT", "paste", "shift DELETE", "cut", "UP", "selectPrevious", "KP_UP", "selectPrevious", "shift UP", "selectPreviousExtendSelection", "shift KP_UP", "selectPreviousExtendSelection", "ctrl shift UP", "selectPreviousExtendSelection", "ctrl shift KP_UP", "selectPreviousExtendSelection", "ctrl UP", "selectPreviousChangeLead", "ctrl KP_UP", "selectPreviousChangeLead", "DOWN", "selectNext", "KP_DOWN", "selectNext", "shift DOWN", "selectNextExtendSelection", "shift KP_DOWN", "selectNextExtendSelection", "ctrl shift DOWN", "selectNextExtendSelection", "ctrl shift KP_DOWN", "selectNextExtendSelection", "ctrl DOWN", "selectNextChangeLead", "ctrl KP_DOWN", "selectNextChangeLead", "RIGHT", "selectChild", "KP_RIGHT", "selectChild", "LEFT", "selectParent", "KP_LEFT", "selectParent", "PAGE_UP", "scrollUpChangeSelection", "shift PAGE_UP", "scrollUpExtendSelection", "ctrl shift PAGE_UP", "scrollUpExtendSelection", "ctrl PAGE_UP", "scrollUpChangeLead", "PAGE_DOWN", "scrollDownChangeSelection", "shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl PAGE_DOWN", "scrollDownChangeLead", "HOME", "selectFirst", "shift HOME", "selectFirstExtendSelection", "ctrl shift HOME", "selectFirstExtendSelection", "ctrl HOME", "selectFirstChangeLead", "END", "selectLast", "shift END", "selectLastExtendSelection", "ctrl shift END", "selectLastExtendSelection", "ctrl END", "selectLastChangeLead", "F2", "startEditing", "ctrl A", "selectAll", "ctrl SLASH", "selectAll", "ctrl BACK_SLASH", "clearSelection", "ctrl LEFT", "scrollLeft", "ctrl KP_LEFT", "scrollLeft", "ctrl RIGHT", "scrollRight", "ctrl KP_RIGHT", "scrollRight", "SPACE", "addToSelection", "ctrl SPACE", "toggleAndAnchor", "shift SPACE", "extendTo", "ctrl shift SPACE", "moveSelectionTo" }), "Tree.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ESCAPE", "cancel" }), // ToolBar "ToolBar.border", toolBarBorder, "ToolBar.background", menuBackground, "ToolBar.foreground", getMenuForeground(), "ToolBar.font", menuTextValue, "ToolBar.dockingBackground", menuBackground, "ToolBar.floatingBackground", menuBackground, "ToolBar.dockingForeground", primaryControlDarkShadow, "ToolBar.floatingForeground", primaryControl, "ToolBar.rolloverBorder", new MetalLazyValue( "javax.swing.plaf.metal.MetalBorders", "getToolBarRolloverBorder"), "ToolBar.nonrolloverBorder", new MetalLazyValue( "javax.swing.plaf.metal.MetalBorders", "getToolBarNonrolloverBorder"), "ToolBar.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "UP", "navigateUp", "KP_UP", "navigateUp", "DOWN", "navigateDown", "KP_DOWN", "navigateDown", "LEFT", "navigateLeft", "KP_LEFT", "navigateLeft", "RIGHT", "navigateRight", "KP_RIGHT", "navigateRight" }), // RootPane "RootPane.frameBorder", new MetalLazyValue( "javax.swing.plaf.metal.MetalBorders$FrameBorder"), "RootPane.plainDialogBorder", dialogBorder, "RootPane.informationDialogBorder", dialogBorder, "RootPane.errorDialogBorder", new MetalLazyValue( "javax.swing.plaf.metal.MetalBorders$ErrorDialogBorder"), "RootPane.colorChooserDialogBorder", questionDialogBorder, "RootPane.fileChooserDialogBorder", questionDialogBorder, "RootPane.questionDialogBorder", questionDialogBorder, "RootPane.warningDialogBorder", new MetalLazyValue( "javax.swing.plaf.metal.MetalBorders$WarningDialogBorder"), // These bindings are only enabled when there is a default // button set on the rootpane. "RootPane.defaultButtonWindowKeyBindings", new Object[] { "ENTER", "press", "released ENTER", "release", "ctrl ENTER", "press", "ctrl released ENTER", "release" }, }; table.putDefaults(defaults); if (isWindows() && useSystemFonts() && theme.isSystemTheme()) { Toolkit kit = Toolkit.getDefaultToolkit(); Object messageFont = new MetalFontDesktopProperty( "win.messagebox.font.height", kit, MetalTheme. CONTROL_TEXT_FONT); defaults = new Object[] { "OptionPane.messageFont", messageFont, "OptionPane.buttonFont", messageFont, }; table.putDefaults(defaults); } flushUnreferenced(); // Remove old listeners boolean lafCond = SwingUtilities2.isLocalDisplay(); Object aaTextInfo = SwingUtilities2.AATextInfo.getAATextInfo(lafCond); table.put(SwingUtilities2.AA_TEXT_PROPERTY_KEY, aaTextInfo); new AATextListener(this); } /** {@collect.stats} * Ensures the current {@code MetalTheme} is {@code non-null}. This is * a cover method for {@code getCurrentTheme}. * * @see #getCurrentTheme */ protected void createDefaultTheme() { getCurrentTheme(); } /** {@collect.stats} * Returns the look and feel defaults. This invokes, in order, * {@code createDefaultTheme()}, {@code super.getDefaults()} and * {@code getCurrentTheme().addCustomEntriesToTable(table)}. * <p> * While this method is public, it should only be invoked by the * {@code UIManager} when the look and feel is set as the current * look and feel and after {@code initialize} has been invoked. * * @return the look and feel defaults * * @see #createDefaultTheme * @see javax.swing.plaf.basic.BasicLookAndFeel#getDefaults() * @see MetalTheme#addCustomEntriesToTable(UIDefaults) */ public UIDefaults getDefaults() { // PENDING: move this to initialize when API changes are allowed METAL_LOOK_AND_FEEL_INITED = true; createDefaultTheme(); UIDefaults table = super.getDefaults(); currentTheme.addCustomEntriesToTable(table); currentTheme.install(); return table; } /** {@collect.stats} * {@inheritDoc} * * @since 1.4 */ public void provideErrorFeedback(Component component) { super.provideErrorFeedback(component); } /** {@collect.stats} * Set the theme used by <code>MetalLookAndFeel</code>. * <p> * After the theme is set, {@code MetalLookAndFeel} needs to be * re-installed and the uis need to be recreated. The following * shows how to do this: * <pre> * MetalLookAndFeel.setCurrentTheme(theme); * * // re-install the Metal Look and Feel * UIManager.setLookAndFeel(new MetalLookAndFeel()); * * // Update the ComponentUIs for all Components. This * // needs to be invoked for all windows. * SwingUtilities.updateComponentTreeUI(rootComponent); * </pre> * If this is not done the results are undefined. * * @param theme the theme to use * @throws NullPointerException if {@code theme} is {@code null} * @see #getCurrentTheme */ public static void setCurrentTheme(MetalTheme theme) { // NOTE: because you need to recreate the look and feel after // this step, we don't bother blowing away any potential windows // values. if (theme == null) { throw new NullPointerException("Can't have null theme"); } currentTheme = theme; cachedAppContext = AppContext.getAppContext(); cachedAppContext.put( "currentMetalTheme", theme ); } /** {@collect.stats} * Return the theme currently being used by <code>MetalLookAndFeel</code>. * If the current theme is {@code null}, the default theme is created. * * @return the current theme * @see #setCurrentTheme * @since 1.5 */ public static MetalTheme getCurrentTheme() { AppContext context = AppContext.getAppContext(); if ( cachedAppContext != context ) { currentTheme = (MetalTheme)context.get( "currentMetalTheme" ); if (currentTheme == null) { // This will happen in two cases: // . When MetalLookAndFeel is first being initialized. // . When a new AppContext has been created that hasn't // triggered UIManager to load a LAF. Rather than invoke // a method on the UIManager, which would trigger the loading // of a potentially different LAF, we directly set the // Theme here. if (useHighContrastTheme()) { currentTheme = new MetalHighContrastTheme(); } else { // Create the default theme. We prefer Ocean, but will // use DefaultMetalTheme if told to. String theme = AccessController.doPrivileged( new GetPropertyAction("swing.metalTheme")); if ("steel".equals(theme)) { currentTheme = new DefaultMetalTheme(); } else { currentTheme = new OceanTheme(); } } setCurrentTheme(currentTheme); } cachedAppContext = context; } return currentTheme; } /** {@collect.stats} * Returns an <code>Icon</code> with a disabled appearance. * This method is used to generate a disabled <code>Icon</code> when * one has not been specified. For example, if you create a * <code>JButton</code> and only specify an <code>Icon</code> via * <code>setIcon</code> this method will be called to generate the * disabled <code>Icon</code>. If null is passed as <code>icon</code> * this method returns null. * <p> * Some look and feels might not render the disabled Icon, in which * case they will ignore this. * * @param component JComponent that will display the Icon, may be null * @param icon Icon to generate disable icon from. * @return Disabled icon, or null if a suitable Icon can not be * generated. * @since 1.5 */ public Icon getDisabledIcon(JComponent component, Icon icon) { if ((icon instanceof ImageIcon) && MetalLookAndFeel.usingOcean()) { return MetalUtils.getOceanDisabledButtonIcon( ((ImageIcon)icon).getImage()); } return super.getDisabledIcon(component, icon); } /** {@collect.stats} * Returns an <code>Icon</code> for use by disabled * components that are also selected. This method is used to generate an * <code>Icon</code> for components that are in both the disabled and * selected states but do not have a specific <code>Icon</code> for this * state. For example, if you create a <code>JButton</code> and only * specify an <code>Icon</code> via <code>setIcon</code> this method * will be called to generate the disabled and selected * <code>Icon</code>. If null is passed as <code>icon</code> this method * returns null. * <p> * Some look and feels might not render the disabled and selected Icon, * in which case they will ignore this. * * @param component JComponent that will display the Icon, may be null * @param icon Icon to generate disabled and selected icon from. * @return Disabled and Selected icon, or null if a suitable Icon can not * be generated. * @since 1.5 */ public Icon getDisabledSelectedIcon(JComponent component, Icon icon) { if ((icon instanceof ImageIcon) && MetalLookAndFeel.usingOcean()) { return MetalUtils.getOceanDisabledButtonIcon( ((ImageIcon)icon).getImage()); } return super.getDisabledSelectedIcon(component, icon); } /** {@collect.stats} * Returns the control text font of the current theme. This is a * cover method for {@code getCurrentTheme().getControlTextColor()}. * * @return the control text font * * @see MetalTheme */ public static FontUIResource getControlTextFont() { return getCurrentTheme().getControlTextFont();} /** {@collect.stats} * Returns the sytem text font of the current theme. This is a * cover method for {@code getCurrentTheme().getSystemTextFont()}. * * @return the system text font * * @see MetalTheme */ public static FontUIResource getSystemTextFont() { return getCurrentTheme().getSystemTextFont();} /** {@collect.stats} * Returns the user text font of the current theme. This is a * cover method for {@code getCurrentTheme().getUserTextFont()}. * * @return the user text font * * @see MetalTheme */ public static FontUIResource getUserTextFont() { return getCurrentTheme().getUserTextFont();} /** {@collect.stats} * Returns the menu text font of the current theme. This is a * cover method for {@code getCurrentTheme().getMenuTextFont()}. * * @return the menu text font * * @see MetalTheme */ public static FontUIResource getMenuTextFont() { return getCurrentTheme().getMenuTextFont();} /** {@collect.stats} * Returns the window title font of the current theme. This is a * cover method for {@code getCurrentTheme().getWindowTitleFont()}. * * @return the window title font * * @see MetalTheme */ public static FontUIResource getWindowTitleFont() { return getCurrentTheme().getWindowTitleFont();} /** {@collect.stats} * Returns the sub-text font of the current theme. This is a * cover method for {@code getCurrentTheme().getSubTextFont()}. * * @return the sub-text font * * @see MetalTheme */ public static FontUIResource getSubTextFont() { return getCurrentTheme().getSubTextFont();} /** {@collect.stats} * Returns the desktop color of the current theme. This is a * cover method for {@code getCurrentTheme().getDesktopColor()}. * * @return the desktop color * * @see MetalTheme */ public static ColorUIResource getDesktopColor() { return getCurrentTheme().getDesktopColor(); } /** {@collect.stats} * Returns the focus color of the current theme. This is a * cover method for {@code getCurrentTheme().getFocusColor()}. * * @return the focus color * * @see MetalTheme */ public static ColorUIResource getFocusColor() { return getCurrentTheme().getFocusColor(); } /** {@collect.stats} * Returns the white color of the current theme. This is a * cover method for {@code getCurrentTheme().getWhite()}. * * @return the white color * * @see MetalTheme */ public static ColorUIResource getWhite() { return getCurrentTheme().getWhite(); } /** {@collect.stats} * Returns the black color of the current theme. This is a * cover method for {@code getCurrentTheme().getBlack()}. * * @return the black color * * @see MetalTheme */ public static ColorUIResource getBlack() { return getCurrentTheme().getBlack(); } /** {@collect.stats} * Returns the control color of the current theme. This is a * cover method for {@code getCurrentTheme().getControl()}. * * @return the control color * * @see MetalTheme */ public static ColorUIResource getControl() { return getCurrentTheme().getControl(); } /** {@collect.stats} * Returns the control shadow color of the current theme. This is a * cover method for {@code getCurrentTheme().getControlShadow()}. * * @return the control shadow color * * @see MetalTheme */ public static ColorUIResource getControlShadow() { return getCurrentTheme().getControlShadow(); } /** {@collect.stats} * Returns the control dark shadow color of the current theme. This is a * cover method for {@code getCurrentTheme().getControlDarkShadow()}. * * @return the control dark shadow color * * @see MetalTheme */ public static ColorUIResource getControlDarkShadow() { return getCurrentTheme().getControlDarkShadow(); } /** {@collect.stats} * Returns the control info color of the current theme. This is a * cover method for {@code getCurrentTheme().getControlInfo()}. * * @return the control info color * * @see MetalTheme */ public static ColorUIResource getControlInfo() { return getCurrentTheme().getControlInfo(); } /** {@collect.stats} * Returns the control highlight color of the current theme. This is a * cover method for {@code getCurrentTheme().getControlHighlight()}. * * @return the control highlight color * * @see MetalTheme */ public static ColorUIResource getControlHighlight() { return getCurrentTheme().getControlHighlight(); } /** {@collect.stats} * Returns the control disabled color of the current theme. This is a * cover method for {@code getCurrentTheme().getControlDisabled()}. * * @return the control disabled color * * @see MetalTheme */ public static ColorUIResource getControlDisabled() { return getCurrentTheme().getControlDisabled(); } /** {@collect.stats} * Returns the primary control color of the current theme. This is a * cover method for {@code getCurrentTheme().getPrimaryControl()}. * * @return the primary control color * * @see MetalTheme */ public static ColorUIResource getPrimaryControl() { return getCurrentTheme().getPrimaryControl(); } /** {@collect.stats} * Returns the primary control shadow color of the current theme. This is a * cover method for {@code getCurrentTheme().getPrimaryControlShadow()}. * * @return the primary control shadow color * * @see MetalTheme */ public static ColorUIResource getPrimaryControlShadow() { return getCurrentTheme().getPrimaryControlShadow(); } /** {@collect.stats} * Returns the primary control dark shadow color of the current * theme. This is a cover method for {@code * getCurrentTheme().getPrimaryControlDarkShadow()}. * * @return the primary control dark shadow color * * @see MetalTheme */ public static ColorUIResource getPrimaryControlDarkShadow() { return getCurrentTheme().getPrimaryControlDarkShadow(); } /** {@collect.stats} * Returns the primary control info color of the current theme. This is a * cover method for {@code getCurrentTheme().getPrimaryControlInfo()}. * * @return the primary control info color * * @see MetalTheme */ public static ColorUIResource getPrimaryControlInfo() { return getCurrentTheme().getPrimaryControlInfo(); } /** {@collect.stats} * Returns the primary control highlight color of the current * theme. This is a cover method for {@code * getCurrentTheme().getPrimaryControlHighlight()}. * * @return the primary control highlight color * * @see MetalTheme */ public static ColorUIResource getPrimaryControlHighlight() { return getCurrentTheme().getPrimaryControlHighlight(); } /** {@collect.stats} * Returns the system text color of the current theme. This is a * cover method for {@code getCurrentTheme().getSystemTextColor()}. * * @return the system text color * * @see MetalTheme */ public static ColorUIResource getSystemTextColor() { return getCurrentTheme().getSystemTextColor(); } /** {@collect.stats} * Returns the control text color of the current theme. This is a * cover method for {@code getCurrentTheme().getControlTextColor()}. * * @return the control text color * * @see MetalTheme */ public static ColorUIResource getControlTextColor() { return getCurrentTheme().getControlTextColor(); } /** {@collect.stats} * Returns the inactive control text color of the current theme. This is a * cover method for {@code * getCurrentTheme().getInactiveControlTextColor()}. * * @return the inactive control text color * * @see MetalTheme */ public static ColorUIResource getInactiveControlTextColor() { return getCurrentTheme().getInactiveControlTextColor(); } /** {@collect.stats} * Returns the inactive system text color of the current theme. This is a * cover method for {@code * getCurrentTheme().getInactiveSystemTextColor()}. * * @return the inactive system text color * * @see MetalTheme */ public static ColorUIResource getInactiveSystemTextColor() { return getCurrentTheme().getInactiveSystemTextColor(); } /** {@collect.stats} * Returns the user text color of the current theme. This is a * cover method for {@code getCurrentTheme().getUserTextColor()}. * * @return the user text color * * @see MetalTheme */ public static ColorUIResource getUserTextColor() { return getCurrentTheme().getUserTextColor(); } /** {@collect.stats} * Returns the text highlight color of the current theme. This is a * cover method for {@code getCurrentTheme().getTextHighlightColor()}. * * @return the text highlight color * * @see MetalTheme */ public static ColorUIResource getTextHighlightColor() { return getCurrentTheme().getTextHighlightColor(); } /** {@collect.stats} * Returns the highlighted text color of the current theme. This is a * cover method for {@code getCurrentTheme().getHighlightedTextColor()}. * * @return the highlighted text color * * @see MetalTheme */ public static ColorUIResource getHighlightedTextColor() { return getCurrentTheme().getHighlightedTextColor(); } /** {@collect.stats} * Returns the window background color of the current theme. This is a * cover method for {@code getCurrentTheme().getWindowBackground()}. * * @return the window background color * * @see MetalTheme */ public static ColorUIResource getWindowBackground() { return getCurrentTheme().getWindowBackground(); } /** {@collect.stats} * Returns the window title background color of the current * theme. This is a cover method for {@code * getCurrentTheme().getWindowTitleBackground()}. * * @return the window title background color * * @see MetalTheme */ public static ColorUIResource getWindowTitleBackground() { return getCurrentTheme().getWindowTitleBackground(); } /** {@collect.stats} * Returns the window title foreground color of the current * theme. This is a cover method for {@code * getCurrentTheme().getWindowTitleForeground()}. * * @return the window title foreground color * * @see MetalTheme */ public static ColorUIResource getWindowTitleForeground() { return getCurrentTheme().getWindowTitleForeground(); } /** {@collect.stats} * Returns the window title inactive background color of the current * theme. This is a cover method for {@code * getCurrentTheme().getWindowTitleInactiveBackground()}. * * @return the window title inactive background color * * @see MetalTheme */ public static ColorUIResource getWindowTitleInactiveBackground() { return getCurrentTheme().getWindowTitleInactiveBackground(); } /** {@collect.stats} * Returns the window title inactive foreground color of the current * theme. This is a cover method for {@code * getCurrentTheme().getWindowTitleInactiveForeground()}. * * @return the window title inactive foreground color * * @see MetalTheme */ public static ColorUIResource getWindowTitleInactiveForeground() { return getCurrentTheme().getWindowTitleInactiveForeground(); } /** {@collect.stats} * Returns the menu background color of the current theme. This is * a cover method for {@code getCurrentTheme().getMenuBackground()}. * * @return the menu background color * * @see MetalTheme */ public static ColorUIResource getMenuBackground() { return getCurrentTheme().getMenuBackground(); } /** {@collect.stats} * Returns the menu foreground color of the current theme. This is * a cover method for {@code getCurrentTheme().getMenuForeground()}. * * @return the menu foreground color * * @see MetalTheme */ public static ColorUIResource getMenuForeground() { return getCurrentTheme().getMenuForeground(); } /** {@collect.stats} * Returns the menu selected background color of the current theme. This is * a cover method for * {@code getCurrentTheme().getMenuSelectedBackground()}. * * @return the menu selected background color * * @see MetalTheme */ public static ColorUIResource getMenuSelectedBackground() { return getCurrentTheme().getMenuSelectedBackground(); } /** {@collect.stats} * Returns the menu selected foreground color of the current theme. This is * a cover method for * {@code getCurrentTheme().getMenuSelectedForeground()}. * * @return the menu selected foreground color * * @see MetalTheme */ public static ColorUIResource getMenuSelectedForeground() { return getCurrentTheme().getMenuSelectedForeground(); } /** {@collect.stats} * Returns the menu disabled foreground color of the current theme. This is * a cover method for * {@code getCurrentTheme().getMenuDisabledForeground()}. * * @return the menu disabled foreground color * * @see MetalTheme */ public static ColorUIResource getMenuDisabledForeground() { return getCurrentTheme().getMenuDisabledForeground(); } /** {@collect.stats} * Returns the separator background color of the current theme. This is * a cover method for {@code getCurrentTheme().getSeparatorBackground()}. * * @return the separator background color * * @see MetalTheme */ public static ColorUIResource getSeparatorBackground() { return getCurrentTheme().getSeparatorBackground(); } /** {@collect.stats} * Returns the separator foreground color of the current theme. This is * a cover method for {@code getCurrentTheme().getSeparatorForeground()}. * * @return the separator foreground color * * @see MetalTheme */ public static ColorUIResource getSeparatorForeground() { return getCurrentTheme().getSeparatorForeground(); } /** {@collect.stats} * Returns the accelerator foreground color of the current theme. This is * a cover method for {@code getCurrentTheme().getAcceleratorForeground()}. * * @return the separator accelerator foreground color * * @see MetalTheme */ public static ColorUIResource getAcceleratorForeground() { return getCurrentTheme().getAcceleratorForeground(); } /** {@collect.stats} * Returns the accelerator selected foreground color of the * current theme. This is a cover method for {@code * getCurrentTheme().getAcceleratorSelectedForeground()}. * * @return the accelerator selected foreground color * * @see MetalTheme */ public static ColorUIResource getAcceleratorSelectedForeground() { return getCurrentTheme().getAcceleratorSelectedForeground(); } /** {@collect.stats} * Returns a {@code LayoutStyle} implementing the Java look and feel * design guidelines as specified at * <a href="http://java.sun.com/products/jlf/ed2/book/HIG.Visual2.html">http://java.sun.com/products/jlf/ed2/book/HIG.Visual2.html</a>. * * @return LayoutStyle implementing the Java look and feel design * guidelines * @since 1.6 */ public LayoutStyle getLayoutStyle() { return MetalLayoutStyle.INSTANCE; } /** {@collect.stats} * MetalLazyValue is a slimmed down version of <code>ProxyLaxyValue</code>. * The code is duplicate so that it can get at the package private * classes in metal. */ private static class MetalLazyValue implements UIDefaults.LazyValue { /** {@collect.stats} * Name of the class to create. */ private String className; private String methodName; MetalLazyValue(String name) { this.className = name; } MetalLazyValue(String name, String methodName) { this(name); this.methodName = methodName; } public Object createValue(UIDefaults table) { try { final Class c = Class.forName(className); if (methodName == null) { return c.newInstance(); } Method method = (Method)AccessController.doPrivileged( new PrivilegedAction() { public Object run() { Method[] methods = c.getDeclaredMethods(); for (int counter = methods.length - 1; counter >= 0; counter--) { if (methods[counter].getName().equals(methodName)){ methods[counter].setAccessible(true); return methods[counter]; } } return null; } }); if (method != null) { return method.invoke(null, (Object[])null); } } catch (ClassNotFoundException cnfe) { } catch (InstantiationException ie) { } catch (IllegalAccessException iae) { } catch (InvocationTargetException ite) { } return null; } } /** {@collect.stats} * FontActiveValue redirects to the appropriate metal theme method. */ private static class FontActiveValue implements UIDefaults.ActiveValue { private int type; private MetalTheme theme; FontActiveValue(MetalTheme theme, int type) { this.theme = theme; this.type = type; } public Object createValue(UIDefaults table) { Object value = null; switch (type) { case MetalTheme.CONTROL_TEXT_FONT: value = theme.getControlTextFont(); break; case MetalTheme.SYSTEM_TEXT_FONT: value = theme.getSystemTextFont(); break; case MetalTheme.USER_TEXT_FONT: value = theme.getUserTextFont(); break; case MetalTheme.MENU_TEXT_FONT: value = theme.getMenuTextFont(); break; case MetalTheme.WINDOW_TITLE_FONT: value = theme.getWindowTitleFont(); break; case MetalTheme.SUB_TEXT_FONT: value = theme.getSubTextFont(); break; } return value; } } static ReferenceQueue queue = new ReferenceQueue(); static void flushUnreferenced() { AATextListener aatl; while ((aatl = (AATextListener)queue.poll()) != null) { aatl.dispose(); } } static class AATextListener extends WeakReference implements PropertyChangeListener { private String key = SunToolkit.DESKTOPFONTHINTS; AATextListener(LookAndFeel laf) { super(laf, queue); Toolkit tk = Toolkit.getDefaultToolkit(); tk.addPropertyChangeListener(key, this); } public void propertyChange(PropertyChangeEvent pce) { LookAndFeel laf = (LookAndFeel)get(); if (laf == null || laf != UIManager.getLookAndFeel()) { dispose(); return; } UIDefaults defaults = UIManager.getLookAndFeelDefaults(); boolean lafCond = SwingUtilities2.isLocalDisplay(); Object aaTextInfo = SwingUtilities2.AATextInfo.getAATextInfo(lafCond); defaults.put(SwingUtilities2.AA_TEXT_PROPERTY_KEY, aaTextInfo); updateUI(); } void dispose() { Toolkit tk = Toolkit.getDefaultToolkit(); tk.removePropertyChangeListener(key, this); } /** {@collect.stats} * Updates the UI of the passed in window and all its children. */ private static void updateWindowUI(Window window) { SwingUtilities.updateComponentTreeUI(window); Window ownedWins[] = window.getOwnedWindows(); for (int i=0; i < ownedWins.length; i++) { updateWindowUI(ownedWins[i]); } } /** {@collect.stats} * Updates the UIs of all the known Frames. */ private static void updateAllUIs() { Frame appFrames[] = Frame.getFrames(); for (int j=0; j < appFrames.length; j++) { updateWindowUI(appFrames[j]); } } /** {@collect.stats} * Indicates if an updateUI call is pending. */ private static boolean updatePending; /** {@collect.stats} * Sets whether or not an updateUI call is pending. */ private static synchronized void setUpdatePending(boolean update) { updatePending = update; } /** {@collect.stats} * Returns true if a UI update is pending. */ private static synchronized boolean isUpdatePending() { return updatePending; } protected void updateUI() { if (!isUpdatePending()) { setUpdatePending(true); Runnable uiUpdater = new Runnable() { public void run() { updateAllUIs(); setUpdatePending(false); } }; SwingUtilities.invokeLater(uiUpdater); } } } // From the JLF Design Guidelines: // http://java.sun.com/products/jlf/ed2/book/HIG.Visual2.html private static class MetalLayoutStyle extends DefaultLayoutStyle { private static MetalLayoutStyle INSTANCE = new MetalLayoutStyle(); @Override public int getPreferredGap(JComponent component1, JComponent component2, ComponentPlacement type, int position, Container parent) { // Checks args super.getPreferredGap(component1, component2, type, position, parent); int offset = 0; switch(type) { case INDENT: // Metal doesn't spec this. if (position == SwingConstants.EAST || position == SwingConstants.WEST) { int indent = getIndent(component1, position); if (indent > 0) { return indent; } return 12; } // Fall through to related. case RELATED: if (component1.getUIClassID() == "ToggleButtonUI" && component2.getUIClassID() == "ToggleButtonUI") { ButtonModel sourceModel = ((JToggleButton)component1). getModel(); ButtonModel targetModel = ((JToggleButton)component2). getModel(); if ((sourceModel instanceof DefaultButtonModel) && (targetModel instanceof DefaultButtonModel) && (((DefaultButtonModel)sourceModel).getGroup() == ((DefaultButtonModel)targetModel).getGroup()) && ((DefaultButtonModel)sourceModel).getGroup() != null) { // When toggle buttons are exclusive (that is, // they form a radio button set), separate // them with 2 pixels. This rule applies // whether the toggle buttons appear in a // toolbar or elsewhere in the interface. // Note: this number does not appear to // include any borders and so is not adjusted // by the border of the toggle button return 2; } // When toggle buttons are independent (like // checkboxes) and used outside a toolbar, // separate them with 5 pixels. if (usingOcean()) { return 6; } return 5; } offset = 6; break; case UNRELATED: offset = 12; break; } if (isLabelAndNonlabel(component1, component2, position)) { // Insert 12 pixels between the trailing edge of a // label and any associated components. Insert 12 // pixels between the trailing edge of a label and the // component it describes when labels are // right-aligned. When labels are left-aligned, insert // 12 pixels between the trailing edge of the longest // label and its associated component return getButtonGap(component1, component2, position, offset + 6); } return getButtonGap(component1, component2, position, offset); } @Override public int getContainerGap(JComponent component, int position, Container parent) { super.getContainerGap(component, position, parent); // Include 11 pixels between the bottom and right // borders of a dialog box and its command // buttons. (To the eye, the 11-pixel spacing appears // to be 12 pixels because the white borders on the // lower and right edges of the button components are // not visually significant.) // NOTE: this last text was designed with Steel in mind, // not Ocean. // // Insert 12 pixels between the edges of the panel and the // titled border. Insert 11 pixels between the top of the // title and the component above the titled border. Insert 12 // pixels between the bottom of the title and the top of the // first label in the panel. Insert 11 pixels between // component groups and between the bottom of the last // component and the lower border. return getButtonGap(component, position, 12 - getButtonAdjustment(component, position)); } @Override protected int getButtonGap(JComponent source, JComponent target, int position, int offset) { offset = super.getButtonGap(source, target, position, offset); if (offset > 0) { int buttonAdjustment = getButtonAdjustment(source, position); if (buttonAdjustment == 0) { buttonAdjustment = getButtonAdjustment( target, flipDirection(position)); } offset -= buttonAdjustment; } if (offset < 0) { return 0; } return offset; } private int getButtonAdjustment(JComponent source, int edge) { String classID = source.getUIClassID(); if (classID == "ButtonUI" || classID == "ToggleButtonUI") { if (!usingOcean() && (edge == SwingConstants.EAST || edge == SwingConstants.SOUTH)) { if (source.getBorder() instanceof UIResource) { return 1; } } } else if (edge == SwingConstants.SOUTH) { if ((classID == "RadioButtonUI" || classID == "CheckBoxUI") && !usingOcean()) { return 1; } } return 0; } } }
Java
/* * Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.metal; import sun.swing.SwingUtilities2; import sun.awt.AppContext; import javax.swing.*; import javax.swing.border.*; import javax.swing.plaf.basic.*; import java.awt.*; import java.awt.event.*; import java.beans.*; import javax.swing.plaf.*; /** {@collect.stats} * MetalButtonUI implementation * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Tom Santos */ public class MetalButtonUI extends BasicButtonUI { // NOTE: These are not really needed, but at this point we can't pull // them. Their values are updated purely for historical reasons. protected Color focusColor; protected Color selectColor; protected Color disabledTextColor; private static final Object METAL_BUTTON_UI_KEY = new Object(); // ******************************** // Create PLAF // ******************************** public static ComponentUI createUI(JComponent c) { AppContext appContext = AppContext.getAppContext(); MetalButtonUI metalButtonUI = (MetalButtonUI) appContext.get(METAL_BUTTON_UI_KEY); if (metalButtonUI == null) { metalButtonUI = new MetalButtonUI(); appContext.put(METAL_BUTTON_UI_KEY, metalButtonUI); } return metalButtonUI; } // ******************************** // Install // ******************************** public void installDefaults(AbstractButton b) { super.installDefaults(b); } public void uninstallDefaults(AbstractButton b) { super.uninstallDefaults(b); } // ******************************** // Create Listeners // ******************************** protected BasicButtonListener createButtonListener(AbstractButton b) { return super.createButtonListener(b); } // ******************************** // Default Accessors // ******************************** protected Color getSelectColor() { selectColor = UIManager.getColor(getPropertyPrefix() + "select"); return selectColor; } protected Color getDisabledTextColor() { disabledTextColor = UIManager.getColor(getPropertyPrefix() + "disabledText"); return disabledTextColor; } protected Color getFocusColor() { focusColor = UIManager.getColor(getPropertyPrefix() + "focus"); return focusColor; } // ******************************** // Paint // ******************************** /** {@collect.stats} * If necessary paints the background of the component, then * invokes <code>paint</code>. * * @param g Graphics to paint to * @param c JComponent painting on * @throws NullPointerException if <code>g</code> or <code>c</code> is * null * @see javax.swing.plaf.ComponentUI#update * @see javax.swing.plaf.ComponentUI#paint * @since 1.5 */ public void update(Graphics g, JComponent c) { AbstractButton button = (AbstractButton)c; if ((c.getBackground() instanceof UIResource) && button.isContentAreaFilled() && c.isEnabled()) { ButtonModel model = button.getModel(); if (!MetalUtils.isToolBarButton(c)) { if (!model.isArmed() && !model.isPressed() && MetalUtils.drawGradient( c, g, "Button.gradient", 0, 0, c.getWidth(), c.getHeight(), true)) { paint(g, c); return; } } else if (model.isRollover() && MetalUtils.drawGradient( c, g, "Button.gradient", 0, 0, c.getWidth(), c.getHeight(), true)) { paint(g, c); return; } } super.update(g, c); } protected void paintButtonPressed(Graphics g, AbstractButton b) { if ( b.isContentAreaFilled() ) { Dimension size = b.getSize(); g.setColor(getSelectColor()); g.fillRect(0, 0, size.width, size.height); } } protected void paintFocus(Graphics g, AbstractButton b, Rectangle viewRect, Rectangle textRect, Rectangle iconRect){ Rectangle focusRect = new Rectangle(); String text = b.getText(); boolean isIcon = b.getIcon() != null; // If there is text if ( text != null && !text.equals( "" ) ) { if ( !isIcon ) { focusRect.setBounds( textRect ); } else { focusRect.setBounds( iconRect.union( textRect ) ); } } // If there is an icon and no text else if ( isIcon ) { focusRect.setBounds( iconRect ); } g.setColor(getFocusColor()); g.drawRect((focusRect.x-1), (focusRect.y-1), focusRect.width+1, focusRect.height+1); } protected void paintText(Graphics g, JComponent c, Rectangle textRect, String text) { AbstractButton b = (AbstractButton) c; ButtonModel model = b.getModel(); FontMetrics fm = SwingUtilities2.getFontMetrics(c, g); int mnemIndex = b.getDisplayedMnemonicIndex(); /* Draw the Text */ if(model.isEnabled()) { /** {@collect.stats}* paint the text normally */ g.setColor(b.getForeground()); } else { /** {@collect.stats}* paint the text disabled ***/ g.setColor(getDisabledTextColor()); } SwingUtilities2.drawStringUnderlineCharAt(c, g,text,mnemIndex, textRect.x, textRect.y + fm.getAscent()); } }
Java
/* * Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.metal; import java.awt.*; import javax.swing.*; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.UIResource; import javax.swing.plaf.basic.*; /** {@collect.stats} * Metal implementation of <code>MenuBarUI</code>. This class is responsible * for providing the metal look and feel for <code>JMenuBar</code>s. * * @see javax.swing.plaf.MenuBarUI * @since 1.5 */ public class MetalMenuBarUI extends BasicMenuBarUI { /** {@collect.stats} * Creates the <code>ComponentUI</code> implementation for the passed * in component. * * @param x JComponent to create the ComponentUI implementation for * @return ComponentUI implementation for <code>x</code> * @throws NullPointerException if <code>x</code> is null */ public static ComponentUI createUI(JComponent x) { if (x == null) { throw new NullPointerException("Must pass in a non-null component"); } return new MetalMenuBarUI(); } /** {@collect.stats} * Configures the specified component appropriate for the metal look and * feel. * * @param c the component where this UI delegate is being installed * @throws NullPointerException if <code>c</code> is null. */ public void installUI(JComponent c) { super.installUI(c); MetalToolBarUI.register(c); } /** {@collect.stats} * Reverses configuration which was done on the specified component during * <code>installUI</code>. * * @param c the component where this UI delegate is being installed * @throws NullPointerException if <code>c</code> is null. */ public void uninstallUI(JComponent c) { super.uninstallUI(c); MetalToolBarUI.unregister(c); } /** {@collect.stats} * If necessary paints the background of the component, then * invokes <code>paint</code>. * * @param g Graphics to paint to * @param c JComponent painting on * @throws NullPointerException if <code>g</code> or <code>c</code> is * null * @see javax.swing.plaf.ComponentUI#update * @see javax.swing.plaf.ComponentUI#paint * @since 1.5 */ public void update(Graphics g, JComponent c) { boolean isOpaque = c.isOpaque(); if (g == null) { throw new NullPointerException("Graphics must be non-null"); } if (isOpaque && (c.getBackground() instanceof UIResource) && UIManager.get("MenuBar.gradient") != null) { if (MetalToolBarUI.doesMenuBarBorderToolBar((JMenuBar)c)) { JToolBar tb = (JToolBar)MetalToolBarUI. findRegisteredComponentOfType(c, JToolBar.class); if (tb.isOpaque() &&tb.getBackground() instanceof UIResource) { MetalUtils.drawGradient(c, g, "MenuBar.gradient", 0, 0, c.getWidth(), c.getHeight() + tb.getHeight(), true); paint(g, c); return; } } MetalUtils.drawGradient(c, g, "MenuBar.gradient", 0, 0, c.getWidth(), c.getHeight(),true); paint(g, c); } else { super.update(g, c); } } }
Java
/* * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.metal; import java.awt.Component; import java.awt.Container; import java.awt.LayoutManager; import java.awt.Adjustable; import java.awt.event.AdjustmentListener; import java.awt.event.AdjustmentEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.Graphics; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Point; import java.awt.Insets; import java.awt.Color; import java.awt.IllegalComponentStateException; import java.beans.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.*; import javax.swing.plaf.basic.BasicScrollBarUI; /** {@collect.stats} * Implementation of ScrollBarUI for the Metal Look and Feel * <p> * * @author Tom Santos * @author Steve Wilson */ public class MetalScrollBarUI extends BasicScrollBarUI { private static Color shadowColor; private static Color highlightColor; private static Color darkShadowColor; private static Color thumbColor; private static Color thumbShadow; private static Color thumbHighlightColor; protected MetalBumps bumps; protected MetalScrollButton increaseButton; protected MetalScrollButton decreaseButton; protected int scrollBarWidth; public static final String FREE_STANDING_PROP = "JScrollBar.isFreeStanding"; protected boolean isFreeStanding = true; public static ComponentUI createUI( JComponent c ) { return new MetalScrollBarUI(); } protected void installDefaults() { scrollBarWidth = ((Integer)(UIManager.get( "ScrollBar.width" ))).intValue(); super.installDefaults(); bumps = new MetalBumps( 10, 10, thumbHighlightColor, thumbShadow, thumbColor ); } protected void installListeners(){ super.installListeners(); ((ScrollBarListener)propertyChangeListener).handlePropertyChange( scrollbar.getClientProperty( FREE_STANDING_PROP ) ); } protected PropertyChangeListener createPropertyChangeListener(){ return new ScrollBarListener(); } protected void configureScrollBarColors() { super.configureScrollBarColors(); shadowColor = UIManager.getColor("ScrollBar.shadow"); highlightColor = UIManager.getColor("ScrollBar.highlight"); darkShadowColor = UIManager.getColor("ScrollBar.darkShadow"); thumbColor = UIManager.getColor("ScrollBar.thumb"); thumbShadow = UIManager.getColor("ScrollBar.thumbShadow"); thumbHighlightColor = UIManager.getColor("ScrollBar.thumbHighlight"); } public Dimension getPreferredSize( JComponent c ) { if ( scrollbar.getOrientation() == JScrollBar.VERTICAL ) { return new Dimension( scrollBarWidth, scrollBarWidth * 3 + 10 ); } else // Horizontal { return new Dimension( scrollBarWidth * 3 + 10, scrollBarWidth ); } } /** {@collect.stats} Returns the view that represents the decrease view. */ protected JButton createDecreaseButton( int orientation ) { decreaseButton = new MetalScrollButton( orientation, scrollBarWidth, isFreeStanding ); return decreaseButton; } /** {@collect.stats} Returns the view that represents the increase view. */ protected JButton createIncreaseButton( int orientation ) { increaseButton = new MetalScrollButton( orientation, scrollBarWidth, isFreeStanding ); return increaseButton; } protected void paintTrack( Graphics g, JComponent c, Rectangle trackBounds ) { g.translate( trackBounds.x, trackBounds.y ); boolean leftToRight = MetalUtils.isLeftToRight(c); if ( scrollbar.getOrientation() == JScrollBar.VERTICAL ) { if ( !isFreeStanding ) { trackBounds.width += 2; if ( !leftToRight ) { g.translate( -1, 0 ); } } if ( c.isEnabled() ) { g.setColor( darkShadowColor ); g.drawLine( 0, 0, 0, trackBounds.height - 1 ); g.drawLine( trackBounds.width - 2, 0, trackBounds.width - 2, trackBounds.height - 1 ); g.drawLine( 2, trackBounds.height - 1, trackBounds.width - 1, trackBounds.height - 1); g.drawLine( 2, 0, trackBounds.width - 2, 0 ); g.setColor( shadowColor ); // g.setColor( Color.red); g.drawLine( 1, 1, 1, trackBounds.height - 2 ); g.drawLine( 1, 1, trackBounds.width - 3, 1 ); if (scrollbar.getValue() != scrollbar.getMaximum()) { // thumb shadow int y = thumbRect.y + thumbRect.height - trackBounds.y; g.drawLine( 1, y, trackBounds.width-1, y); } g.setColor(highlightColor); g.drawLine( trackBounds.width - 1, 0, trackBounds.width - 1, trackBounds.height - 1 ); } else { MetalUtils.drawDisabledBorder(g, 0, 0, trackBounds.width, trackBounds.height ); } if ( !isFreeStanding ) { trackBounds.width -= 2; if ( !leftToRight ) { g.translate( 1, 0 ); } } } else // HORIZONTAL { if ( !isFreeStanding ) { trackBounds.height += 2; } if ( c.isEnabled() ) { g.setColor( darkShadowColor ); g.drawLine( 0, 0, trackBounds.width - 1, 0 ); // top g.drawLine( 0, 2, 0, trackBounds.height - 2 ); // left g.drawLine( 0, trackBounds.height - 2, trackBounds.width - 1, trackBounds.height - 2 ); // bottom g.drawLine( trackBounds.width - 1, 2, trackBounds.width - 1, trackBounds.height - 1 ); // right g.setColor( shadowColor ); // g.setColor( Color.red); g.drawLine( 1, 1, trackBounds.width - 2, 1 ); // top g.drawLine( 1, 1, 1, trackBounds.height - 3 ); // left g.drawLine( 0, trackBounds.height - 1, trackBounds.width - 1, trackBounds.height - 1 ); // bottom if (scrollbar.getValue() != scrollbar.getMaximum()) { // thumb shadow int x = thumbRect.x + thumbRect.width - trackBounds.x; g.drawLine( x, 1, x, trackBounds.height-1); } } else { MetalUtils.drawDisabledBorder(g, 0, 0, trackBounds.width, trackBounds.height ); } if ( !isFreeStanding ) { trackBounds.height -= 2; } } g.translate( -trackBounds.x, -trackBounds.y ); } protected void paintThumb( Graphics g, JComponent c, Rectangle thumbBounds ) { if (!c.isEnabled()) { return; } if (MetalLookAndFeel.usingOcean()) { oceanPaintThumb(g, c, thumbBounds); return; } boolean leftToRight = MetalUtils.isLeftToRight(c); g.translate( thumbBounds.x, thumbBounds.y ); if ( scrollbar.getOrientation() == JScrollBar.VERTICAL ) { if ( !isFreeStanding ) { thumbBounds.width += 2; if ( !leftToRight ) { g.translate( -1, 0 ); } } g.setColor( thumbColor ); g.fillRect( 0, 0, thumbBounds.width - 2, thumbBounds.height - 1 ); g.setColor( thumbShadow ); g.drawRect( 0, 0, thumbBounds.width - 2, thumbBounds.height - 1 ); g.setColor( thumbHighlightColor ); g.drawLine( 1, 1, thumbBounds.width - 3, 1 ); g.drawLine( 1, 1, 1, thumbBounds.height - 2 ); bumps.setBumpArea( thumbBounds.width - 6, thumbBounds.height - 7 ); bumps.paintIcon( c, g, 3, 4 ); if ( !isFreeStanding ) { thumbBounds.width -= 2; if ( !leftToRight ) { g.translate( 1, 0 ); } } } else // HORIZONTAL { if ( !isFreeStanding ) { thumbBounds.height += 2; } g.setColor( thumbColor ); g.fillRect( 0, 0, thumbBounds.width - 1, thumbBounds.height - 2 ); g.setColor( thumbShadow ); g.drawRect( 0, 0, thumbBounds.width - 1, thumbBounds.height - 2 ); g.setColor( thumbHighlightColor ); g.drawLine( 1, 1, thumbBounds.width - 3, 1 ); g.drawLine( 1, 1, 1, thumbBounds.height - 3 ); bumps.setBumpArea( thumbBounds.width - 7, thumbBounds.height - 6 ); bumps.paintIcon( c, g, 4, 3 ); if ( !isFreeStanding ) { thumbBounds.height -= 2; } } g.translate( -thumbBounds.x, -thumbBounds.y ); } private void oceanPaintThumb(Graphics g, JComponent c, Rectangle thumbBounds) { boolean leftToRight = MetalUtils.isLeftToRight(c); g.translate(thumbBounds.x, thumbBounds.y); if (scrollbar.getOrientation() == JScrollBar.VERTICAL) { if (!isFreeStanding) { thumbBounds.width += 2; if (!leftToRight) { g.translate(-1, 0); } } if (thumbColor != null) { g.setColor(thumbColor); g.fillRect(0, 0, thumbBounds.width - 2,thumbBounds.height - 1); } g.setColor(thumbShadow); g.drawRect(0, 0, thumbBounds.width - 2, thumbBounds.height - 1); g.setColor(thumbHighlightColor); g.drawLine(1, 1, thumbBounds.width - 3, 1); g.drawLine(1, 1, 1, thumbBounds.height - 2); MetalUtils.drawGradient(c, g, "ScrollBar.gradient", 2, 2, thumbBounds.width - 4, thumbBounds.height - 3, false); int gripSize = thumbBounds.width - 8; if (gripSize > 2 && thumbBounds.height >= 10) { g.setColor(MetalLookAndFeel.getPrimaryControlDarkShadow()); int gripY = thumbBounds.height / 2 - 2; for (int counter = 0; counter < 6; counter += 2) { g.fillRect(4, counter + gripY, gripSize, 1); } g.setColor(MetalLookAndFeel.getWhite()); gripY++; for (int counter = 0; counter < 6; counter += 2) { g.fillRect(5, counter + gripY, gripSize, 1); } } if (!isFreeStanding) { thumbBounds.width -= 2; if (!leftToRight) { g.translate(1, 0); } } } else { // HORIZONTAL if (!isFreeStanding) { thumbBounds.height += 2; } if (thumbColor != null) { g.setColor(thumbColor); g.fillRect(0, 0, thumbBounds.width - 1,thumbBounds.height - 2); } g.setColor(thumbShadow); g.drawRect(0, 0, thumbBounds.width - 1, thumbBounds.height - 2); g.setColor(thumbHighlightColor); g.drawLine(1, 1, thumbBounds.width - 2, 1); g.drawLine(1, 1, 1, thumbBounds.height - 3); MetalUtils.drawGradient(c, g, "ScrollBar.gradient", 2, 2, thumbBounds.width - 3, thumbBounds.height - 4, true); int gripSize = thumbBounds.height - 8; if (gripSize > 2 && thumbBounds.width >= 10) { g.setColor(MetalLookAndFeel.getPrimaryControlDarkShadow()); int gripX = thumbBounds.width / 2 - 2; for (int counter = 0; counter < 6; counter += 2) { g.fillRect(gripX + counter, 4, 1, gripSize); } g.setColor(MetalLookAndFeel.getWhite()); gripX++; for (int counter = 0; counter < 6; counter += 2) { g.fillRect(gripX + counter, 5, 1, gripSize); } } if (!isFreeStanding) { thumbBounds.height -= 2; } } g.translate( -thumbBounds.x, -thumbBounds.y ); } protected Dimension getMinimumThumbSize() { return new Dimension( scrollBarWidth, scrollBarWidth ); } /** {@collect.stats} * This is overridden only to increase the invalid area. This * ensures that the "Shadow" below the thumb is invalidated */ protected void setThumbBounds(int x, int y, int width, int height) { /* If the thumbs bounds haven't changed, we're done. */ if ((thumbRect.x == x) && (thumbRect.y == y) && (thumbRect.width == width) && (thumbRect.height == height)) { return; } /* Update thumbRect, and repaint the union of x,y,w,h and * the old thumbRect. */ int minX = Math.min(x, thumbRect.x); int minY = Math.min(y, thumbRect.y); int maxX = Math.max(x + width, thumbRect.x + thumbRect.width); int maxY = Math.max(y + height, thumbRect.y + thumbRect.height); thumbRect.setBounds(x, y, width, height); scrollbar.repaint(minX, minY, (maxX - minX)+1, (maxY - minY)+1); } class ScrollBarListener extends BasicScrollBarUI.PropertyChangeHandler { public void propertyChange(PropertyChangeEvent e) { String name = e.getPropertyName(); if ( name.equals( FREE_STANDING_PROP ) ) { handlePropertyChange( e.getNewValue() ); } else { super.propertyChange( e ); } } public void handlePropertyChange( Object newValue ) { if ( newValue != null ) { boolean temp = ((Boolean)newValue).booleanValue(); boolean becameFlush = temp == false && isFreeStanding == true; boolean becameNormal = temp == true && isFreeStanding == false; isFreeStanding = temp; if ( becameFlush ) { toFlush(); } else if ( becameNormal ) { toFreeStanding(); } } else { if ( !isFreeStanding ) { isFreeStanding = true; toFreeStanding(); } // This commented-out block is used for testing flush scrollbars. /* if ( isFreeStanding ) { isFreeStanding = false; toFlush(); } */ } if ( increaseButton != null ) { increaseButton.setFreeStanding( isFreeStanding ); } if ( decreaseButton != null ) { decreaseButton.setFreeStanding( isFreeStanding ); } } protected void toFlush() { scrollBarWidth -= 2; } protected void toFreeStanding() { scrollBarWidth += 2; } } // end class ScrollBarListener }
Java
/* * Copyright (c) 1998, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.metal; import java.awt.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.plaf.basic.*; /** {@collect.stats} * Metal's split pane divider * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Steve Wilson * @author Ralph kar */ class MetalSplitPaneDivider extends BasicSplitPaneDivider { private MetalBumps bumps = new MetalBumps(10, 10, MetalLookAndFeel.getControlHighlight(), MetalLookAndFeel.getControlDarkShadow(), MetalLookAndFeel.getControl() ); private MetalBumps focusBumps = new MetalBumps(10, 10, MetalLookAndFeel.getPrimaryControlHighlight(), MetalLookAndFeel.getPrimaryControlDarkShadow(), UIManager.getColor("SplitPane.dividerFocusColor")); private int inset = 2; private Color controlColor = MetalLookAndFeel.getControl(); private Color primaryControlColor = UIManager.getColor( "SplitPane.dividerFocusColor"); public MetalSplitPaneDivider(BasicSplitPaneUI ui) { super(ui); } public void paint(Graphics g) { MetalBumps usedBumps; if (splitPane.hasFocus()) { usedBumps = focusBumps; g.setColor(primaryControlColor); } else { usedBumps = bumps; g.setColor(controlColor); } Rectangle clip = g.getClipBounds(); Insets insets = getInsets(); g.fillRect(clip.x, clip.y, clip.width, clip.height); Dimension size = getSize(); size.width -= inset * 2; size.height -= inset * 2; int drawX = inset; int drawY = inset; if (insets != null) { size.width -= (insets.left + insets.right); size.height -= (insets.top + insets.bottom); drawX += insets.left; drawY += insets.top; } usedBumps.setBumpArea(size); usedBumps.paintIcon(this, g, drawX, drawY); super.paint(g); } /** {@collect.stats} * Creates and return an instance of JButton that can be used to * collapse the left component in the metal split pane. */ protected JButton createLeftOneTouchButton() { JButton b = new JButton() { // Sprite buffer for the arrow image of the left button int[][] buffer = {{0, 0, 0, 2, 2, 0, 0, 0, 0}, {0, 0, 2, 1, 1, 1, 0, 0, 0}, {0, 2, 1, 1, 1, 1, 1, 0, 0}, {2, 1, 1, 1, 1, 1, 1, 1, 0}, {0, 3, 3, 3, 3, 3, 3, 3, 3}}; public void setBorder(Border b) { } public void paint(Graphics g) { JSplitPane splitPane = getSplitPaneFromSuper(); if(splitPane != null) { int oneTouchSize = getOneTouchSizeFromSuper(); int orientation = getOrientationFromSuper(); int blockSize = Math.min(getDividerSize(), oneTouchSize); // Initialize the color array Color[] colors = { this.getBackground(), MetalLookAndFeel.getPrimaryControlDarkShadow(), MetalLookAndFeel.getPrimaryControlInfo(), MetalLookAndFeel.getPrimaryControlHighlight()}; // Fill the background first ... g.setColor(this.getBackground()); if (isOpaque()) { g.fillRect(0, 0, this.getWidth(), this.getHeight()); } // ... then draw the arrow. if (getModel().isPressed()) { // Adjust color mapping for pressed button state colors[1] = colors[2]; } if(orientation == JSplitPane.VERTICAL_SPLIT) { // Draw the image for a vertical split for (int i=1; i<=buffer[0].length; i++) { for (int j=1; j<blockSize; j++) { if (buffer[j-1][i-1] == 0) { continue; } else { g.setColor( colors[buffer[j-1][i-1]]); } g.drawLine(i, j, i, j); } } } else { // Draw the image for a horizontal split // by simply swaping the i and j axis. // Except the drawLine() call this code is // identical to the code block above. This was done // in order to remove the additional orientation // check for each pixel. for (int i=1; i<=buffer[0].length; i++) { for (int j=1; j<blockSize; j++) { if (buffer[j-1][i-1] == 0) { // Nothing needs // to be drawn continue; } else { // Set the color from the // color map g.setColor( colors[buffer[j-1][i-1]]); } // Draw a pixel g.drawLine(j, i, j, i); } } } } } // Don't want the button to participate in focus traversable. public boolean isFocusTraversable() { return false; } }; b.setRequestFocusEnabled(false); b.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); b.setFocusPainted(false); b.setBorderPainted(false); maybeMakeButtonOpaque(b); return b; } /** {@collect.stats} * If necessary <code>c</code> is made opaque. */ private void maybeMakeButtonOpaque(JComponent c) { Object opaque = UIManager.get("SplitPane.oneTouchButtonsOpaque"); if (opaque != null) { c.setOpaque(((Boolean)opaque).booleanValue()); } } /** {@collect.stats} * Creates and return an instance of JButton that can be used to * collapse the right component in the metal split pane. */ protected JButton createRightOneTouchButton() { JButton b = new JButton() { // Sprite buffer for the arrow image of the right button int[][] buffer = {{2, 2, 2, 2, 2, 2, 2, 2}, {0, 1, 1, 1, 1, 1, 1, 3}, {0, 0, 1, 1, 1, 1, 3, 0}, {0, 0, 0, 1, 1, 3, 0, 0}, {0, 0, 0, 0, 3, 0, 0, 0}}; public void setBorder(Border border) { } public void paint(Graphics g) { JSplitPane splitPane = getSplitPaneFromSuper(); if(splitPane != null) { int oneTouchSize = getOneTouchSizeFromSuper(); int orientation = getOrientationFromSuper(); int blockSize = Math.min(getDividerSize(), oneTouchSize); // Initialize the color array Color[] colors = { this.getBackground(), MetalLookAndFeel.getPrimaryControlDarkShadow(), MetalLookAndFeel.getPrimaryControlInfo(), MetalLookAndFeel.getPrimaryControlHighlight()}; // Fill the background first ... g.setColor(this.getBackground()); if (isOpaque()) { g.fillRect(0, 0, this.getWidth(), this.getHeight()); } // ... then draw the arrow. if (getModel().isPressed()) { // Adjust color mapping for pressed button state colors[1] = colors[2]; } if(orientation == JSplitPane.VERTICAL_SPLIT) { // Draw the image for a vertical split for (int i=1; i<=buffer[0].length; i++) { for (int j=1; j<blockSize; j++) { if (buffer[j-1][i-1] == 0) { continue; } else { g.setColor( colors[buffer[j-1][i-1]]); } g.drawLine(i, j, i, j); } } } else { // Draw the image for a horizontal split // by simply swaping the i and j axis. // Except the drawLine() call this code is // identical to the code block above. This was done // in order to remove the additional orientation // check for each pixel. for (int i=1; i<=buffer[0].length; i++) { for (int j=1; j<blockSize; j++) { if (buffer[j-1][i-1] == 0) { // Nothing needs // to be drawn continue; } else { // Set the color from the // color map g.setColor( colors[buffer[j-1][i-1]]); } // Draw a pixel g.drawLine(j, i, j, i); } } } } } // Don't want the button to participate in focus traversable. public boolean isFocusTraversable() { return false; } }; b.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); b.setFocusPainted(false); b.setBorderPainted(false); b.setRequestFocusEnabled(false); maybeMakeButtonOpaque(b); return b; } /** {@collect.stats} * Used to layout a MetalSplitPaneDivider. Layout for the divider * involves appropriately moving the left/right buttons around. * <p> * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of MetalSplitPaneDivider. */ public class MetalDividerLayout implements LayoutManager { // NOTE NOTE NOTE NOTE NOTE // This class is no longer used, the functionality has // been rolled into BasicSplitPaneDivider.DividerLayout as a // defaults property public void layoutContainer(Container c) { JButton leftButton = getLeftButtonFromSuper(); JButton rightButton = getRightButtonFromSuper(); JSplitPane splitPane = getSplitPaneFromSuper(); int orientation = getOrientationFromSuper(); int oneTouchSize = getOneTouchSizeFromSuper(); int oneTouchOffset = getOneTouchOffsetFromSuper(); Insets insets = getInsets(); // This layout differs from the one used in BasicSplitPaneDivider. // It does not center justify the oneTouchExpadable buttons. // This was necessary in order to meet the spec of the Metal // splitpane divider. if (leftButton != null && rightButton != null && c == MetalSplitPaneDivider.this) { if (splitPane.isOneTouchExpandable()) { if (orientation == JSplitPane.VERTICAL_SPLIT) { int extraY = (insets != null) ? insets.top : 0; int blockSize = getDividerSize(); if (insets != null) { blockSize -= (insets.top + insets.bottom); } blockSize = Math.min(blockSize, oneTouchSize); leftButton.setBounds(oneTouchOffset, extraY, blockSize * 2, blockSize); rightButton.setBounds(oneTouchOffset + oneTouchSize * 2, extraY, blockSize * 2, blockSize); } else { int blockSize = getDividerSize(); int extraX = (insets != null) ? insets.left : 0; if (insets != null) { blockSize -= (insets.left + insets.right); } blockSize = Math.min(blockSize, oneTouchSize); leftButton.setBounds(extraX, oneTouchOffset, blockSize, blockSize * 2); rightButton.setBounds(extraX, oneTouchOffset + oneTouchSize * 2, blockSize, blockSize * 2); } } else { leftButton.setBounds(-5, -5, 1, 1); rightButton.setBounds(-5, -5, 1, 1); } } } public Dimension minimumLayoutSize(Container c) { return new Dimension(0,0); } public Dimension preferredLayoutSize(Container c) { return new Dimension(0, 0); } public void removeLayoutComponent(Component c) {} public void addLayoutComponent(String string, Component c) {} } /* * The following methods only exist in order to be able to access protected * members in the superclass, because these are otherwise not available * in any inner class. */ int getOneTouchSizeFromSuper() { return super.ONE_TOUCH_SIZE; } int getOneTouchOffsetFromSuper() { return super.ONE_TOUCH_OFFSET; } int getOrientationFromSuper() { return super.orientation; } JSplitPane getSplitPaneFromSuper() { return super.splitPane; } JButton getLeftButtonFromSuper() { return super.leftButton; } JButton getRightButtonFromSuper() { return super.rightButton; } }
Java
/* * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.metal; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Color; import java.awt.Polygon; import javax.swing.*; import javax.swing.plaf.basic.BasicArrowButton; /** {@collect.stats} * JButton object for Metal scrollbar arrows. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Tom Santos * @author Steve Wilson */ public class MetalScrollButton extends BasicArrowButton { private static Color shadowColor; private static Color highlightColor; private boolean isFreeStanding = false; private int buttonWidth; public MetalScrollButton( int direction, int width, boolean freeStanding ) { super( direction ); shadowColor = UIManager.getColor("ScrollBar.darkShadow"); highlightColor = UIManager.getColor("ScrollBar.highlight"); buttonWidth = width; isFreeStanding = freeStanding; } public void setFreeStanding( boolean freeStanding ) { isFreeStanding = freeStanding; } public void paint( Graphics g ) { boolean leftToRight = MetalUtils.isLeftToRight(this); boolean isEnabled = getParent().isEnabled(); Color arrowColor = isEnabled ? MetalLookAndFeel.getControlInfo() : MetalLookAndFeel.getControlDisabled(); boolean isPressed = getModel().isPressed(); int width = getWidth(); int height = getHeight(); int w = width; int h = height; int arrowHeight = (height+1) / 4; int arrowWidth = (height+1) / 2; if ( isPressed ) { g.setColor( MetalLookAndFeel.getControlShadow() ); } else { g.setColor( getBackground() ); } g.fillRect( 0, 0, width, height ); if ( getDirection() == NORTH ) { if ( !isFreeStanding ) { height +=1; g.translate( 0, -1 ); width += 2; if ( !leftToRight ) { g.translate( -1, 0 ); } } // Draw the arrow g.setColor( arrowColor ); int startY = ((h+1) - arrowHeight) / 2; int startX = (w / 2); // System.out.println( "startX :" + startX + " startY :"+startY); for (int line = 0; line < arrowHeight; line++) { g.drawLine( startX-line, startY+line, startX +line+1, startY+line); } /* g.drawLine( 7, 6, 8, 6 ); g.drawLine( 6, 7, 9, 7 ); g.drawLine( 5, 8, 10, 8 ); g.drawLine( 4, 9, 11, 9 );*/ if (isEnabled) { g.setColor( highlightColor ); if ( !isPressed ) { g.drawLine( 1, 1, width - 3, 1 ); g.drawLine( 1, 1, 1, height - 1 ); } g.drawLine( width - 1, 1, width - 1, height - 1 ); g.setColor( shadowColor ); g.drawLine( 0, 0, width - 2, 0 ); g.drawLine( 0, 0, 0, height - 1 ); g.drawLine( width - 2, 2, width - 2, height - 1 ); } else { MetalUtils.drawDisabledBorder(g, 0, 0, width, height+1); } if ( !isFreeStanding ) { height -= 1; g.translate( 0, 1 ); width -= 2; if ( !leftToRight ) { g.translate( 1, 0 ); } } } else if ( getDirection() == SOUTH ) { if ( !isFreeStanding ) { height += 1; width += 2; if ( !leftToRight ) { g.translate( -1, 0 ); } } // Draw the arrow g.setColor( arrowColor ); int startY = (((h+1) - arrowHeight) / 2)+ arrowHeight-1; int startX = (w / 2); // System.out.println( "startX2 :" + startX + " startY2 :"+startY); for (int line = 0; line < arrowHeight; line++) { g.drawLine( startX-line, startY-line, startX +line+1, startY-line); } /* g.drawLine( 4, 5, 11, 5 ); g.drawLine( 5, 6, 10, 6 ); g.drawLine( 6, 7, 9, 7 ); g.drawLine( 7, 8, 8, 8 ); */ if (isEnabled) { g.setColor( highlightColor ); if ( !isPressed ) { g.drawLine( 1, 0, width - 3, 0 ); g.drawLine( 1, 0, 1, height - 3 ); } g.drawLine( 1, height - 1, width - 1, height - 1 ); g.drawLine( width - 1, 0, width - 1, height - 1 ); g.setColor( shadowColor ); g.drawLine( 0, 0, 0, height - 2 ); g.drawLine( width - 2, 0, width - 2, height - 2 ); g.drawLine( 2, height - 2, width - 2, height - 2 ); } else { MetalUtils.drawDisabledBorder(g, 0,-1, width, height+1); } if ( !isFreeStanding ) { height -= 1; width -= 2; if ( !leftToRight ) { g.translate( 1, 0 ); } } } else if ( getDirection() == EAST ) { if ( !isFreeStanding ) { height += 2; width += 1; } // Draw the arrow g.setColor( arrowColor ); int startX = (((w+1) - arrowHeight) / 2) + arrowHeight-1; int startY = (h / 2); //System.out.println( "startX2 :" + startX + " startY2 :"+startY); for (int line = 0; line < arrowHeight; line++) { g.drawLine( startX-line, startY-line, startX -line, startY+line+1); } /* g.drawLine( 5, 4, 5, 11 ); g.drawLine( 6, 5, 6, 10 ); g.drawLine( 7, 6, 7, 9 ); g.drawLine( 8, 7, 8, 8 );*/ if (isEnabled) { g.setColor( highlightColor ); if ( !isPressed ) { g.drawLine( 0, 1, width - 3, 1 ); g.drawLine( 0, 1, 0, height - 3 ); } g.drawLine( width - 1, 1, width - 1, height - 1 ); g.drawLine( 0, height - 1, width - 1, height - 1 ); g.setColor( shadowColor ); g.drawLine( 0, 0,width - 2, 0 ); g.drawLine( width - 2, 2, width - 2, height - 2 ); g.drawLine( 0, height - 2, width - 2, height - 2 ); } else { MetalUtils.drawDisabledBorder(g,-1,0, width+1, height); } if ( !isFreeStanding ) { height -= 2; width -= 1; } } else if ( getDirection() == WEST ) { if ( !isFreeStanding ) { height += 2; width += 1; g.translate( -1, 0 ); } // Draw the arrow g.setColor( arrowColor ); int startX = (((w+1) - arrowHeight) / 2); int startY = (h / 2); for (int line = 0; line < arrowHeight; line++) { g.drawLine( startX+line, startY-line, startX +line, startY+line+1); } /* g.drawLine( 6, 7, 6, 8 ); g.drawLine( 7, 6, 7, 9 ); g.drawLine( 8, 5, 8, 10 ); g.drawLine( 9, 4, 9, 11 );*/ if (isEnabled) { g.setColor( highlightColor ); if ( !isPressed ) { g.drawLine( 1, 1, width - 1, 1 ); g.drawLine( 1, 1, 1, height - 3 ); } g.drawLine( 1, height - 1, width - 1, height - 1 ); g.setColor( shadowColor ); g.drawLine( 0, 0, width - 1, 0 ); g.drawLine( 0, 0, 0, height - 2 ); g.drawLine( 2, height - 2, width - 1, height - 2 ); } else { MetalUtils.drawDisabledBorder(g,0,0, width+1, height); } if ( !isFreeStanding ) { height -= 2; width -= 1; g.translate( 1, 0 ); } } } public Dimension getPreferredSize() { if ( getDirection() == NORTH ) { return new Dimension( buttonWidth, buttonWidth - 2 ); } else if ( getDirection() == SOUTH ) { return new Dimension( buttonWidth, buttonWidth - (isFreeStanding ? 1 : 2) ); } else if ( getDirection() == EAST ) { return new Dimension( buttonWidth - (isFreeStanding ? 1 : 2), buttonWidth ); } else if ( getDirection() == WEST ) { return new Dimension( buttonWidth - 2, buttonWidth ); } else { return new Dimension( 0, 0 ); } } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getMaximumSize() { return new Dimension( Integer.MAX_VALUE, Integer.MAX_VALUE ); } public int getButtonWidth() { return buttonWidth; } }
Java
/* * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; /** {@collect.stats} * This interface is used to mark objects created by ComponentUI delegates. * The <code>ComponentUI.installUI()</code> and * <code>ComponentUI.uninstallUI()</code> methods can use this interface * to decide if a properties value has been overridden. For example, the * JList cellRenderer property is initialized by BasicListUI.installUI(), * only if it's initial value is null: * <pre> * if (list.getCellRenderer() == null) { * list.setCellRenderer((ListCellRenderer)(UIManager.get("List.cellRenderer"))); * } * </pre> * At uninstallUI() time we reset the property to null if its value * is an instance of UIResource: * <pre> * if (list.getCellRenderer() instanceof UIResource) { * list.setCellRenderer(null); * } *</pre> * This pattern applies to all properties except the java.awt.Component * properties font, foreground, and background. If one of these * properties isn't initialized, or is explicitly set to null, * its container provides the value. For this reason the * <code>"== null"</code> is unreliable when installUI() is called * to dynamically change a components look and feel. So at installUI() * time we check to see if the current value is a UIResource: *<pre> * if (!(list.getFont() instanceof UIResource)) { * list.setFont(UIManager.getFont("List.font")); * } * </pre> * * @see ComponentUI * @author Hans Muller * */ public interface UIResource { }
Java
/* * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; import java.awt.Rectangle; import javax.swing.JTree; import javax.swing.tree.TreePath; /** {@collect.stats} * Pluggable look and feel interface for JTree. * * @author Rob Davis * @author Scott Violet */ public abstract class TreeUI extends ComponentUI { /** {@collect.stats} * Returns the Rectangle enclosing the label portion that the * last item in path will be drawn into. Will return null if * any component in path is currently valid. */ public abstract Rectangle getPathBounds(JTree tree, TreePath path); /** {@collect.stats} * Returns the path for passed in row. If row is not visible * null is returned. */ public abstract TreePath getPathForRow(JTree tree, int row); /** {@collect.stats} * Returns the row that the last item identified in path is visible * at. Will return -1 if any of the elements in path are not * currently visible. */ public abstract int getRowForPath(JTree tree, TreePath path); /** {@collect.stats} * Returns the number of rows that are being displayed. */ public abstract int getRowCount(JTree tree); /** {@collect.stats} * Returns the path to the node that is closest to x,y. If * there is nothing currently visible this will return null, otherwise * it'll always return a valid path. If you need to test if the * returned object is exactly at x, y you should get the bounds for * the returned path and test x, y against that. */ public abstract TreePath getClosestPathForLocation(JTree tree, int x, int y); /** {@collect.stats} * Returns true if the tree is being edited. The item that is being * edited can be returned by getEditingPath(). */ public abstract boolean isEditing(JTree tree); /** {@collect.stats} * Stops the current editing session. This has no effect if the * tree isn't being edited. Returns true if the editor allows the * editing session to stop. */ public abstract boolean stopEditing(JTree tree); /** {@collect.stats} * Cancels the current editing session. This has no effect if the * tree isn't being edited. Returns true if the editor allows the * editing session to stop. */ public abstract void cancelEditing(JTree tree); /** {@collect.stats} * Selects the last item in path and tries to edit it. Editing will * fail if the CellEditor won't allow it for the selected item. */ public abstract void startEditingAtPath(JTree tree, TreePath path); /** {@collect.stats} * Returns the path to the element that is being edited. */ public abstract TreePath getEditingPath(JTree tree); }
Java
/* * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; /** {@collect.stats} * Pluggable look and feel interface for JSeparator. * * @author Georges Saab * @author David Karlton */ public abstract class SeparatorUI extends ComponentUI { }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; import javax.swing.ComponentInputMap; import javax.swing.JComponent; /** {@collect.stats} * A subclass of javax.swing.ComponentInputMap that implements UIResource. * UI classes which provide a ComponentInputMap should use this class. * * @author Scott Violet * @since 1.3 */ public class ComponentInputMapUIResource extends ComponentInputMap implements UIResource { public ComponentInputMapUIResource(JComponent component) { super(component); } }
Java
/* * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; import javax.swing.*; import javax.swing.colorchooser.*; /** {@collect.stats} * Pluggable look and feel interface for JColorChooser. * * @author Amy Fowler * @author Steve Wilson */ public abstract class ColorChooserUI extends ComponentUI { }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; import javax.swing.InputMap; /** {@collect.stats} * A subclass of javax.swing.InputMap that implements UIResource. * UI classes which provide a InputMap should use this class. * * @author Scott Violet * @since 1.3 */ public class InputMapUIResource extends InputMap implements UIResource { public InputMapUIResource() { } }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; import javax.swing.ActionMap; /** {@collect.stats} * A subclass of javax.swing.ActionMap that implements UIResource. * UI classes which provide an ActionMap should use this class. * * @author Scott Violet * @since 1.3 */ public class ActionMapUIResource extends ActionMap implements UIResource { public ActionMapUIResource() { } }
Java
/* * Copyright (c) 1998, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import java.io.*; /** {@collect.stats} * Center-positioning layout manager. * @author Tom Santos * @author Steve Wilson */ class CenterLayout implements LayoutManager, Serializable { public void addLayoutComponent(String name, Component comp) { } public void removeLayoutComponent(Component comp) { } public Dimension preferredLayoutSize( Container container ) { Component c = container.getComponent( 0 ); if ( c != null ) { Dimension size = c.getPreferredSize(); Insets insets = container.getInsets(); return new Dimension(size.width + insets.left + insets.right, size.height + insets.top + insets.bottom); } else { return new Dimension( 0, 0 ); } } public Dimension minimumLayoutSize(Container cont) { return preferredLayoutSize(cont); } public void layoutContainer(Container container) { if (container.getComponentCount() > 0) { Component c = container.getComponent(0); Dimension pref = c.getPreferredSize(); int containerWidth = container.getWidth(); int containerHeight = container.getHeight(); Insets containerInsets = container.getInsets(); containerWidth -= containerInsets.left + containerInsets.right; containerHeight -= containerInsets.top + containerInsets.bottom; int left = (containerWidth - pref.width) / 2 + containerInsets.left; int right = (containerHeight - pref.height) / 2 + containerInsets.top; c.setBounds(left, right, pref.width, pref.height); } } }
Java
/* * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.*; import javax.swing.table.*; import sun.swing.*; /** {@collect.stats} * BasicTableHeaderUI implementation * * @author Alan Chung * @author Philip Milne */ public class BasicTableHeaderUI extends TableHeaderUI { private static Cursor resizeCursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR); // // Instance Variables // /** {@collect.stats} The JTableHeader that is delegating the painting to this UI. */ protected JTableHeader header; protected CellRendererPane rendererPane; // Listeners that are attached to the JTable protected MouseInputListener mouseInputListener; // The column header over which the mouse currently is. private int rolloverColumn = -1; // The column that should be highlighted when the table header has the focus. private int selectedColumnIndex = 0; // Read ONLY via getSelectedColumnIndex! private static FocusListener focusListener = new FocusListener() { public void focusGained(FocusEvent e) { repaintHeader(e.getSource()); } public void focusLost(FocusEvent e) { repaintHeader(e.getSource()); } private void repaintHeader(Object source) { if (source instanceof JTableHeader) { JTableHeader th = (JTableHeader)source; BasicTableHeaderUI ui = (BasicTableHeaderUI)BasicLookAndFeel. getUIOfType(th.getUI(), BasicTableHeaderUI.class); if (ui == null) { return; } th.repaint(th.getHeaderRect(ui.getSelectedColumnIndex())); } } }; /** {@collect.stats} * This inner class is marked &quot;public&quot; due to a compiler bug. * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicTableUI. */ public class MouseInputHandler implements MouseInputListener { private int mouseXOffset; private Cursor otherCursor = resizeCursor; public void mouseClicked(MouseEvent e) { if (e.getClickCount() % 2 == 1 && SwingUtilities.isLeftMouseButton(e)){ JTable table = header.getTable(); RowSorter sorter; if (table != null && (sorter = table.getRowSorter()) != null) { int columnIndex = header.columnAtPoint(e.getPoint()); if (columnIndex != -1) { columnIndex = table.convertColumnIndexToModel( columnIndex); sorter.toggleSortOrder(columnIndex); } } } } private TableColumn getResizingColumn(Point p) { return getResizingColumn(p, header.columnAtPoint(p)); } private TableColumn getResizingColumn(Point p, int column) { if (column == -1) { return null; } Rectangle r = header.getHeaderRect(column); r.grow(-3, 0); if (r.contains(p)) { return null; } int midPoint = r.x + r.width/2; int columnIndex; if( header.getComponentOrientation().isLeftToRight() ) { columnIndex = (p.x < midPoint) ? column - 1 : column; } else { columnIndex = (p.x < midPoint) ? column : column - 1; } if (columnIndex == -1) { return null; } return header.getColumnModel().getColumn(columnIndex); } public void mousePressed(MouseEvent e) { header.setDraggedColumn(null); header.setResizingColumn(null); header.setDraggedDistance(0); Point p = e.getPoint(); // First find which header cell was hit TableColumnModel columnModel = header.getColumnModel(); int index = header.columnAtPoint(p); if (index != -1) { // The last 3 pixels + 3 pixels of next column are for resizing TableColumn resizingColumn = getResizingColumn(p, index); if (canResize(resizingColumn, header)) { header.setResizingColumn(resizingColumn); if( header.getComponentOrientation().isLeftToRight() ) { mouseXOffset = p.x - resizingColumn.getWidth(); } else { mouseXOffset = p.x + resizingColumn.getWidth(); } } else if (header.getReorderingAllowed()) { TableColumn hitColumn = columnModel.getColumn(index); header.setDraggedColumn(hitColumn); mouseXOffset = p.x; } } if (header.getReorderingAllowed()) { int oldRolloverColumn = rolloverColumn; rolloverColumn = -1; rolloverColumnUpdated(oldRolloverColumn, rolloverColumn); } } private void swapCursor() { Cursor tmp = header.getCursor(); header.setCursor(otherCursor); otherCursor = tmp; } public void mouseMoved(MouseEvent e) { if (canResize(getResizingColumn(e.getPoint()), header) != (header.getCursor() == resizeCursor)) { swapCursor(); } updateRolloverColumn(e); } public void mouseDragged(MouseEvent e) { int mouseX = e.getX(); TableColumn resizingColumn = header.getResizingColumn(); TableColumn draggedColumn = header.getDraggedColumn(); boolean headerLeftToRight = header.getComponentOrientation().isLeftToRight(); if (resizingColumn != null) { int oldWidth = resizingColumn.getWidth(); int newWidth; if (headerLeftToRight) { newWidth = mouseX - mouseXOffset; } else { newWidth = mouseXOffset - mouseX; } mouseXOffset += changeColumnWidth(resizingColumn, header, oldWidth, newWidth); } else if (draggedColumn != null) { TableColumnModel cm = header.getColumnModel(); int draggedDistance = mouseX - mouseXOffset; int direction = (draggedDistance < 0) ? -1 : 1; int columnIndex = viewIndexForColumn(draggedColumn); int newColumnIndex = columnIndex + (headerLeftToRight ? direction : -direction); if (0 <= newColumnIndex && newColumnIndex < cm.getColumnCount()) { int width = cm.getColumn(newColumnIndex).getWidth(); if (Math.abs(draggedDistance) > (width / 2)) { JTable table = header.getTable(); mouseXOffset = mouseXOffset + direction * width; header.setDraggedDistance(draggedDistance - direction * width); //Cache the selected column. int selectedIndex = table.convertColumnIndexToModel( getSelectedColumnIndex()); //Now do the move. cm.moveColumn(columnIndex, newColumnIndex); //Update the selected index. selectColumn( table.convertColumnIndexToView(selectedIndex), false); return; } } setDraggedDistance(draggedDistance, columnIndex); } updateRolloverColumn(e); } public void mouseReleased(MouseEvent e) { setDraggedDistance(0, viewIndexForColumn(header.getDraggedColumn())); header.setResizingColumn(null); header.setDraggedColumn(null); updateRolloverColumn(e); } public void mouseEntered(MouseEvent e) { updateRolloverColumn(e); } public void mouseExited(MouseEvent e) { int oldRolloverColumn = rolloverColumn; rolloverColumn = -1; rolloverColumnUpdated(oldRolloverColumn, rolloverColumn); } // // Protected & Private Methods // private void setDraggedDistance(int draggedDistance, int column) { header.setDraggedDistance(draggedDistance); if (column != -1) { header.getColumnModel().moveColumn(column, column); } } } // // Factory methods for the Listeners // /** {@collect.stats} * Creates the mouse listener for the JTableHeader. */ protected MouseInputListener createMouseInputListener() { return new MouseInputHandler(); } // // The installation/uninstall procedures and support // public static ComponentUI createUI(JComponent h) { return new BasicTableHeaderUI(); } // Installation public void installUI(JComponent c) { header = (JTableHeader)c; rendererPane = new CellRendererPane(); header.add(rendererPane); installDefaults(); installListeners(); installKeyboardActions(); } /** {@collect.stats} * Initialize JTableHeader properties, e.g. font, foreground, and background. * The font, foreground, and background properties are only set if their * current value is either null or a UIResource, other properties are set * if the current value is null. * * @see #installUI */ protected void installDefaults() { LookAndFeel.installColorsAndFont(header, "TableHeader.background", "TableHeader.foreground", "TableHeader.font"); LookAndFeel.installProperty(header, "opaque", Boolean.TRUE); } /** {@collect.stats} * Attaches listeners to the JTableHeader. */ protected void installListeners() { mouseInputListener = createMouseInputListener(); header.addMouseListener(mouseInputListener); header.addMouseMotionListener(mouseInputListener); header.addFocusListener(focusListener); } /** {@collect.stats} * Register all keyboard actions on the JTableHeader. */ protected void installKeyboardActions() { InputMap keyMap = (InputMap)DefaultLookup.get(header, this, "TableHeader.ancestorInputMap"); SwingUtilities.replaceUIInputMap(header, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, keyMap); LazyActionMap.installLazyActionMap(header, BasicTableHeaderUI.class, "TableHeader.actionMap"); } // Uninstall methods public void uninstallUI(JComponent c) { uninstallDefaults(); uninstallListeners(); uninstallKeyboardActions(); header.remove(rendererPane); rendererPane = null; header = null; } protected void uninstallDefaults() {} protected void uninstallListeners() { header.removeMouseListener(mouseInputListener); header.removeMouseMotionListener(mouseInputListener); mouseInputListener = null; } /** {@collect.stats} * Unregisters default key actions. */ protected void uninstallKeyboardActions() { SwingUtilities.replaceUIInputMap(header, JComponent.WHEN_FOCUSED, null); SwingUtilities.replaceUIActionMap(header, null); } /** {@collect.stats} * Populates TableHeader's actions. */ static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.TOGGLE_SORT_ORDER)); map.put(new Actions(Actions.SELECT_COLUMN_TO_LEFT)); map.put(new Actions(Actions.SELECT_COLUMN_TO_RIGHT)); map.put(new Actions(Actions.MOVE_COLUMN_LEFT)); map.put(new Actions(Actions.MOVE_COLUMN_RIGHT)); map.put(new Actions(Actions.RESIZE_LEFT)); map.put(new Actions(Actions.RESIZE_RIGHT)); map.put(new Actions(Actions.FOCUS_TABLE)); } // // Support for mouse rollover // /** {@collect.stats} * Returns the index of the column header over which the mouse * currently is. When the mouse is not over the table header, * -1 is returned. * * @see #rolloverColumnUpdated(int, int) * @return the index of the current rollover column * @since 1.6 */ protected int getRolloverColumn() { return rolloverColumn; } /** {@collect.stats} * This method gets called every time the rollover column in the table * header is updated. Every look and feel supporting rollover effect * in table header should override this method and repaint the header. * * @param oldColumn the index of the previous rollover column or -1 if the * mouse was not over a column * @param newColumn the index of the new rollover column or -1 if the mouse * is not over a column * @see #getRolloverColumn() * @see JTableHeader#getHeaderRect(int) * @since 1.6 */ protected void rolloverColumnUpdated(int oldColumn, int newColumn) { } private void updateRolloverColumn(MouseEvent e) { if (header.getDraggedColumn() == null && header.contains(e.getPoint())) { int col = header.columnAtPoint(e.getPoint()); if (col != rolloverColumn) { int oldRolloverColumn = rolloverColumn; rolloverColumn = col; rolloverColumnUpdated(oldRolloverColumn, rolloverColumn); } } } // // Support for keyboard and mouse access // private int selectNextColumn(boolean doIt) { int newIndex = getSelectedColumnIndex(); if (newIndex < header.getColumnModel().getColumnCount() - 1) { newIndex++; if (doIt) { selectColumn(newIndex); } } return newIndex; } private int selectPreviousColumn(boolean doIt) { int newIndex = getSelectedColumnIndex(); if (newIndex > 0) { newIndex--; if (doIt) { selectColumn(newIndex); } } return newIndex; } /** {@collect.stats} * Selects the specified column in the table header. Repaints the * affected header cells and makes sure the newly selected one is visible. */ void selectColumn(int newColIndex) { selectColumn(newColIndex, true); } void selectColumn(int newColIndex, boolean doScroll) { Rectangle repaintRect = header.getHeaderRect(selectedColumnIndex); header.repaint(repaintRect); selectedColumnIndex = newColIndex; repaintRect = header.getHeaderRect(newColIndex); header.repaint(repaintRect); if (doScroll) { scrollToColumn(newColIndex); } return; } /** {@collect.stats} * Used by selectColumn to scroll horizontally, if necessary, * to ensure that the newly selected column is visible. */ private void scrollToColumn(int col) { Container container; JTable table; //Test whether the header is in a scroll pane and has a table. if ((header.getParent() == null) || ((container = header.getParent().getParent()) == null) || !(container instanceof JScrollPane) || ((table = header.getTable()) == null)) { return; } //Now scroll, if necessary. Rectangle vis = table.getVisibleRect(); Rectangle cellBounds = table.getCellRect(0, col, true); vis.x = cellBounds.x; vis.width = cellBounds.width; table.scrollRectToVisible(vis); } private int getSelectedColumnIndex() { int numCols = header.getColumnModel().getColumnCount(); if (selectedColumnIndex >= numCols && numCols > 0) { selectedColumnIndex = numCols - 1; } return selectedColumnIndex; } private static boolean canResize(TableColumn column, JTableHeader header) { return (column != null) && header.getResizingAllowed() && column.getResizable(); } private int changeColumnWidth(TableColumn resizingColumn, JTableHeader th, int oldWidth, int newWidth) { resizingColumn.setWidth(newWidth); Container container; JTable table; if ((th.getParent() == null) || ((container = th.getParent().getParent()) == null) || !(container instanceof JScrollPane) || ((table = th.getTable()) == null)) { return 0; } if (!container.getComponentOrientation().isLeftToRight() && !th.getComponentOrientation().isLeftToRight()) { JViewport viewport = ((JScrollPane)container).getViewport(); int viewportWidth = viewport.getWidth(); int diff = newWidth - oldWidth; int newHeaderWidth = table.getWidth() + diff; /* Resize a table */ Dimension tableSize = table.getSize(); tableSize.width += diff; table.setSize(tableSize); /* If this table is in AUTO_RESIZE_OFF mode and * has a horizontal scrollbar, we need to update * a view's position. */ if ((newHeaderWidth >= viewportWidth) && (table.getAutoResizeMode() == JTable.AUTO_RESIZE_OFF)) { Point p = viewport.getViewPosition(); p.x = Math.max(0, Math.min(newHeaderWidth - viewportWidth, p.x + diff)); viewport.setViewPosition(p); return diff; } } return 0; } // // Baseline // /** {@collect.stats} * Returns the baseline. * * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public int getBaseline(JComponent c, int width, int height) { super.getBaseline(c, width, height); int baseline = -1; TableColumnModel columnModel = header.getColumnModel(); for(int column = 0; column < columnModel.getColumnCount(); column++) { TableColumn aColumn = columnModel.getColumn(column); Component comp = getHeaderRenderer(column); Dimension pref = comp.getPreferredSize(); int columnBaseline = comp.getBaseline(pref.width, height); if (columnBaseline >= 0) { if (baseline == -1) { baseline = columnBaseline; } else if (baseline != columnBaseline) { baseline = -1; break; } } } return baseline; } // // Paint Methods and support // public void paint(Graphics g, JComponent c) { if (header.getColumnModel().getColumnCount() <= 0) { return; } boolean ltr = header.getComponentOrientation().isLeftToRight(); Rectangle clip = g.getClipBounds(); Point left = clip.getLocation(); Point right = new Point( clip.x + clip.width - 1, clip.y ); TableColumnModel cm = header.getColumnModel(); int cMin = header.columnAtPoint( ltr ? left : right ); int cMax = header.columnAtPoint( ltr ? right : left ); // This should never happen. if (cMin == -1) { cMin = 0; } // If the table does not have enough columns to fill the view we'll get -1. // Replace this with the index of the last column. if (cMax == -1) { cMax = cm.getColumnCount()-1; } TableColumn draggedColumn = header.getDraggedColumn(); int columnWidth; Rectangle cellRect = header.getHeaderRect(ltr ? cMin : cMax); TableColumn aColumn; if (ltr) { for(int column = cMin; column <= cMax ; column++) { aColumn = cm.getColumn(column); columnWidth = aColumn.getWidth(); cellRect.width = columnWidth; if (aColumn != draggedColumn) { paintCell(g, cellRect, column); } cellRect.x += columnWidth; } } else { for(int column = cMax; column >= cMin; column--) { aColumn = cm.getColumn(column); columnWidth = aColumn.getWidth(); cellRect.width = columnWidth; if (aColumn != draggedColumn) { paintCell(g, cellRect, column); } cellRect.x += columnWidth; } } // Paint the dragged column if we are dragging. if (draggedColumn != null) { int draggedColumnIndex = viewIndexForColumn(draggedColumn); Rectangle draggedCellRect = header.getHeaderRect(draggedColumnIndex); // Draw a gray well in place of the moving column. g.setColor(header.getParent().getBackground()); g.fillRect(draggedCellRect.x, draggedCellRect.y, draggedCellRect.width, draggedCellRect.height); draggedCellRect.x += header.getDraggedDistance(); // Fill the background. g.setColor(header.getBackground()); g.fillRect(draggedCellRect.x, draggedCellRect.y, draggedCellRect.width, draggedCellRect.height); paintCell(g, draggedCellRect, draggedColumnIndex); } // Remove all components in the rendererPane. rendererPane.removeAll(); } private Component getHeaderRenderer(int columnIndex) { TableColumn aColumn = header.getColumnModel().getColumn(columnIndex); TableCellRenderer renderer = aColumn.getHeaderRenderer(); if (renderer == null) { renderer = header.getDefaultRenderer(); } boolean hasFocus = !header.isPaintingForPrint() && (columnIndex == getSelectedColumnIndex()) && header.hasFocus(); return renderer.getTableCellRendererComponent(header.getTable(), aColumn.getHeaderValue(), false, hasFocus, -1, columnIndex); } private void paintCell(Graphics g, Rectangle cellRect, int columnIndex) { Component component = getHeaderRenderer(columnIndex); rendererPane.paintComponent(g, component, header, cellRect.x, cellRect.y, cellRect.width, cellRect.height, true); } private int viewIndexForColumn(TableColumn aColumn) { TableColumnModel cm = header.getColumnModel(); for (int column = 0; column < cm.getColumnCount(); column++) { if (cm.getColumn(column) == aColumn) { return column; } } return -1; } // // Size Methods // private int getHeaderHeight() { int height = 0; boolean accomodatedDefault = false; TableColumnModel columnModel = header.getColumnModel(); for(int column = 0; column < columnModel.getColumnCount(); column++) { TableColumn aColumn = columnModel.getColumn(column); boolean isDefault = (aColumn.getHeaderRenderer() == null); if (!isDefault || !accomodatedDefault) { Component comp = getHeaderRenderer(column); int rendererHeight = comp.getPreferredSize().height; height = Math.max(height, rendererHeight); // Configuring the header renderer to calculate its preferred size // is expensive. Optimise this by assuming the default renderer // always has the same height as the first non-zero height that // it returns for a non-null/non-empty value. if (isDefault && rendererHeight > 0) { Object headerValue = aColumn.getHeaderValue(); if (headerValue != null) { headerValue = headerValue.toString(); if (headerValue != null && !headerValue.equals("")) { accomodatedDefault = true; } } } } } return height; } private Dimension createHeaderSize(long width) { TableColumnModel columnModel = header.getColumnModel(); // None of the callers include the intercell spacing, do it here. if (width > Integer.MAX_VALUE) { width = Integer.MAX_VALUE; } return new Dimension((int)width, getHeaderHeight()); } /** {@collect.stats} * Return the minimum size of the header. The minimum width is the sum * of the minimum widths of each column (plus inter-cell spacing). */ public Dimension getMinimumSize(JComponent c) { long width = 0; Enumeration enumeration = header.getColumnModel().getColumns(); while (enumeration.hasMoreElements()) { TableColumn aColumn = (TableColumn)enumeration.nextElement(); width = width + aColumn.getMinWidth(); } return createHeaderSize(width); } /** {@collect.stats} * Return the preferred size of the header. The preferred height is the * maximum of the preferred heights of all of the components provided * by the header renderers. The preferred width is the sum of the * preferred widths of each column (plus inter-cell spacing). */ public Dimension getPreferredSize(JComponent c) { long width = 0; Enumeration enumeration = header.getColumnModel().getColumns(); while (enumeration.hasMoreElements()) { TableColumn aColumn = (TableColumn)enumeration.nextElement(); width = width + aColumn.getPreferredWidth(); } return createHeaderSize(width); } /** {@collect.stats} * Return the maximum size of the header. The maximum width is the sum * of the maximum widths of each column (plus inter-cell spacing). */ public Dimension getMaximumSize(JComponent c) { long width = 0; Enumeration enumeration = header.getColumnModel().getColumns(); while (enumeration.hasMoreElements()) { TableColumn aColumn = (TableColumn)enumeration.nextElement(); width = width + aColumn.getMaxWidth(); } return createHeaderSize(width); } private static class Actions extends UIAction { public static final String TOGGLE_SORT_ORDER = "toggleSortOrder"; public static final String SELECT_COLUMN_TO_LEFT = "selectColumnToLeft"; public static final String SELECT_COLUMN_TO_RIGHT = "selectColumnToRight"; public static final String MOVE_COLUMN_LEFT = "moveColumnLeft"; public static final String MOVE_COLUMN_RIGHT = "moveColumnRight"; public static final String RESIZE_LEFT = "resizeLeft"; public static final String RESIZE_RIGHT = "resizeRight"; public static final String FOCUS_TABLE = "focusTable"; public Actions(String name) { super(name); } public boolean isEnabled(Object sender) { if (sender instanceof JTableHeader) { JTableHeader th = (JTableHeader)sender; TableColumnModel cm = th.getColumnModel(); if (cm.getColumnCount() <= 0) { return false; } String key = getName(); BasicTableHeaderUI ui = (BasicTableHeaderUI)BasicLookAndFeel.getUIOfType(th.getUI(), BasicTableHeaderUI.class); if (ui != null) { if (key == MOVE_COLUMN_LEFT) { return th.getReorderingAllowed() && maybeMoveColumn(true, th, ui, false); } else if (key == MOVE_COLUMN_RIGHT) { return th.getReorderingAllowed() && maybeMoveColumn(false, th, ui, false); } else if (key == RESIZE_LEFT || key == RESIZE_RIGHT) { return canResize(cm.getColumn(ui.getSelectedColumnIndex()), th); } else if (key == FOCUS_TABLE) { return (th.getTable() != null); } } } return true; } public void actionPerformed(ActionEvent e) { JTableHeader th = (JTableHeader)e.getSource(); BasicTableHeaderUI ui = (BasicTableHeaderUI)BasicLookAndFeel. getUIOfType(th.getUI(), BasicTableHeaderUI.class); if (ui == null) { return; } String name = getName(); if (TOGGLE_SORT_ORDER == name) { JTable table = th.getTable(); RowSorter sorter = table.getRowSorter(); if (sorter != null) { int columnIndex = ui.getSelectedColumnIndex(); columnIndex = table.convertColumnIndexToModel( columnIndex); sorter.toggleSortOrder(columnIndex); } } else if (SELECT_COLUMN_TO_LEFT == name) { if (th.getComponentOrientation().isLeftToRight()) { ui.selectPreviousColumn(true); } else { ui.selectNextColumn(true); } } else if (SELECT_COLUMN_TO_RIGHT == name) { if (th.getComponentOrientation().isLeftToRight()) { ui.selectNextColumn(true); } else { ui.selectPreviousColumn(true); } } else if (MOVE_COLUMN_LEFT == name) { moveColumn(true, th, ui); } else if (MOVE_COLUMN_RIGHT == name) { moveColumn(false, th, ui); } else if (RESIZE_LEFT == name) { resize(true, th, ui); } else if (RESIZE_RIGHT == name) { resize(false, th, ui); } else if (FOCUS_TABLE == name) { JTable table = th.getTable(); if (table != null) { table.requestFocusInWindow(); } } } private void moveColumn(boolean leftArrow, JTableHeader th, BasicTableHeaderUI ui) { maybeMoveColumn(leftArrow, th, ui, true); } private boolean maybeMoveColumn(boolean leftArrow, JTableHeader th, BasicTableHeaderUI ui, boolean doIt) { int oldIndex = ui.getSelectedColumnIndex(); int newIndex; if (th.getComponentOrientation().isLeftToRight()) { newIndex = leftArrow ? ui.selectPreviousColumn(doIt) : ui.selectNextColumn(doIt); } else { newIndex = leftArrow ? ui.selectNextColumn(doIt) : ui.selectPreviousColumn(doIt); } if (newIndex != oldIndex) { if (doIt) { th.getColumnModel().moveColumn(oldIndex, newIndex); } else { return true; // we'd do the move if asked } } return false; } private void resize(boolean leftArrow, JTableHeader th, BasicTableHeaderUI ui) { int columnIndex = ui.getSelectedColumnIndex(); TableColumn resizingColumn = th.getColumnModel().getColumn(columnIndex); th.setResizingColumn(resizingColumn); int oldWidth = resizingColumn.getWidth(); int newWidth = oldWidth; if (th.getComponentOrientation().isLeftToRight()) { newWidth = newWidth + (leftArrow ? -1 : 1); } else { newWidth = newWidth + (leftArrow ? 1 : -1); } ui.changeColumnWidth(resizingColumn, th, oldWidth, newWidth); } } } // End of Class BasicTableHeaderUI
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import sun.swing.DefaultLookup; import sun.swing.UIAction; import java.awt.*; import java.awt.event.*; import java.beans.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.*; import javax.swing.border.*; import java.util.Arrays; import java.util.ArrayList; /** {@collect.stats} * A default L&F implementation of MenuUI. This implementation * is a "combined" view/controller. * * @author Georges Saab * @author David Karlton * @author Arnaud Weber */ public class BasicMenuUI extends BasicMenuItemUI { protected ChangeListener changeListener; protected MenuListener menuListener; private int lastMnemonic = 0; /** {@collect.stats} Uses as the parent of the windowInputMap when selected. */ private InputMap selectedWindowInputMap; /* diagnostic aids -- should be false for production builds. */ private static final boolean TRACE = false; // trace creates and disposes private static final boolean VERBOSE = false; // show reuse hits/misses private static final boolean DEBUG = false; // show bad params, misc. private static boolean crossMenuMnemonic = true; public static ComponentUI createUI(JComponent x) { return new BasicMenuUI(); } static void loadActionMap(LazyActionMap map) { BasicMenuItemUI.loadActionMap(map); map.put(new Actions(Actions.SELECT, null, true)); } protected void installDefaults() { super.installDefaults(); updateDefaultBackgroundColor(); ((JMenu)menuItem).setDelay(200); crossMenuMnemonic = UIManager.getBoolean("Menu.crossMenuMnemonic"); } protected String getPropertyPrefix() { return "Menu"; } protected void installListeners() { super.installListeners(); if (changeListener == null) changeListener = createChangeListener(menuItem); if (changeListener != null) menuItem.addChangeListener(changeListener); if (menuListener == null) menuListener = createMenuListener(menuItem); if (menuListener != null) ((JMenu)menuItem).addMenuListener(menuListener); } protected void installKeyboardActions() { super.installKeyboardActions(); updateMnemonicBinding(); } void installLazyActionMap() { LazyActionMap.installLazyActionMap(menuItem, BasicMenuUI.class, getPropertyPrefix() + ".actionMap"); } void updateMnemonicBinding() { int mnemonic = menuItem.getModel().getMnemonic(); int[] shortcutKeys = (int[])DefaultLookup.get(menuItem, this, "Menu.shortcutKeys"); if (shortcutKeys == null) { shortcutKeys = new int[] {KeyEvent.ALT_MASK}; } if (mnemonic == lastMnemonic) { return; } InputMap windowInputMap = SwingUtilities.getUIInputMap( menuItem, JComponent.WHEN_IN_FOCUSED_WINDOW); if (lastMnemonic != 0 && windowInputMap != null) { for (int i=0; i<shortcutKeys.length; i++) { windowInputMap.remove(KeyStroke.getKeyStroke (lastMnemonic, shortcutKeys[i], false)); } } if (mnemonic != 0) { if (windowInputMap == null) { windowInputMap = createInputMap(JComponent. WHEN_IN_FOCUSED_WINDOW); SwingUtilities.replaceUIInputMap(menuItem, JComponent. WHEN_IN_FOCUSED_WINDOW, windowInputMap); } for (int i=0; i<shortcutKeys.length; i++) { windowInputMap.put(KeyStroke.getKeyStroke(mnemonic, shortcutKeys[i], false), "selectMenu"); } } lastMnemonic = mnemonic; } protected void uninstallKeyboardActions() { super.uninstallKeyboardActions(); lastMnemonic = 0; } protected MouseInputListener createMouseInputListener(JComponent c) { return getHandler(); } protected MenuListener createMenuListener(JComponent c) { return null; } protected ChangeListener createChangeListener(JComponent c) { return null; } protected PropertyChangeListener createPropertyChangeListener(JComponent c) { return getHandler(); } BasicMenuItemUI.Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } protected void uninstallDefaults() { menuItem.setArmed(false); menuItem.setSelected(false); menuItem.resetKeyboardActions(); super.uninstallDefaults(); } protected void uninstallListeners() { super.uninstallListeners(); if (changeListener != null) menuItem.removeChangeListener(changeListener); if (menuListener != null) ((JMenu)menuItem).removeMenuListener(menuListener); changeListener = null; menuListener = null; handler = null; } protected MenuDragMouseListener createMenuDragMouseListener(JComponent c) { return getHandler(); } protected MenuKeyListener createMenuKeyListener(JComponent c) { return (MenuKeyListener)getHandler(); } public Dimension getMaximumSize(JComponent c) { if (((JMenu)menuItem).isTopLevelMenu() == true) { Dimension d = c.getPreferredSize(); return new Dimension(d.width, Short.MAX_VALUE); } return null; } protected void setupPostTimer(JMenu menu) { Timer timer = new Timer(menu.getDelay(), new Actions( Actions.SELECT, menu,false)); timer.setRepeats(false); timer.start(); } private static void appendPath(MenuElement[] path, MenuElement elem) { MenuElement newPath[] = new MenuElement[path.length+1]; System.arraycopy(path, 0, newPath, 0, path.length); newPath[path.length] = elem; MenuSelectionManager.defaultManager().setSelectedPath(newPath); } private static class Actions extends UIAction { private static final String SELECT = "selectMenu"; // NOTE: This will be null if the action is registered in the // ActionMap. For the timer use it will be non-null. private JMenu menu; private boolean force=false; Actions(String key, JMenu menu, boolean shouldForce) { super(key); this.menu = menu; this.force = shouldForce; } private JMenu getMenu(ActionEvent e) { if (e.getSource() instanceof JMenu) { return (JMenu)e.getSource(); } return menu; } public void actionPerformed(ActionEvent e) { JMenu menu = getMenu(e); if (!crossMenuMnemonic) { JPopupMenu pm = BasicPopupMenuUI.getLastPopup(); if (pm != null && pm != menu.getParent()) { return; } } final MenuSelectionManager defaultManager = MenuSelectionManager.defaultManager(); if(force) { Container cnt = menu.getParent(); if(cnt != null && cnt instanceof JMenuBar) { MenuElement me[]; MenuElement subElements[]; subElements = menu.getPopupMenu().getSubElements(); if(subElements.length > 0) { me = new MenuElement[4]; me[0] = (MenuElement) cnt; me[1] = (MenuElement) menu; me[2] = (MenuElement) menu.getPopupMenu(); me[3] = subElements[0]; } else { me = new MenuElement[3]; me[0] = (MenuElement)cnt; me[1] = menu; me[2] = (MenuElement) menu.getPopupMenu(); } defaultManager.setSelectedPath(me); } } else { MenuElement path[] = defaultManager.getSelectedPath(); if(path.length > 0 && path[path.length-1] == menu) { appendPath(path, menu.getPopupMenu()); } } } public boolean isEnabled(Object c) { if (c instanceof JMenu) { return ((JMenu)c).isEnabled(); } return true; } } /* * Set the background color depending on whether this is a toplevel menu * in a menubar or a submenu of another menu. */ private void updateDefaultBackgroundColor() { if (!UIManager.getBoolean("Menu.useMenuBarBackgroundForTopLevel")) { return; } JMenu menu = (JMenu)menuItem; if (menu.getBackground() instanceof UIResource) { if (menu.isTopLevelMenu()) { menu.setBackground(UIManager.getColor("MenuBar.background")); } else { menu.setBackground(UIManager.getColor(getPropertyPrefix() + ".background")); } } } /** {@collect.stats} * Instantiated and used by a menu item to handle the current menu selection * from mouse events. A MouseInputHandler processes and forwards all mouse events * to a shared instance of the MenuSelectionManager. * <p> * This class is protected so that it can be subclassed by other look and * feels to implement their own mouse handling behavior. All overridden * methods should call the parent methods so that the menu selection * is correct. * * @see javax.swing.MenuSelectionManager * @since 1.4 */ protected class MouseInputHandler implements MouseInputListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void mouseClicked(MouseEvent e) { getHandler().mouseClicked(e); } /** {@collect.stats} * Invoked when the mouse has been clicked on the menu. This * method clears or sets the selection path of the * MenuSelectionManager. * * @param e the mouse event */ public void mousePressed(MouseEvent e) { getHandler().mousePressed(e); } /** {@collect.stats} * Invoked when the mouse has been released on the menu. Delegates the * mouse event to the MenuSelectionManager. * * @param e the mouse event */ public void mouseReleased(MouseEvent e) { getHandler().mouseReleased(e); } /** {@collect.stats} * Invoked when the cursor enters the menu. This method sets the selected * path for the MenuSelectionManager and handles the case * in which a menu item is used to pop up an additional menu, as in a * hierarchical menu system. * * @param e the mouse event; not used */ public void mouseEntered(MouseEvent e) { getHandler().mouseEntered(e); } public void mouseExited(MouseEvent e) { getHandler().mouseExited(e); } /** {@collect.stats} * Invoked when a mouse button is pressed on the menu and then dragged. * Delegates the mouse event to the MenuSelectionManager. * * @param e the mouse event * @see java.awt.event.MouseMotionListener#mouseDragged */ public void mouseDragged(MouseEvent e) { getHandler().mouseDragged(e); } public void mouseMoved(MouseEvent e) { getHandler().mouseMoved(e); } } /** {@collect.stats} * As of Java 2 platform 1.4, this previously undocumented class * is now obsolete. KeyBindings are now managed by the popup menu. */ public class ChangeHandler implements ChangeListener { public JMenu menu; public BasicMenuUI ui; public boolean isSelected = false; public Component wasFocused; public ChangeHandler(JMenu m, BasicMenuUI ui) { menu = m; this.ui = ui; } public void stateChanged(ChangeEvent e) { } } private class Handler extends BasicMenuItemUI.Handler implements MenuKeyListener { // // PropertyChangeListener // public void propertyChange(PropertyChangeEvent e) { if (e.getPropertyName() == AbstractButton. MNEMONIC_CHANGED_PROPERTY) { updateMnemonicBinding(); } else { if (e.getPropertyName().equals("ancestor")) { updateDefaultBackgroundColor(); } super.propertyChange(e); } } // // MouseInputListener // public void mouseClicked(MouseEvent e) { } /** {@collect.stats} * Invoked when the mouse has been clicked on the menu. This * method clears or sets the selection path of the * MenuSelectionManager. * * @param e the mouse event */ public void mousePressed(MouseEvent e) { JMenu menu = (JMenu)menuItem; if (!menu.isEnabled()) return; MenuSelectionManager manager = MenuSelectionManager.defaultManager(); if(menu.isTopLevelMenu()) { if(menu.isSelected() && menu.getPopupMenu().isShowing()) { manager.clearSelectedPath(); } else { Container cnt = menu.getParent(); if(cnt != null && cnt instanceof JMenuBar) { MenuElement me[] = new MenuElement[2]; me[0]=(MenuElement)cnt; me[1]=menu; manager.setSelectedPath(me); } } } MenuElement selectedPath[] = manager.getSelectedPath(); if (selectedPath.length > 0 && selectedPath[selectedPath.length-1] != menu.getPopupMenu()) { if(menu.isTopLevelMenu() || menu.getDelay() == 0) { appendPath(selectedPath, menu.getPopupMenu()); } else { setupPostTimer(menu); } } } /** {@collect.stats} * Invoked when the mouse has been released on the menu. Delegates the * mouse event to the MenuSelectionManager. * * @param e the mouse event */ public void mouseReleased(MouseEvent e) { JMenu menu = (JMenu)menuItem; if (!menu.isEnabled()) return; MenuSelectionManager manager = MenuSelectionManager.defaultManager(); manager.processMouseEvent(e); if (!e.isConsumed()) manager.clearSelectedPath(); } /** {@collect.stats} * Invoked when the cursor enters the menu. This method sets the selected * path for the MenuSelectionManager and handles the case * in which a menu item is used to pop up an additional menu, as in a * hierarchical menu system. * * @param e the mouse event; not used */ public void mouseEntered(MouseEvent e) { JMenu menu = (JMenu)menuItem; // only disable the menu highlighting if it's disabled and the property isn't // true. This allows disabled rollovers to work in WinL&F if (!menu.isEnabled() && !UIManager.getBoolean("MenuItem.disabledAreNavigable")) { return; } MenuSelectionManager manager = MenuSelectionManager.defaultManager(); MenuElement selectedPath[] = manager.getSelectedPath(); if (!menu.isTopLevelMenu()) { if(!(selectedPath.length > 0 && selectedPath[selectedPath.length-1] == menu.getPopupMenu())) { if(menu.getDelay() == 0) { appendPath(getPath(), menu.getPopupMenu()); } else { manager.setSelectedPath(getPath()); setupPostTimer(menu); } } } else { if(selectedPath.length > 0 && selectedPath[0] == menu.getParent()) { MenuElement newPath[] = new MenuElement[3]; // A top level menu's parent is by definition // a JMenuBar newPath[0] = (MenuElement)menu.getParent(); newPath[1] = menu; if (BasicPopupMenuUI.getLastPopup() != null) { newPath[2] = menu.getPopupMenu(); } manager.setSelectedPath(newPath); } } } public void mouseExited(MouseEvent e) { } /** {@collect.stats} * Invoked when a mouse button is pressed on the menu and then dragged. * Delegates the mouse event to the MenuSelectionManager. * * @param e the mouse event * @see java.awt.event.MouseMotionListener#mouseDragged */ public void mouseDragged(MouseEvent e) { JMenu menu = (JMenu)menuItem; if (!menu.isEnabled()) return; MenuSelectionManager.defaultManager().processMouseEvent(e); } public void mouseMoved(MouseEvent e) { } // // MenuDragHandler // public void menuDragMouseEntered(MenuDragMouseEvent e) {} public void menuDragMouseDragged(MenuDragMouseEvent e) { if (menuItem.isEnabled() == false) return; MenuSelectionManager manager = e.getMenuSelectionManager(); MenuElement path[] = e.getPath(); Point p = e.getPoint(); if(p.x >= 0 && p.x < menuItem.getWidth() && p.y >= 0 && p.y < menuItem.getHeight()) { JMenu menu = (JMenu)menuItem; MenuElement selectedPath[] = manager.getSelectedPath(); if(!(selectedPath.length > 0 && selectedPath[selectedPath.length-1] == menu.getPopupMenu())) { if(menu.isTopLevelMenu() || menu.getDelay() == 0 || e.getID() == MouseEvent.MOUSE_DRAGGED) { appendPath(path, menu.getPopupMenu()); } else { manager.setSelectedPath(path); setupPostTimer(menu); } } } else if(e.getID() == MouseEvent.MOUSE_RELEASED) { Component comp = manager.componentForPoint(e.getComponent(), e.getPoint()); if (comp == null) manager.clearSelectedPath(); } } public void menuDragMouseExited(MenuDragMouseEvent e) {} public void menuDragMouseReleased(MenuDragMouseEvent e) {} // // MenuKeyListener // /** {@collect.stats} * Open the Menu */ public void menuKeyTyped(MenuKeyEvent e) { if (!crossMenuMnemonic && BasicPopupMenuUI.getLastPopup() != null) { // when crossMenuMnemonic is not set, we don't open a toplevel // menu if another toplevel menu is already open return; } char key = Character.toLowerCase((char)menuItem.getMnemonic()); MenuElement path[] = e.getPath(); MenuSelectionManager manager = e.getMenuSelectionManager(); if (key == Character.toLowerCase(e.getKeyChar())) { JPopupMenu popupMenu = ((JMenu)menuItem).getPopupMenu(); ArrayList newList = new ArrayList(Arrays.asList(path)); newList.add(popupMenu); MenuElement subs[] = popupMenu.getSubElements(); MenuElement sub = BasicPopupMenuUI.findEnabledChild(subs, -1, true); if(sub != null) { newList.add(sub); } MenuElement newPath[] = new MenuElement[0];; newPath = (MenuElement[]) newList.toArray(newPath); manager.setSelectedPath(newPath); e.consume(); } else if (((JMenu)menuItem).isTopLevelMenu() && BasicPopupMenuUI.getLastPopup() == null) { manager.clearSelectedPath(); } } public void menuKeyPressed(MenuKeyEvent e) {} public void menuKeyReleased(MenuKeyEvent e) {} } }
Java
/* * Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.accessibility.*; import javax.swing.plaf.*; import javax.swing.text.*; import javax.swing.event.*; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import sun.awt.AppContext; import sun.swing.DefaultLookup; import sun.swing.UIAction; /** {@collect.stats} * Basic UI implementation for JComboBox. * <p> * The combo box is a compound component which means that it is an agregate of * many simpler components. This class creates and manages the listeners * on the combo box and the combo box model. These listeners update the user * interface in response to changes in the properties and state of the combo box. * <p> * All event handling is handled by listener classes created with the * <code>createxxxListener()</code> methods and internal classes. * You can change the behavior of this class by overriding the * <code>createxxxListener()</code> methods and supplying your own * event listeners or subclassing from the ones supplied in this class. * <p> * For adding specific actions, * overide <code>installKeyboardActions</code> to add actions in response to * KeyStroke bindings. See the article <a href="http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html">Keyboard Bindings in Swing</a> * at <a href="http://java.sun.com/products/jfc/tsc"><em>The Swing Connection</em></a>. * * @author Arnaud Weber * @author Tom Santos * @author Mark Davidson */ public class BasicComboBoxUI extends ComboBoxUI { protected JComboBox comboBox; /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. */ protected boolean hasFocus = false; // Control the selection behavior of the JComboBox when it is used // in the JTable DefaultCellEditor. private boolean isTableCellEditor = false; private static final String IS_TABLE_CELL_EDITOR = "JComboBox.isTableCellEditor"; // This list is for drawing the current item in the combo box. protected JList listBox; // Used to render the currently selected item in the combo box. // It doesn't have anything to do with the popup's rendering. protected CellRendererPane currentValuePane = new CellRendererPane(); // The implementation of ComboPopup that is used to show the popup. protected ComboPopup popup; // The Component that the ComboBoxEditor uses for editing protected Component editor; // The arrow button that invokes the popup. protected JButton arrowButton; // Listeners that are attached to the JComboBox /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. Override the listener construction method instead. * * @see #createKeyListener */ protected KeyListener keyListener; /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. Override the listener construction method instead. * * @see #createFocusListener */ protected FocusListener focusListener; /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. Override the listener construction method instead. * * @see #createPropertyChangeListener */ protected PropertyChangeListener propertyChangeListener; /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. Override the listener construction method instead. * * @see #createItemListener */ protected ItemListener itemListener; // Listeners that the ComboPopup produces. protected MouseListener popupMouseListener; protected MouseMotionListener popupMouseMotionListener; protected KeyListener popupKeyListener; // This is used for knowing when to cache the minimum preferred size. // If the data in the list changes, the cached value get marked for recalc. // Added to the current JComboBox model /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. Override the listener construction method instead. * * @see #createListDataListener */ protected ListDataListener listDataListener; /** {@collect.stats} * Implements all the Listeners needed by this class, all existing * listeners redirect to it. */ private Handler handler; /** {@collect.stats} * The time factor to treate the series of typed alphanumeric key * as prefix for first letter navigation. */ private long timeFactor = 1000L; /** {@collect.stats} * This is tricky, this variables is needed for DefaultKeySelectionManager * to take into account time factor. */ private long lastTime = 0L; private long time = 0L; /** {@collect.stats} * The default key selection manager */ JComboBox.KeySelectionManager keySelectionManager; // Flag for recalculating the minimum preferred size. protected boolean isMinimumSizeDirty = true; // Cached minimum preferred size. protected Dimension cachedMinimumSize = new Dimension( 0, 0 ); // Flag for calculating the display size private boolean isDisplaySizeDirty = true; // Cached the size that the display needs to render the largest item private Dimension cachedDisplaySize = new Dimension( 0, 0 ); // Key used for lookup of the DefaultListCellRenderer in the AppContext. private static final Object COMBO_UI_LIST_CELL_RENDERER_KEY = new Object(); // DefaultListCellRendererKey static final Object HIDE_POPUP_KEY = new Object(); // HidePopupKey /** {@collect.stats} * Whether or not all cells have the same baseline. */ private boolean sameBaseline; /** {@collect.stats} * Indicates whether or not the combo box button should be square. * If square, then the width and height are equal, and are both set to * the height of the combo (minus appropriate insets). */ private boolean squareButton = true; /** {@collect.stats} * Optional: if specified, these insets act as padding around the cell * renderer when laying out and painting the "selected" item in the * combo box. BasicComboBoxUI uses a single combo box renderer for rendering * both the main combo box item and also all the items in the dropdown * for the combo box. padding allows you to specify addition insets in * addition to those specified by the cell renderer. */ private Insets padding; // Used for calculating the default size. private static ListCellRenderer getDefaultListCellRenderer() { ListCellRenderer renderer = (ListCellRenderer)AppContext. getAppContext().get(COMBO_UI_LIST_CELL_RENDERER_KEY); if (renderer == null) { renderer = new DefaultListCellRenderer(); AppContext.getAppContext().put(COMBO_UI_LIST_CELL_RENDERER_KEY, new DefaultListCellRenderer()); } return renderer; } /** {@collect.stats} * Populates ComboBox's actions. */ static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.HIDE)); map.put(new Actions(Actions.PAGE_DOWN)); map.put(new Actions(Actions.PAGE_UP)); map.put(new Actions(Actions.HOME)); map.put(new Actions(Actions.END)); map.put(new Actions(Actions.DOWN)); map.put(new Actions(Actions.DOWN_2)); map.put(new Actions(Actions.TOGGLE)); map.put(new Actions(Actions.TOGGLE_2)); map.put(new Actions(Actions.UP)); map.put(new Actions(Actions.UP_2)); map.put(new Actions(Actions.ENTER)); } //======================== // begin UI Initialization // public static ComponentUI createUI(JComponent c) { return new BasicComboBoxUI(); } @Override public void installUI( JComponent c ) { isMinimumSizeDirty = true; comboBox = (JComboBox)c; installDefaults(); popup = createPopup(); listBox = popup.getList(); // Is this combo box a cell editor? Boolean inTable = (Boolean)c.getClientProperty(IS_TABLE_CELL_EDITOR ); if (inTable != null) { isTableCellEditor = inTable.equals(Boolean.TRUE) ? true : false; } if ( comboBox.getRenderer() == null || comboBox.getRenderer() instanceof UIResource ) { comboBox.setRenderer( createRenderer() ); } if ( comboBox.getEditor() == null || comboBox.getEditor() instanceof UIResource ) { comboBox.setEditor( createEditor() ); } installListeners(); installComponents(); comboBox.setLayout( createLayoutManager() ); comboBox.setRequestFocusEnabled( true ); installKeyboardActions(); comboBox.putClientProperty("doNotCancelPopup", HIDE_POPUP_KEY); if (keySelectionManager == null || keySelectionManager instanceof UIResource) { keySelectionManager = new DefaultKeySelectionManager(); } comboBox.setKeySelectionManager(keySelectionManager); } @Override public void uninstallUI( JComponent c ) { setPopupVisible( comboBox, false); popup.uninstallingUI(); uninstallKeyboardActions(); comboBox.setLayout( null ); uninstallComponents(); uninstallListeners(); uninstallDefaults(); if ( comboBox.getRenderer() == null || comboBox.getRenderer() instanceof UIResource ) { comboBox.setRenderer( null ); } ComboBoxEditor comboBoxEditor = comboBox.getEditor(); if (comboBoxEditor instanceof UIResource ) { if (comboBoxEditor.getEditorComponent().hasFocus()) { // Leave focus in JComboBox. comboBox.requestFocusInWindow(); } comboBox.setEditor( null ); } if (keySelectionManager instanceof UIResource) { comboBox.setKeySelectionManager(null); } handler = null; keyListener = null; focusListener = null; listDataListener = null; propertyChangeListener = null; popup = null; listBox = null; comboBox = null; } /** {@collect.stats} * Installs the default colors, default font, default renderer, and default * editor into the JComboBox. */ protected void installDefaults() { LookAndFeel.installColorsAndFont( comboBox, "ComboBox.background", "ComboBox.foreground", "ComboBox.font" ); LookAndFeel.installBorder( comboBox, "ComboBox.border" ); LookAndFeel.installProperty( comboBox, "opaque", Boolean.TRUE); Long l = (Long)UIManager.get("ComboBox.timeFactor"); timeFactor = l == null ? 1000L : l.longValue(); //NOTE: this needs to default to true if not specified Boolean b = (Boolean)UIManager.get("ComboBox.squareButton"); squareButton = b == null ? true : b; padding = UIManager.getInsets("ComboBox.padding"); } /** {@collect.stats} * Create and install the listeners for the combo box and its model. * This method is called when the UI is installed. */ protected void installListeners() { if ( (itemListener = createItemListener()) != null) { comboBox.addItemListener( itemListener ); } if ( (propertyChangeListener = createPropertyChangeListener()) != null ) { comboBox.addPropertyChangeListener( propertyChangeListener ); } if ( (keyListener = createKeyListener()) != null ) { comboBox.addKeyListener( keyListener ); } if ( (focusListener = createFocusListener()) != null ) { comboBox.addFocusListener( focusListener ); } if ((popupMouseListener = popup.getMouseListener()) != null) { comboBox.addMouseListener( popupMouseListener ); } if ((popupMouseMotionListener = popup.getMouseMotionListener()) != null) { comboBox.addMouseMotionListener( popupMouseMotionListener ); } if ((popupKeyListener = popup.getKeyListener()) != null) { comboBox.addKeyListener(popupKeyListener); } if ( comboBox.getModel() != null ) { if ( (listDataListener = createListDataListener()) != null ) { comboBox.getModel().addListDataListener( listDataListener ); } } } /** {@collect.stats} * Uninstalls the default colors, default font, default renderer, and default * editor into the JComboBox. */ protected void uninstallDefaults() { LookAndFeel.installColorsAndFont( comboBox, "ComboBox.background", "ComboBox.foreground", "ComboBox.font" ); LookAndFeel.uninstallBorder( comboBox ); } /** {@collect.stats} * Remove the installed listeners from the combo box and its model. * The number and types of listeners removed and in this method should be * the same that was added in <code>installListeners</code> */ protected void uninstallListeners() { if ( keyListener != null ) { comboBox.removeKeyListener( keyListener ); } if ( itemListener != null) { comboBox.removeItemListener( itemListener ); } if ( propertyChangeListener != null ) { comboBox.removePropertyChangeListener( propertyChangeListener ); } if ( focusListener != null) { comboBox.removeFocusListener( focusListener ); } if ( popupMouseListener != null) { comboBox.removeMouseListener( popupMouseListener ); } if ( popupMouseMotionListener != null) { comboBox.removeMouseMotionListener( popupMouseMotionListener ); } if (popupKeyListener != null) { comboBox.removeKeyListener(popupKeyListener); } if ( comboBox.getModel() != null ) { if ( listDataListener != null ) { comboBox.getModel().removeListDataListener( listDataListener ); } } } /** {@collect.stats} * Creates the popup portion of the combo box. * * @return an instance of <code>ComboPopup</code> * @see ComboPopup */ protected ComboPopup createPopup() { return new BasicComboPopup( comboBox ); } /** {@collect.stats} * Creates a <code>KeyListener</code> which will be added to the * combo box. If this method returns null then it will not be added * to the combo box. * * @return an instance <code>KeyListener</code> or null */ protected KeyListener createKeyListener() { return getHandler(); } /** {@collect.stats} * Creates a <code>FocusListener</code> which will be added to the combo box. * If this method returns null then it will not be added to the combo box. * * @return an instance of a <code>FocusListener</code> or null */ protected FocusListener createFocusListener() { return getHandler(); } /** {@collect.stats} * Creates a list data listener which will be added to the * <code>ComboBoxModel</code>. If this method returns null then * it will not be added to the combo box model. * * @return an instance of a <code>ListDataListener</code> or null */ protected ListDataListener createListDataListener() { return getHandler(); } /** {@collect.stats} * Creates an <code>ItemListener</code> which will be added to the * combo box. If this method returns null then it will not * be added to the combo box. * <p> * Subclasses may override this method to return instances of their own * ItemEvent handlers. * * @return an instance of an <code>ItemListener</code> or null */ protected ItemListener createItemListener() { return null; } /** {@collect.stats} * Creates a <code>PropertyChangeListener</code> which will be added to * the combo box. If this method returns null then it will not * be added to the combo box. * * @return an instance of a <code>PropertyChangeListener</code> or null */ protected PropertyChangeListener createPropertyChangeListener() { return getHandler(); } /** {@collect.stats} * Creates a layout manager for managing the components which make up the * combo box. * * @return an instance of a layout manager */ protected LayoutManager createLayoutManager() { return getHandler(); } /** {@collect.stats} * Creates the default renderer that will be used in a non-editiable combo * box. A default renderer will used only if a renderer has not been * explicitly set with <code>setRenderer</code>. * * @return a <code>ListCellRender</code> used for the combo box * @see javax.swing.JComboBox#setRenderer */ protected ListCellRenderer createRenderer() { return new BasicComboBoxRenderer.UIResource(); } /** {@collect.stats} * Creates the default editor that will be used in editable combo boxes. * A default editor will be used only if an editor has not been * explicitly set with <code>setEditor</code>. * * @return a <code>ComboBoxEditor</code> used for the combo box * @see javax.swing.JComboBox#setEditor */ protected ComboBoxEditor createEditor() { return new BasicComboBoxEditor.UIResource(); } /** {@collect.stats} * Returns the shared listener. */ private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } // // end UI Initialization //====================== //====================== // begin Inner classes // /** {@collect.stats} * This listener checks to see if the key event isn't a navigation key. If * it finds a key event that wasn't a navigation key it dispatches it to * JComboBox.selectWithKeyChar() so that it can do type-ahead. * * This public inner class should be treated as protected. * Instantiate it only within subclasses of * <code>BasicComboBoxUI</code>. */ public class KeyHandler extends KeyAdapter { @Override public void keyPressed( KeyEvent e ) { getHandler().keyPressed(e); } } /** {@collect.stats} * This listener hides the popup when the focus is lost. It also repaints * when focus is gained or lost. * * This public inner class should be treated as protected. * Instantiate it only within subclasses of * <code>BasicComboBoxUI</code>. */ public class FocusHandler implements FocusListener { public void focusGained( FocusEvent e ) { getHandler().focusGained(e); } public void focusLost( FocusEvent e ) { getHandler().focusLost(e); } } /** {@collect.stats} * This listener watches for changes in the * <code>ComboBoxModel</code>. * <p> * This public inner class should be treated as protected. * Instantiate it only within subclasses of * <code>BasicComboBoxUI</code>. * * @see #createListDataListener */ public class ListDataHandler implements ListDataListener { public void contentsChanged( ListDataEvent e ) { getHandler().contentsChanged(e); } public void intervalAdded( ListDataEvent e ) { getHandler().intervalAdded(e); } public void intervalRemoved( ListDataEvent e ) { getHandler().intervalRemoved(e); } } /** {@collect.stats} * This listener watches for changes to the selection in the * combo box. * <p> * This public inner class should be treated as protected. * Instantiate it only within subclasses of * <code>BasicComboBoxUI</code>. * * @see #createItemListener */ public class ItemHandler implements ItemListener { // This class used to implement behavior which is now redundant. public void itemStateChanged(ItemEvent e) {} } /** {@collect.stats} * This listener watches for bound properties that have changed in the * combo box. * <p> * Subclasses which wish to listen to combo box property changes should * call the superclass methods to ensure that the combo box ui correctly * handles property changes. * <p> * This public inner class should be treated as protected. * Instantiate it only within subclasses of * <code>BasicComboBoxUI</code>. * * @see #createPropertyChangeListener */ public class PropertyChangeHandler implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent e) { getHandler().propertyChange(e); } } // Syncronizes the ToolTip text for the components within the combo box to be the // same value as the combo box ToolTip text. private void updateToolTipTextForChildren() { Component[] children = comboBox.getComponents(); for ( int i = 0; i < children.length; ++i ) { if ( children[i] instanceof JComponent ) { ((JComponent)children[i]).setToolTipText( comboBox.getToolTipText() ); } } } /** {@collect.stats} * This layout manager handles the 'standard' layout of combo boxes. It puts * the arrow button to the right and the editor to the left. If there is no * editor it still keeps the arrow button to the right. * * This public inner class should be treated as protected. * Instantiate it only within subclasses of * <code>BasicComboBoxUI</code>. */ public class ComboBoxLayoutManager implements LayoutManager { public void addLayoutComponent(String name, Component comp) {} public void removeLayoutComponent(Component comp) {} public Dimension preferredLayoutSize(Container parent) { return getHandler().preferredLayoutSize(parent); } public Dimension minimumLayoutSize(Container parent) { return getHandler().minimumLayoutSize(parent); } public void layoutContainer(Container parent) { getHandler().layoutContainer(parent); } } // // end Inner classes //==================== //=============================== // begin Sub-Component Management // /** {@collect.stats} * Creates and initializes the components which make up the * aggregate combo box. This method is called as part of the UI * installation process. */ protected void installComponents() { arrowButton = createArrowButton(); comboBox.add( arrowButton ); if (arrowButton != null) { configureArrowButton(); } if ( comboBox.isEditable() ) { addEditor(); } comboBox.add( currentValuePane ); } /** {@collect.stats} * The aggregate components which compise the combo box are * unregistered and uninitialized. This method is called as part of the * UI uninstallation process. */ protected void uninstallComponents() { if ( arrowButton != null ) { unconfigureArrowButton(); } if ( editor != null ) { unconfigureEditor(); } comboBox.removeAll(); // Just to be safe. arrowButton = null; } /** {@collect.stats} * This public method is implementation specific and should be private. * do not call or override. To implement a specific editor create a * custom <code>ComboBoxEditor</code> * * @see #createEditor * @see javax.swing.JComboBox#setEditor * @see javax.swing.ComboBoxEditor */ public void addEditor() { removeEditor(); editor = comboBox.getEditor().getEditorComponent(); if ( editor != null ) { configureEditor(); comboBox.add(editor); if(comboBox.isFocusOwner()) { // Switch focus to the editor component editor.requestFocusInWindow(); } } } /** {@collect.stats} * This public method is implementation specific and should be private. * do not call or override. * * @see #addEditor */ public void removeEditor() { if ( editor != null ) { unconfigureEditor(); comboBox.remove( editor ); editor = null; } } /** {@collect.stats} * This protected method is implementation specific and should be private. * do not call or override. * * @see #addEditor */ protected void configureEditor() { // Should be in the same state as the combobox editor.setEnabled(comboBox.isEnabled()); editor.setFocusable(comboBox.isFocusable()); editor.setFont( comboBox.getFont() ); if (focusListener != null) { editor.addFocusListener(focusListener); } editor.addFocusListener( getHandler() ); comboBox.getEditor().addActionListener(getHandler()); if(editor instanceof JComponent) { ((JComponent)editor).putClientProperty("doNotCancelPopup", HIDE_POPUP_KEY); ((JComponent)editor).setInheritsPopupMenu(true); } comboBox.configureEditor(comboBox.getEditor(),comboBox.getSelectedItem()); editor.addPropertyChangeListener(propertyChangeListener); } /** {@collect.stats} * This protected method is implementation specific and should be private. * Do not call or override. * * @see #addEditor */ protected void unconfigureEditor() { if (focusListener != null) { editor.removeFocusListener(focusListener); } editor.removePropertyChangeListener(propertyChangeListener); editor.removeFocusListener(getHandler()); comboBox.getEditor().removeActionListener(getHandler()); } /** {@collect.stats} * This public method is implementation specific and should be private. Do * not call or override. * * @see #createArrowButton */ public void configureArrowButton() { if ( arrowButton != null ) { arrowButton.setEnabled( comboBox.isEnabled() ); arrowButton.setFocusable(comboBox.isFocusable()); arrowButton.setRequestFocusEnabled(false); arrowButton.addMouseListener( popup.getMouseListener() ); arrowButton.addMouseMotionListener( popup.getMouseMotionListener() ); arrowButton.resetKeyboardActions(); arrowButton.putClientProperty("doNotCancelPopup", HIDE_POPUP_KEY); arrowButton.setInheritsPopupMenu(true); } } /** {@collect.stats} * This public method is implementation specific and should be private. Do * not call or override. * * @see #createArrowButton */ public void unconfigureArrowButton() { if ( arrowButton != null ) { arrowButton.removeMouseListener( popup.getMouseListener() ); arrowButton.removeMouseMotionListener( popup.getMouseMotionListener() ); } } /** {@collect.stats} * Creates an button which will be used as the control to show or hide * the popup portion of the combo box. * * @return a button which represents the popup control */ protected JButton createArrowButton() { JButton button = new BasicArrowButton(BasicArrowButton.SOUTH, UIManager.getColor("ComboBox.buttonBackground"), UIManager.getColor("ComboBox.buttonShadow"), UIManager.getColor("ComboBox.buttonDarkShadow"), UIManager.getColor("ComboBox.buttonHighlight")); button.setName("ComboBox.arrowButton"); return button; } // // end Sub-Component Management //=============================== //================================ // begin ComboBoxUI Implementation // /** {@collect.stats} * Tells if the popup is visible or not. */ public boolean isPopupVisible( JComboBox c ) { return popup.isVisible(); } /** {@collect.stats} * Hides the popup. */ public void setPopupVisible( JComboBox c, boolean v ) { if ( v ) { popup.show(); } else { popup.hide(); } } /** {@collect.stats} * Determines if the JComboBox is focus traversable. If the JComboBox is editable * this returns false, otherwise it returns true. */ public boolean isFocusTraversable( JComboBox c ) { return !comboBox.isEditable(); } // // end ComboBoxUI Implementation //============================== //================================= // begin ComponentUI Implementation @Override public void paint( Graphics g, JComponent c ) { hasFocus = comboBox.hasFocus(); if ( !comboBox.isEditable() ) { Rectangle r = rectangleForCurrentValue(); paintCurrentValueBackground(g,r,hasFocus); paintCurrentValue(g,r,hasFocus); } } @Override public Dimension getPreferredSize( JComponent c ) { return getMinimumSize(c); } /** {@collect.stats} * The minumum size is the size of the display area plus insets plus the button. */ @Override public Dimension getMinimumSize( JComponent c ) { if ( !isMinimumSizeDirty ) { return new Dimension(cachedMinimumSize); } Dimension size = getDisplaySize(); Insets insets = getInsets(); //calculate the width and height of the button int buttonHeight = size.height; int buttonWidth = squareButton ? buttonHeight : arrowButton.getPreferredSize().width; //adjust the size based on the button width size.height += insets.top + insets.bottom; size.width += insets.left + insets.right + buttonWidth; cachedMinimumSize.setSize( size.width, size.height ); isMinimumSizeDirty = false; return new Dimension(size); } @Override public Dimension getMaximumSize( JComponent c ) { return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE); } /** {@collect.stats} * Returns the baseline. * * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ @Override public int getBaseline(JComponent c, int width, int height) { super.getBaseline(c, width, height); int baseline = -1; // force sameBaseline to be updated. getDisplaySize(); if (sameBaseline) { Insets insets = c.getInsets(); height = height - insets.top - insets.bottom; if (!comboBox.isEditable()) { ListCellRenderer renderer = comboBox.getRenderer(); if (renderer == null) { renderer = new DefaultListCellRenderer(); } Object value = null; Object prototypeValue = comboBox.getPrototypeDisplayValue(); if (prototypeValue != null) { value = prototypeValue; } else if (comboBox.getModel().getSize() > 0) { // Note, we're assuming the baseline is the same for all // cells, if not, this needs to loop through all. value = comboBox.getModel().getElementAt(0); } if (value == null) { value = " "; } else if (value instanceof String && "".equals(value)) { value = " "; } Component component = renderer. getListCellRendererComponent(listBox, value, -1, false, false); if (component instanceof JComponent) { component.setFont(comboBox.getFont()); } baseline = component.getBaseline(width, height); } else { baseline = editor.getBaseline(width, height); } if (baseline > 0) { baseline += insets.top; } } return baseline; } /** {@collect.stats} * Returns an enum indicating how the baseline of the component * changes as the size changes. * * @throws NullPointerException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ @Override public Component.BaselineResizeBehavior getBaselineResizeBehavior( JComponent c) { super.getBaselineResizeBehavior(c); // Force sameBaseline to be updated. getDisplaySize(); if (comboBox.isEditable()) { return editor.getBaselineResizeBehavior(); } else if (sameBaseline) { ListCellRenderer renderer = comboBox.getRenderer(); if (renderer == null) { renderer = new DefaultListCellRenderer(); } Object value = null; Object prototypeValue = comboBox.getPrototypeDisplayValue(); if (prototypeValue != null) { value = prototypeValue; } else if (comboBox.getModel().getSize() > 0) { // Note, we're assuming the baseline is the same for all // cells, if not, this needs to loop through all. value = comboBox.getModel().getElementAt(0); } if (value != null) { Component component = renderer. getListCellRendererComponent(listBox, value, -1, false, false); return component.getBaselineResizeBehavior(); } } return Component.BaselineResizeBehavior.OTHER; } // This is currently hacky... @Override public int getAccessibleChildrenCount(JComponent c) { if ( comboBox.isEditable() ) { return 2; } else { return 1; } } // This is currently hacky... @Override public Accessible getAccessibleChild(JComponent c, int i) { // 0 = the popup // 1 = the editor switch ( i ) { case 0: if ( popup instanceof Accessible ) { AccessibleContext ac = ((Accessible) popup).getAccessibleContext(); ac.setAccessibleParent(comboBox); return(Accessible) popup; } break; case 1: if ( comboBox.isEditable() && (editor instanceof Accessible) ) { AccessibleContext ac = ((Accessible) editor).getAccessibleContext(); ac.setAccessibleParent(comboBox); return(Accessible) editor; } break; } return null; } // // end ComponentUI Implementation //=============================== //====================== // begin Utility Methods // /** {@collect.stats} * Returns whether or not the supplied keyCode maps to a key that is used for * navigation. This is used for optimizing key input by only passing non- * navigation keys to the type-ahead mechanism. Subclasses should override this * if they change the navigation keys. */ protected boolean isNavigationKey( int keyCode ) { return keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_KP_UP || keyCode == KeyEvent.VK_KP_DOWN; } private boolean isNavigationKey(int keyCode, int modifiers) { InputMap inputMap = comboBox.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); KeyStroke key = KeyStroke.getKeyStroke(keyCode, modifiers); if (inputMap != null && inputMap.get(key) != null) { return true; } return false; } /** {@collect.stats} * Selects the next item in the list. It won't change the selection if the * currently selected item is already the last item. */ protected void selectNextPossibleValue() { int si; if ( comboBox.isPopupVisible() ) { si = listBox.getSelectedIndex(); } else { si = comboBox.getSelectedIndex(); } if ( si < comboBox.getModel().getSize() - 1 ) { listBox.setSelectedIndex( si + 1 ); listBox.ensureIndexIsVisible( si + 1 ); if ( !isTableCellEditor ) { comboBox.setSelectedIndex(si+1); } comboBox.repaint(); } } /** {@collect.stats} * Selects the previous item in the list. It won't change the selection if the * currently selected item is already the first item. */ protected void selectPreviousPossibleValue() { int si; if ( comboBox.isPopupVisible() ) { si = listBox.getSelectedIndex(); } else { si = comboBox.getSelectedIndex(); } if ( si > 0 ) { listBox.setSelectedIndex( si - 1 ); listBox.ensureIndexIsVisible( si - 1 ); if ( !isTableCellEditor ) { comboBox.setSelectedIndex(si-1); } comboBox.repaint(); } } /** {@collect.stats} * Hides the popup if it is showing and shows the popup if it is hidden. */ protected void toggleOpenClose() { setPopupVisible(comboBox, !isPopupVisible(comboBox)); } /** {@collect.stats} * Returns the area that is reserved for drawing the currently selected item. */ protected Rectangle rectangleForCurrentValue() { int width = comboBox.getWidth(); int height = comboBox.getHeight(); Insets insets = getInsets(); int buttonSize = height - (insets.top + insets.bottom); if ( arrowButton != null ) { buttonSize = arrowButton.getWidth(); } if(BasicGraphicsUtils.isLeftToRight(comboBox)) { return new Rectangle(insets.left, insets.top, width - (insets.left + insets.right + buttonSize), height - (insets.top + insets.bottom)); } else { return new Rectangle(insets.left + buttonSize, insets.top, width - (insets.left + insets.right + buttonSize), height - (insets.top + insets.bottom)); } } /** {@collect.stats} * Gets the insets from the JComboBox. */ protected Insets getInsets() { return comboBox.getInsets(); } // // end Utility Methods //==================== //=============================== // begin Painting Utility Methods // /** {@collect.stats} * Paints the currently selected item. */ public void paintCurrentValue(Graphics g,Rectangle bounds,boolean hasFocus) { ListCellRenderer renderer = comboBox.getRenderer(); Component c; if ( hasFocus && !isPopupVisible(comboBox) ) { c = renderer.getListCellRendererComponent( listBox, comboBox.getSelectedItem(), -1, true, false ); } else { c = renderer.getListCellRendererComponent( listBox, comboBox.getSelectedItem(), -1, false, false ); c.setBackground(UIManager.getColor("ComboBox.background")); } c.setFont(comboBox.getFont()); if ( hasFocus && !isPopupVisible(comboBox) ) { c.setForeground(listBox.getSelectionForeground()); c.setBackground(listBox.getSelectionBackground()); } else { if ( comboBox.isEnabled() ) { c.setForeground(comboBox.getForeground()); c.setBackground(comboBox.getBackground()); } else { c.setForeground(DefaultLookup.getColor( comboBox, this, "ComboBox.disabledForeground", null)); c.setBackground(DefaultLookup.getColor( comboBox, this, "ComboBox.disabledBackground", null)); } } // Fix for 4238829: should lay out the JPanel. boolean shouldValidate = false; if (c instanceof JPanel) { shouldValidate = true; } int x = bounds.x, y = bounds.y, w = bounds.width, h = bounds.height; if (padding != null) { x = bounds.x + padding.left; y = bounds.y + padding.top; w = bounds.width - (padding.left + padding.right); h = bounds.height - (padding.top + padding.bottom); } currentValuePane.paintComponent(g,c,comboBox,x,y,w,h,shouldValidate); } /** {@collect.stats} * Paints the background of the currently selected item. */ public void paintCurrentValueBackground(Graphics g,Rectangle bounds,boolean hasFocus) { Color t = g.getColor(); if ( comboBox.isEnabled() ) g.setColor(DefaultLookup.getColor(comboBox, this, "ComboBox.background", null)); else g.setColor(DefaultLookup.getColor(comboBox, this, "ComboBox.disabledBackground", null)); g.fillRect(bounds.x,bounds.y,bounds.width,bounds.height); g.setColor(t); } /** {@collect.stats} * Repaint the currently selected item. */ void repaintCurrentValue() { Rectangle r = rectangleForCurrentValue(); comboBox.repaint(r.x,r.y,r.width,r.height); } // // end Painting Utility Methods //============================= //=============================== // begin Size Utility Methods // /** {@collect.stats} * Return the default size of an empty display area of the combo box using * the current renderer and font. * * @return the size of an empty display area * @see #getDisplaySize */ protected Dimension getDefaultSize() { // Calculates the height and width using the default text renderer Dimension d = getSizeForComponent(getDefaultListCellRenderer().getListCellRendererComponent(listBox, " ", -1, false, false)); return new Dimension(d.width, d.height); } /** {@collect.stats} * Returns the calculated size of the display area. The display area is the * portion of the combo box in which the selected item is displayed. This * method will use the prototype display value if it has been set. * <p> * For combo boxes with a non trivial number of items, it is recommended to * use a prototype display value to significantly speed up the display * size calculation. * * @return the size of the display area calculated from the combo box items * @see javax.swing.JComboBox#setPrototypeDisplayValue */ protected Dimension getDisplaySize() { if (!isDisplaySizeDirty) { return new Dimension(cachedDisplaySize); } Dimension result = new Dimension(); ListCellRenderer renderer = comboBox.getRenderer(); if (renderer == null) { renderer = new DefaultListCellRenderer(); } sameBaseline = true; Object prototypeValue = comboBox.getPrototypeDisplayValue(); if (prototypeValue != null) { // Calculates the dimension based on the prototype value result = getSizeForComponent(renderer.getListCellRendererComponent(listBox, prototypeValue, -1, false, false)); } else { // Calculate the dimension by iterating over all the elements in the combo // box list. ComboBoxModel model = comboBox.getModel(); int modelSize = model.getSize(); int baseline = -1; Dimension d; Component cpn; if (modelSize > 0 ) { for (int i = 0; i < modelSize ; i++ ) { // Calculates the maximum height and width based on the largest // element Object value = model.getElementAt(i); Component c = renderer.getListCellRendererComponent( listBox, value, -1, false, false); d = getSizeForComponent(c); if (sameBaseline && value != null && (!(value instanceof String) || !"".equals(value))) { int newBaseline = c.getBaseline(d.width, d.height); if (newBaseline == -1) { sameBaseline = false; } else if (baseline == -1) { baseline = newBaseline; } else if (baseline != newBaseline) { sameBaseline = false; } } result.width = Math.max(result.width,d.width); result.height = Math.max(result.height,d.height); } } else { result = getDefaultSize(); if (comboBox.isEditable()) { result.width = 100; } } } if ( comboBox.isEditable() ) { Dimension d = editor.getPreferredSize(); result.width = Math.max(result.width,d.width); result.height = Math.max(result.height,d.height); } // calculate in the padding if (padding != null) { result.width += padding.left + padding.right; result.height += padding.top + padding.bottom; } // Set the cached value cachedDisplaySize.setSize(result.width, result.height); isDisplaySizeDirty = false; return result; } /** {@collect.stats} * This has been refactored out in hopes that it may be investigated and * simplified for the next major release. adding/removing * the component to the currentValuePane and changing the font may be * redundant operations. */ private Dimension getSizeForComponent(Component comp) { currentValuePane.add(comp); comp.setFont(comboBox.getFont()); Dimension d = comp.getPreferredSize(); currentValuePane.remove(comp); return d; } // // end Size Utility Methods //============================= //================================= // begin Keyboard Action Management // /** {@collect.stats} * Adds keyboard actions to the JComboBox. Actions on enter and esc are already * supplied. Add more actions as you need them. */ protected void installKeyboardActions() { InputMap km = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); SwingUtilities.replaceUIInputMap(comboBox, JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, km); LazyActionMap.installLazyActionMap(comboBox, BasicComboBoxUI.class, "ComboBox.actionMap"); } InputMap getInputMap(int condition) { if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) { return (InputMap)DefaultLookup.get(comboBox, this, "ComboBox.ancestorInputMap"); } return null; } boolean isTableCellEditor() { return isTableCellEditor; } /** {@collect.stats} * Removes the focus InputMap and ActionMap. */ protected void uninstallKeyboardActions() { SwingUtilities.replaceUIInputMap(comboBox, JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null); SwingUtilities.replaceUIActionMap(comboBox, null); } // // Actions // private static class Actions extends UIAction { private static final String HIDE = "hidePopup"; private static final String DOWN = "selectNext"; private static final String DOWN_2 = "selectNext2"; private static final String TOGGLE = "togglePopup"; private static final String TOGGLE_2 = "spacePopup"; private static final String UP = "selectPrevious"; private static final String UP_2 = "selectPrevious2"; private static final String ENTER = "enterPressed"; private static final String PAGE_DOWN = "pageDownPassThrough"; private static final String PAGE_UP = "pageUpPassThrough"; private static final String HOME = "homePassThrough"; private static final String END = "endPassThrough"; Actions(String name) { super(name); } public void actionPerformed( ActionEvent e ) { String key = getName(); JComboBox comboBox = (JComboBox)e.getSource(); BasicComboBoxUI ui = (BasicComboBoxUI)BasicLookAndFeel.getUIOfType( comboBox.getUI(), BasicComboBoxUI.class); if (key == HIDE) { comboBox.firePopupMenuCanceled(); comboBox.setPopupVisible(false); } else if (key == PAGE_DOWN || key == PAGE_UP || key == HOME || key == END) { int index = getNextIndex(comboBox, key); if (index >= 0 && index < comboBox.getItemCount()) { comboBox.setSelectedIndex(index); } } else if (key == DOWN) { if (comboBox.isShowing() ) { if ( comboBox.isPopupVisible() ) { if (ui != null) { ui.selectNextPossibleValue(); } } else { comboBox.setPopupVisible(true); } } } else if (key == DOWN_2) { // Special case in which pressing the arrow keys will not // make the popup appear - except for editable combo boxes // and combo boxes inside a table. if (comboBox.isShowing() ) { if ( (comboBox.isEditable() || (ui != null && ui.isTableCellEditor())) && !comboBox.isPopupVisible() ) { comboBox.setPopupVisible(true); } else { if (ui != null) { ui.selectNextPossibleValue(); } } } } else if (key == TOGGLE || key == TOGGLE_2) { if (ui != null && (key == TOGGLE || !comboBox.isEditable())) { if ( ui.isTableCellEditor() ) { // Forces the selection of the list item if the // combo box is in a JTable. comboBox.setSelectedIndex(ui.popup.getList(). getSelectedIndex()); } else { comboBox.setPopupVisible(!comboBox.isPopupVisible()); } } } else if (key == UP) { if (ui != null) { if (ui.isPopupVisible(comboBox)) { ui.selectPreviousPossibleValue(); } else if (DefaultLookup.getBoolean(comboBox, ui, "ComboBox.showPopupOnNavigation", false)) { ui.setPopupVisible(comboBox, true); } } } else if (key == UP_2) { // Special case in which pressing the arrow keys will not // make the popup appear - except for editable combo boxes. if (comboBox.isShowing() && ui != null) { if ( comboBox.isEditable() && !comboBox.isPopupVisible()) { comboBox.setPopupVisible(true); } else { ui.selectPreviousPossibleValue(); } } } else if (key == ENTER) { if (comboBox.isPopupVisible()) { // Forces the selection of the list item boolean isEnterSelectablePopup = UIManager.getBoolean("ComboBox.isEnterSelectablePopup"); if (!comboBox.isEditable() || isEnterSelectablePopup || ui.isTableCellEditor) { Object listItem = ui.popup.getList().getSelectedValue(); if (listItem != null) { comboBox.getModel().setSelectedItem(listItem); // Ensure that JComboBox.actionPerformed() // doesn't set editor value as selected item comboBox.getEditor().setItem(listItem); } } comboBox.setPopupVisible(false); } else { // Call the default button binding. // This is a pretty messy way of passing an event through // to the root pane. JRootPane root = SwingUtilities.getRootPane(comboBox); if (root != null) { InputMap im = root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); ActionMap am = root.getActionMap(); if (im != null && am != null) { Object obj = im.get(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0)); if (obj != null) { Action action = am.get(obj); if (action != null) { action.actionPerformed(new ActionEvent( root, e.getID(), e.getActionCommand(), e.getWhen(), e.getModifiers())); } } } } } } } private int getNextIndex(JComboBox comboBox, String key) { if (key == PAGE_UP) { int listHeight = comboBox.getMaximumRowCount(); int index = comboBox.getSelectedIndex() - listHeight; return (index < 0 ? 0: index); } else if (key == PAGE_DOWN) { int listHeight = comboBox.getMaximumRowCount(); int index = comboBox.getSelectedIndex() + listHeight; int max = comboBox.getItemCount(); return (index < max ? index: max-1); } else if (key == HOME) { return 0; } else if (key == END) { return comboBox.getItemCount() - 1; } return comboBox.getSelectedIndex(); } public boolean isEnabled(Object c) { if (getName() == HIDE) { return (c != null && ((JComboBox)c).isPopupVisible()); } return true; } } // // end Keyboard Action Management //=============================== // // Shared Handler, implements all listeners // private class Handler implements ActionListener, FocusListener, KeyListener, LayoutManager, ListDataListener, PropertyChangeListener { // // PropertyChangeListener // public void propertyChange(PropertyChangeEvent e) { String propertyName = e.getPropertyName(); if (e.getSource() == editor){ // If the border of the editor changes then this can effect // the size of the editor which can cause the combo's size to // become invalid so we need to clear size caches if ("border".equals(propertyName)){ isMinimumSizeDirty = true; isDisplaySizeDirty = true; comboBox.revalidate(); } } else { JComboBox comboBox = (JComboBox)e.getSource(); if ( propertyName == "model" ) { ComboBoxModel newModel = (ComboBoxModel)e.getNewValue(); ComboBoxModel oldModel = (ComboBoxModel)e.getOldValue(); if ( oldModel != null && listDataListener != null ) { oldModel.removeListDataListener( listDataListener ); } if ( newModel != null && listDataListener != null ) { newModel.addListDataListener( listDataListener ); } if ( editor != null ) { comboBox.configureEditor( comboBox.getEditor(), comboBox.getSelectedItem() ); } isMinimumSizeDirty = true; isDisplaySizeDirty = true; comboBox.revalidate(); comboBox.repaint(); } else if ( propertyName == "editor" && comboBox.isEditable() ) { addEditor(); comboBox.revalidate(); } else if ( propertyName == "editable" ) { if ( comboBox.isEditable() ) { comboBox.setRequestFocusEnabled( false ); addEditor(); } else { comboBox.setRequestFocusEnabled( true ); removeEditor(); } updateToolTipTextForChildren(); comboBox.revalidate(); } else if ( propertyName == "enabled" ) { boolean enabled = comboBox.isEnabled(); if ( editor != null ) editor.setEnabled(enabled); if ( arrowButton != null ) arrowButton.setEnabled(enabled); comboBox.repaint(); } else if ( propertyName == "focusable" ) { boolean focusable = comboBox.isFocusable(); if ( editor != null ) editor.setFocusable(focusable); if ( arrowButton != null ) arrowButton.setFocusable(focusable); comboBox.repaint(); } else if ( propertyName == "maximumRowCount" ) { if ( isPopupVisible( comboBox ) ) { setPopupVisible(comboBox, false); setPopupVisible(comboBox, true); } } else if ( propertyName == "font" ) { listBox.setFont( comboBox.getFont() ); if ( editor != null ) { editor.setFont( comboBox.getFont() ); } isMinimumSizeDirty = true; comboBox.validate(); } else if ( propertyName == JComponent.TOOL_TIP_TEXT_KEY ) { updateToolTipTextForChildren(); } else if ( propertyName == BasicComboBoxUI.IS_TABLE_CELL_EDITOR ) { Boolean inTable = (Boolean)e.getNewValue(); isTableCellEditor = inTable.equals(Boolean.TRUE) ? true : false; } else if (propertyName == "prototypeDisplayValue") { isMinimumSizeDirty = true; isDisplaySizeDirty = true; comboBox.revalidate(); } else if (propertyName == "renderer") { isMinimumSizeDirty = true; isDisplaySizeDirty = true; comboBox.revalidate(); } } } // // KeyListener // // This listener checks to see if the key event isn't a navigation // key. If it finds a key event that wasn't a navigation key it // dispatches it to JComboBox.selectWithKeyChar() so that it can do // type-ahead. public void keyPressed( KeyEvent e ) { if ( isNavigationKey(e.getKeyCode(), e.getModifiers()) ) { lastTime = 0L; } else if ( comboBox.isEnabled() && comboBox.getModel().getSize()!=0 && isTypeAheadKey( e ) && e.getKeyChar() != KeyEvent.CHAR_UNDEFINED) { time = e.getWhen(); if ( comboBox.selectWithKeyChar(e.getKeyChar()) ) { e.consume(); } } } public void keyTyped(KeyEvent e) { } public void keyReleased(KeyEvent e) { } private boolean isTypeAheadKey( KeyEvent e ) { return !e.isAltDown() && !e.isControlDown() && !e.isMetaDown(); } // // FocusListener // // NOTE: The class is added to both the Editor and ComboBox. // The combo box listener hides the popup when the focus is lost. // It also repaints when focus is gained or lost. public void focusGained( FocusEvent e ) { ComboBoxEditor comboBoxEditor = comboBox.getEditor(); if ( (comboBoxEditor != null) && (e.getSource() == comboBoxEditor.getEditorComponent()) ) { return; } hasFocus = true; comboBox.repaint(); if (comboBox.isEditable() && editor != null) { editor.requestFocus(); } } public void focusLost( FocusEvent e ) { ComboBoxEditor editor = comboBox.getEditor(); if ( (editor != null) && (e.getSource() == editor.getEditorComponent()) ) { Object item = editor.getItem(); Object selectedItem = comboBox.getSelectedItem(); if (!e.isTemporary() && item != null && !item.equals((selectedItem == null) ? "" : selectedItem )) { comboBox.actionPerformed (new ActionEvent(editor, 0, "", EventQueue.getMostRecentEventTime(), 0)); } } hasFocus = false; if (!e.isTemporary()) { setPopupVisible(comboBox, false); } comboBox.repaint(); } // // ListDataListener // // This listener watches for changes in the ComboBoxModel public void contentsChanged( ListDataEvent e ) { if ( !(e.getIndex0() == -1 && e.getIndex1() == -1) ) { isMinimumSizeDirty = true; comboBox.revalidate(); } // set the editor with the selected item since this // is the event handler for a selected item change. if (comboBox.isEditable() && editor != null) { comboBox.configureEditor( comboBox.getEditor(), comboBox.getSelectedItem() ); } isDisplaySizeDirty = true; comboBox.repaint(); } public void intervalAdded( ListDataEvent e ) { contentsChanged( e ); } public void intervalRemoved( ListDataEvent e ) { contentsChanged( e ); } // // LayoutManager // // This layout manager handles the 'standard' layout of combo boxes. // It puts the arrow button to the right and the editor to the left. // If there is no editor it still keeps the arrow button to the right. public void addLayoutComponent(String name, Component comp) {} public void removeLayoutComponent(Component comp) {} public Dimension preferredLayoutSize(Container parent) { return parent.getPreferredSize(); } public Dimension minimumLayoutSize(Container parent) { return parent.getMinimumSize(); } public void layoutContainer(Container parent) { JComboBox cb = (JComboBox)parent; int width = cb.getWidth(); int height = cb.getHeight(); Insets insets = getInsets(); int buttonHeight = height - (insets.top + insets.bottom); int buttonWidth = buttonHeight; if (arrowButton != null) { Insets arrowInsets = arrowButton.getInsets(); buttonWidth = squareButton ? buttonHeight : arrowButton.getPreferredSize().width + arrowInsets.left + arrowInsets.right; } Rectangle cvb; if (arrowButton != null) { if (BasicGraphicsUtils.isLeftToRight(cb)) { arrowButton.setBounds(width - (insets.right + buttonWidth), insets.top, buttonWidth, buttonHeight); } else { arrowButton.setBounds(insets.left, insets.top, buttonWidth, buttonHeight); } } if ( editor != null ) { cvb = rectangleForCurrentValue(); editor.setBounds(cvb); } } // // ActionListener // // Fix for 4515752: Forward the Enter pressed on the // editable combo box to the default button // Note: This could depend on event ordering. The first ActionEvent // from the editor may be handled by the JComboBox in which case, the // enterPressed action will always be invoked. public void actionPerformed(ActionEvent evt) { Object item = comboBox.getEditor().getItem(); if (item != null) { if(!comboBox.isPopupVisible() && !item.equals(comboBox.getSelectedItem())) { comboBox.setSelectedItem(comboBox.getEditor().getItem()); } ActionMap am = comboBox.getActionMap(); if (am != null) { Action action = am.get("enterPressed"); if (action != null) { action.actionPerformed(new ActionEvent(comboBox, evt.getID(), evt.getActionCommand(), evt.getModifiers())); } } } } } class DefaultKeySelectionManager implements JComboBox.KeySelectionManager, UIResource { private String prefix = ""; private String typedString = ""; public int selectionForKey(char aKey,ComboBoxModel aModel) { if (lastTime == 0L) { prefix = ""; typedString = ""; } boolean startingFromSelection = true; int startIndex = comboBox.getSelectedIndex(); if (time - lastTime < timeFactor) { typedString += aKey; if((prefix.length() == 1) && (aKey == prefix.charAt(0))) { // Subsequent same key presses move the keyboard focus to the next // object that starts with the same letter. startIndex++; } else { prefix = typedString; } } else { startIndex++; typedString = "" + aKey; prefix = typedString; } lastTime = time; if (startIndex < 0 || startIndex >= aModel.getSize()) { startingFromSelection = false; startIndex = 0; } int index = listBox.getNextMatch(prefix, startIndex, Position.Bias.Forward); if (index < 0 && startingFromSelection) { // wrap index = listBox.getNextMatch(prefix, 0, Position.Bias.Forward); } return index; } } }
Java
/* * Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import javax.swing.plaf.*; import javax.swing.text.View; import sun.swing.*; /** {@collect.stats} * BasicMenuItem implementation * * @author Georges Saab * @author David Karlton * @author Arnaud Weber * @author Fredrik Lagerblad */ public class BasicMenuItemUI extends MenuItemUI { protected JMenuItem menuItem = null; protected Color selectionBackground; protected Color selectionForeground; protected Color disabledForeground; protected Color acceleratorForeground; protected Color acceleratorSelectionForeground; private String acceleratorDelimiter; protected int defaultTextIconGap; protected Font acceleratorFont; protected MouseInputListener mouseInputListener; protected MenuDragMouseListener menuDragMouseListener; protected MenuKeyListener menuKeyListener; /** {@collect.stats} * <code>PropertyChangeListener</code> returned from * <code>createPropertyChangeListener</code>. You should not * need to access this field, rather if you want to customize the * <code>PropertyChangeListener</code> override * <code>createPropertyChangeListener</code>. * * @since 1.6 * @see #createPropertyChangeListener */ protected PropertyChangeListener propertyChangeListener; // BasicMenuUI also uses this. Handler handler; protected Icon arrowIcon = null; protected Icon checkIcon = null; protected boolean oldBorderPainted; /* diagnostic aids -- should be false for production builds. */ private static final boolean TRACE = false; // trace creates and disposes private static final boolean VERBOSE = false; // show reuse hits/misses private static final boolean DEBUG = false; // show bad params, misc. static void loadActionMap(LazyActionMap map) { // NOTE: BasicMenuUI also calls into this method. map.put(new Actions(Actions.CLICK)); BasicLookAndFeel.installAudioActionMap(map); } public static ComponentUI createUI(JComponent c) { return new BasicMenuItemUI(); } public void installUI(JComponent c) { menuItem = (JMenuItem) c; installDefaults(); installComponents(menuItem); installListeners(); installKeyboardActions(); } protected void installDefaults() { String prefix = getPropertyPrefix(); acceleratorFont = UIManager.getFont("MenuItem.acceleratorFont"); // use default if missing so that BasicMenuItemUI can be used in other // LAFs like Nimbus if (acceleratorFont == null) { acceleratorFont = UIManager.getFont("MenuItem.font"); } Object opaque = UIManager.get(getPropertyPrefix() + ".opaque"); if (opaque != null) { LookAndFeel.installProperty(menuItem, "opaque", opaque); } else { LookAndFeel.installProperty(menuItem, "opaque", Boolean.TRUE); } if(menuItem.getMargin() == null || (menuItem.getMargin() instanceof UIResource)) { menuItem.setMargin(UIManager.getInsets(prefix + ".margin")); } LookAndFeel.installProperty(menuItem, "iconTextGap", new Integer(4)); defaultTextIconGap = menuItem.getIconTextGap(); LookAndFeel.installBorder(menuItem, prefix + ".border"); oldBorderPainted = menuItem.isBorderPainted(); LookAndFeel.installProperty(menuItem, "borderPainted", UIManager.getBoolean(prefix + ".borderPainted")); LookAndFeel.installColorsAndFont(menuItem, prefix + ".background", prefix + ".foreground", prefix + ".font"); // MenuItem specific defaults if (selectionBackground == null || selectionBackground instanceof UIResource) { selectionBackground = UIManager.getColor(prefix + ".selectionBackground"); } if (selectionForeground == null || selectionForeground instanceof UIResource) { selectionForeground = UIManager.getColor(prefix + ".selectionForeground"); } if (disabledForeground == null || disabledForeground instanceof UIResource) { disabledForeground = UIManager.getColor(prefix + ".disabledForeground"); } if (acceleratorForeground == null || acceleratorForeground instanceof UIResource) { acceleratorForeground = UIManager.getColor(prefix + ".acceleratorForeground"); } if (acceleratorSelectionForeground == null || acceleratorSelectionForeground instanceof UIResource) { acceleratorSelectionForeground = UIManager.getColor(prefix + ".acceleratorSelectionForeground"); } // Get accelerator delimiter acceleratorDelimiter = UIManager.getString("MenuItem.acceleratorDelimiter"); if (acceleratorDelimiter == null) { acceleratorDelimiter = "+"; } // Icons if (arrowIcon == null || arrowIcon instanceof UIResource) { arrowIcon = UIManager.getIcon(prefix + ".arrowIcon"); } if (checkIcon == null || checkIcon instanceof UIResource) { checkIcon = UIManager.getIcon(prefix + ".checkIcon"); //In case of column layout, .checkIconFactory is defined for this UI, //the icon is compatible with it and useCheckAndArrow() is true, //then the icon is handled by the checkIcon. boolean isColumnLayout = MenuItemLayoutHelper.isColumnLayout( BasicGraphicsUtils.isLeftToRight(menuItem), menuItem); if (isColumnLayout) { MenuItemCheckIconFactory iconFactory = (MenuItemCheckIconFactory) UIManager.get(prefix + ".checkIconFactory"); if (iconFactory != null && MenuItemLayoutHelper.useCheckAndArrow(menuItem) && iconFactory.isCompatible(checkIcon, prefix)) { checkIcon = iconFactory.getIcon(menuItem); } } } } /** {@collect.stats} * @since 1.3 */ protected void installComponents(JMenuItem menuItem){ BasicHTML.updateRenderer(menuItem, menuItem.getText()); } protected String getPropertyPrefix() { return "MenuItem"; } protected void installListeners() { if ((mouseInputListener = createMouseInputListener(menuItem)) != null) { menuItem.addMouseListener(mouseInputListener); menuItem.addMouseMotionListener(mouseInputListener); } if ((menuDragMouseListener = createMenuDragMouseListener(menuItem)) != null) { menuItem.addMenuDragMouseListener(menuDragMouseListener); } if ((menuKeyListener = createMenuKeyListener(menuItem)) != null) { menuItem.addMenuKeyListener(menuKeyListener); } if ((propertyChangeListener = createPropertyChangeListener(menuItem)) != null) { menuItem.addPropertyChangeListener(propertyChangeListener); } } protected void installKeyboardActions() { installLazyActionMap(); updateAcceleratorBinding(); } void installLazyActionMap() { LazyActionMap.installLazyActionMap(menuItem, BasicMenuItemUI.class, getPropertyPrefix() + ".actionMap"); } public void uninstallUI(JComponent c) { menuItem = (JMenuItem)c; uninstallDefaults(); uninstallComponents(menuItem); uninstallListeners(); uninstallKeyboardActions(); MenuItemLayoutHelper.clearUsedParentClientProperties(menuItem); menuItem = null; } protected void uninstallDefaults() { LookAndFeel.uninstallBorder(menuItem); LookAndFeel.installProperty(menuItem, "borderPainted", oldBorderPainted); if (menuItem.getMargin() instanceof UIResource) menuItem.setMargin(null); if (arrowIcon instanceof UIResource) arrowIcon = null; if (checkIcon instanceof UIResource) checkIcon = null; } /** {@collect.stats} * @since 1.3 */ protected void uninstallComponents(JMenuItem menuItem){ BasicHTML.updateRenderer(menuItem, ""); } protected void uninstallListeners() { if (mouseInputListener != null) { menuItem.removeMouseListener(mouseInputListener); menuItem.removeMouseMotionListener(mouseInputListener); } if (menuDragMouseListener != null) { menuItem.removeMenuDragMouseListener(menuDragMouseListener); } if (menuKeyListener != null) { menuItem.removeMenuKeyListener(menuKeyListener); } if (propertyChangeListener != null) { menuItem.removePropertyChangeListener(propertyChangeListener); } mouseInputListener = null; menuDragMouseListener = null; menuKeyListener = null; propertyChangeListener = null; handler = null; } protected void uninstallKeyboardActions() { SwingUtilities.replaceUIActionMap(menuItem, null); SwingUtilities.replaceUIInputMap(menuItem, JComponent. WHEN_IN_FOCUSED_WINDOW, null); } protected MouseInputListener createMouseInputListener(JComponent c) { return getHandler(); } protected MenuDragMouseListener createMenuDragMouseListener(JComponent c) { return getHandler(); } protected MenuKeyListener createMenuKeyListener(JComponent c) { return null; } /** {@collect.stats} * Creates a <code>PropertyChangeListener</code> which will be added to * the menu item. * If this method returns null then it will not be added to the menu item. * * @return an instance of a <code>PropertyChangeListener</code> or null * @since 1.6 */ protected PropertyChangeListener createPropertyChangeListener(JComponent c) { return getHandler(); } Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } InputMap createInputMap(int condition) { if (condition == JComponent.WHEN_IN_FOCUSED_WINDOW) { return new ComponentInputMapUIResource(menuItem); } return null; } void updateAcceleratorBinding() { KeyStroke accelerator = menuItem.getAccelerator(); InputMap windowInputMap = SwingUtilities.getUIInputMap( menuItem, JComponent.WHEN_IN_FOCUSED_WINDOW); if (windowInputMap != null) { windowInputMap.clear(); } if (accelerator != null) { if (windowInputMap == null) { windowInputMap = createInputMap(JComponent. WHEN_IN_FOCUSED_WINDOW); SwingUtilities.replaceUIInputMap(menuItem, JComponent.WHEN_IN_FOCUSED_WINDOW, windowInputMap); } windowInputMap.put(accelerator, "doClick"); } } public Dimension getMinimumSize(JComponent c) { Dimension d = null; View v = (View) c.getClientProperty(BasicHTML.propertyKey); if (v != null) { d = getPreferredSize(c); d.width -= v.getPreferredSpan(View.X_AXIS) - v.getMinimumSpan(View.X_AXIS); } return d; } public Dimension getPreferredSize(JComponent c) { return getPreferredMenuItemSize(c, checkIcon, arrowIcon, defaultTextIconGap); } public Dimension getMaximumSize(JComponent c) { Dimension d = null; View v = (View) c.getClientProperty(BasicHTML.propertyKey); if (v != null) { d = getPreferredSize(c); d.width += v.getMaximumSpan(View.X_AXIS) - v.getPreferredSpan(View.X_AXIS); } return d; } protected Dimension getPreferredMenuItemSize(JComponent c, Icon checkIcon, Icon arrowIcon, int defaultTextIconGap) { // The method also determines the preferred width of the // parent popup menu (through DefaultMenuLayout class). // The menu width equals to the maximal width // among child menu items. // Menu item width will be a sum of the widest check icon, label, // arrow icon and accelerator text among neighbor menu items. // For the latest menu item we will know the maximal widths exactly. // It will be the widest menu item and it will determine // the width of the parent popup menu. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // There is a conceptual problem: if user sets preferred size manually // for a menu item, this method won't be called for it // (see JComponent.getPreferredSize()), // maximal widths won't be calculated, other menu items won't be able // to take them into account and will be layouted in such a way, // as there is no the item with manual preferred size. // But after the first paint() method call, all maximal widths // will be correctly calculated and layout of some menu items // can be changed. For example, it can cause a shift of // the icon and text when user points a menu item by mouse. JMenuItem mi = (JMenuItem) c; MenuItemLayoutHelper lh = new MenuItemLayoutHelper(mi, checkIcon, arrowIcon, MenuItemLayoutHelper.createMaxRect(), defaultTextIconGap, acceleratorDelimiter, BasicGraphicsUtils.isLeftToRight(mi), mi.getFont(), acceleratorFont, MenuItemLayoutHelper.useCheckAndArrow(menuItem), getPropertyPrefix()); Dimension result = new Dimension(); // Calculate the result width result.width = lh.getLeadingGap(); MenuItemLayoutHelper.addMaxWidth(lh.getCheckSize(), lh.getAfterCheckIconGap(), result); // Take into account mimimal text offset. if ((!lh.isTopLevelMenu()) && (lh.getMinTextOffset() > 0) && (result.width < lh.getMinTextOffset())) { result.width = lh.getMinTextOffset(); } MenuItemLayoutHelper.addMaxWidth(lh.getLabelSize(), lh.getGap(), result); MenuItemLayoutHelper.addMaxWidth(lh.getAccSize(), lh.getGap(), result); MenuItemLayoutHelper.addMaxWidth(lh.getArrowSize(), lh.getGap(), result); // Calculate the result height result.height = MenuItemLayoutHelper.max(lh.getCheckSize().getHeight(), lh.getLabelSize().getHeight(), lh.getAccSize().getHeight(), lh.getArrowSize().getHeight()); // Take into account menu item insets Insets insets = lh.getMenuItem().getInsets(); if(insets != null) { result.width += insets.left + insets.right; result.height += insets.top + insets.bottom; } // if the width is even, bump it up one. This is critical // for the focus dash line to draw properly if(result.width%2 == 0) { result.width++; } // if the height is even, bump it up one. This is critical // for the text to center properly if(result.height%2 == 0 && Boolean.TRUE != UIManager.get(getPropertyPrefix() + ".evenHeight")) { result.height++; } return result; } /** {@collect.stats} * We draw the background in paintMenuItem() * so override update (which fills the background of opaque * components by default) to just call paint(). * */ public void update(Graphics g, JComponent c) { paint(g, c); } public void paint(Graphics g, JComponent c) { paintMenuItem(g, c, checkIcon, arrowIcon, selectionBackground, selectionForeground, defaultTextIconGap); } protected void paintMenuItem(Graphics g, JComponent c, Icon checkIcon, Icon arrowIcon, Color background, Color foreground, int defaultTextIconGap) { // Save original graphics font and color Font holdf = g.getFont(); Color holdc = g.getColor(); JMenuItem mi = (JMenuItem) c; g.setFont(mi.getFont()); Rectangle viewRect = new Rectangle(0, 0, mi.getWidth(), mi.getHeight()); applyInsets(viewRect, mi.getInsets()); MenuItemLayoutHelper lh = new MenuItemLayoutHelper(mi, checkIcon, arrowIcon, viewRect, defaultTextIconGap, acceleratorDelimiter, BasicGraphicsUtils.isLeftToRight(mi), mi.getFont(), acceleratorFont, MenuItemLayoutHelper.useCheckAndArrow(menuItem), getPropertyPrefix()); MenuItemLayoutHelper.LayoutResult lr = lh.layoutMenuItem(); paintBackground(g, mi, background); paintCheckIcon(g, lh, lr, holdc, foreground); paintIcon(g, lh, lr, holdc); paintText(g, lh, lr); paintAccText(g, lh, lr); paintArrowIcon(g, lh, lr, foreground); // Restore original graphics font and color g.setColor(holdc); g.setFont(holdf); } private void paintIcon(Graphics g, MenuItemLayoutHelper lh, MenuItemLayoutHelper.LayoutResult lr, Color holdc) { if (lh.getIcon() != null) { Icon icon; ButtonModel model = lh.getMenuItem().getModel(); if (!model.isEnabled()) { icon = lh.getMenuItem().getDisabledIcon(); } else if (model.isPressed() && model.isArmed()) { icon = lh.getMenuItem().getPressedIcon(); if (icon == null) { // Use default icon icon = lh.getMenuItem().getIcon(); } } else { icon = lh.getMenuItem().getIcon(); } if (icon != null) { icon.paintIcon(lh.getMenuItem(), g, lr.getIconRect().x, lr.getIconRect().y); g.setColor(holdc); } } } private void paintCheckIcon(Graphics g, MenuItemLayoutHelper lh, MenuItemLayoutHelper.LayoutResult lr, Color holdc, Color foreground) { if (lh.getCheckIcon() != null) { ButtonModel model = lh.getMenuItem().getModel(); if (model.isArmed() || (lh.getMenuItem() instanceof JMenu && model.isSelected())) { g.setColor(foreground); } else { g.setColor(holdc); } if (lh.useCheckAndArrow()) { lh.getCheckIcon().paintIcon(lh.getMenuItem(), g, lr.getCheckRect().x, lr.getCheckRect().y); } g.setColor(holdc); } } private void paintAccText(Graphics g, MenuItemLayoutHelper lh, MenuItemLayoutHelper.LayoutResult lr) { if (!lh.getAccText().equals("")) { ButtonModel model = lh.getMenuItem().getModel(); g.setFont(lh.getAccFontMetrics().getFont()); if (!model.isEnabled()) { // *** paint the accText disabled if (disabledForeground != null) { g.setColor(disabledForeground); SwingUtilities2.drawString(lh.getMenuItem(), g, lh.getAccText(), lr.getAccRect().x, lr.getAccRect().y + lh.getAccFontMetrics().getAscent()); } else { g.setColor(lh.getMenuItem().getBackground().brighter()); SwingUtilities2.drawString(lh.getMenuItem(), g, lh.getAccText(), lr.getAccRect().x, lr.getAccRect().y + lh.getAccFontMetrics().getAscent()); g.setColor(lh.getMenuItem().getBackground().darker()); SwingUtilities2.drawString(lh.getMenuItem(), g, lh.getAccText(), lr.getAccRect().x - 1, lr.getAccRect().y + lh.getFontMetrics().getAscent() - 1); } } else { // *** paint the accText normally if (model.isArmed() || (lh.getMenuItem() instanceof JMenu && model.isSelected())) { g.setColor(acceleratorSelectionForeground); } else { g.setColor(acceleratorForeground); } SwingUtilities2.drawString(lh.getMenuItem(), g, lh.getAccText(), lr.getAccRect().x, lr.getAccRect().y + lh.getAccFontMetrics().getAscent()); } } } private void paintText(Graphics g, MenuItemLayoutHelper lh, MenuItemLayoutHelper.LayoutResult lr) { if (!lh.getText().equals("")) { if (lh.getHtmlView() != null) { // Text is HTML lh.getHtmlView().paint(g, lr.getTextRect()); } else { // Text isn't HTML paintText(g, lh.getMenuItem(), lr.getTextRect(), lh.getText()); } } } private void paintArrowIcon(Graphics g, MenuItemLayoutHelper lh, MenuItemLayoutHelper.LayoutResult lr, Color foreground) { if (lh.getArrowIcon() != null) { ButtonModel model = lh.getMenuItem().getModel(); if (model.isArmed() || (lh.getMenuItem() instanceof JMenu && model.isSelected())) { g.setColor(foreground); } if (lh.useCheckAndArrow()) { lh.getArrowIcon().paintIcon(lh.getMenuItem(), g, lr.getArrowRect().x, lr.getArrowRect().y); } } } private void applyInsets(Rectangle rect, Insets insets) { if(insets != null) { rect.x += insets.left; rect.y += insets.top; rect.width -= (insets.right + rect.x); rect.height -= (insets.bottom + rect.y); } } /** {@collect.stats} * Draws the background of the menu item. * * @param g the paint graphics * @param menuItem menu item to be painted * @param bgColor selection background color * @since 1.4 */ protected void paintBackground(Graphics g, JMenuItem menuItem, Color bgColor) { ButtonModel model = menuItem.getModel(); Color oldColor = g.getColor(); int menuWidth = menuItem.getWidth(); int menuHeight = menuItem.getHeight(); if(menuItem.isOpaque()) { if (model.isArmed()|| (menuItem instanceof JMenu && model.isSelected())) { g.setColor(bgColor); g.fillRect(0,0, menuWidth, menuHeight); } else { g.setColor(menuItem.getBackground()); g.fillRect(0,0, menuWidth, menuHeight); } g.setColor(oldColor); } else if (model.isArmed() || (menuItem instanceof JMenu && model.isSelected())) { g.setColor(bgColor); g.fillRect(0,0, menuWidth, menuHeight); g.setColor(oldColor); } } /** {@collect.stats} * Renders the text of the current menu item. * <p> * @param g graphics context * @param menuItem menu item to render * @param textRect bounding rectangle for rendering the text * @param text string to render * @since 1.4 */ protected void paintText(Graphics g, JMenuItem menuItem, Rectangle textRect, String text) { ButtonModel model = menuItem.getModel(); FontMetrics fm = SwingUtilities2.getFontMetrics(menuItem, g); int mnemIndex = menuItem.getDisplayedMnemonicIndex(); if(!model.isEnabled()) { // *** paint the text disabled if ( UIManager.get("MenuItem.disabledForeground") instanceof Color ) { g.setColor( UIManager.getColor("MenuItem.disabledForeground") ); SwingUtilities2.drawStringUnderlineCharAt(menuItem, g,text, mnemIndex, textRect.x, textRect.y + fm.getAscent()); } else { g.setColor(menuItem.getBackground().brighter()); SwingUtilities2.drawStringUnderlineCharAt(menuItem, g, text, mnemIndex, textRect.x, textRect.y + fm.getAscent()); g.setColor(menuItem.getBackground().darker()); SwingUtilities2.drawStringUnderlineCharAt(menuItem, g,text, mnemIndex, textRect.x - 1, textRect.y + fm.getAscent() - 1); } } else { // *** paint the text normally if (model.isArmed()|| (menuItem instanceof JMenu && model.isSelected())) { g.setColor(selectionForeground); // Uses protected field. } SwingUtilities2.drawStringUnderlineCharAt(menuItem, g,text, mnemIndex, textRect.x, textRect.y + fm.getAscent()); } } public MenuElement[] getPath() { MenuSelectionManager m = MenuSelectionManager.defaultManager(); MenuElement oldPath[] = m.getSelectedPath(); MenuElement newPath[]; int i = oldPath.length; if (i == 0) return new MenuElement[0]; Component parent = menuItem.getParent(); if (oldPath[i-1].getComponent() == parent) { // The parent popup menu is the last so far newPath = new MenuElement[i+1]; System.arraycopy(oldPath, 0, newPath, 0, i); newPath[i] = menuItem; } else { // A sibling menuitem is the current selection // // This probably needs to handle 'exit submenu into // a menu item. Search backwards along the current // selection until you find the parent popup menu, // then copy up to that and add yourself... int j; for (j = oldPath.length-1; j >= 0; j--) { if (oldPath[j].getComponent() == parent) break; } newPath = new MenuElement[j+2]; System.arraycopy(oldPath, 0, newPath, 0, j+1); newPath[j+1] = menuItem; /* System.out.println("Sibling condition -- "); System.out.println("Old array : "); printMenuElementArray(oldPath, false); System.out.println("New array : "); printMenuElementArray(newPath, false); */ } return newPath; } void printMenuElementArray(MenuElement path[], boolean dumpStack) { System.out.println("Path is("); int i, j; for(i=0,j=path.length; i<j ;i++){ for (int k=0; k<=i; k++) System.out.print(" "); MenuElement me = (MenuElement) path[i]; if(me instanceof JMenuItem) System.out.println(((JMenuItem)me).getText() + ", "); else if (me == null) System.out.println("NULL , "); else System.out.println("" + me + ", "); } System.out.println(")"); if (dumpStack == true) Thread.dumpStack(); } protected class MouseInputHandler implements MouseInputListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void mouseClicked(MouseEvent e) { getHandler().mouseClicked(e); } public void mousePressed(MouseEvent e) { getHandler().mousePressed(e); } public void mouseReleased(MouseEvent e) { getHandler().mouseReleased(e); } public void mouseEntered(MouseEvent e) { getHandler().mouseEntered(e); } public void mouseExited(MouseEvent e) { getHandler().mouseExited(e); } public void mouseDragged(MouseEvent e) { getHandler().mouseDragged(e); } public void mouseMoved(MouseEvent e) { getHandler().mouseMoved(e); } } private static class Actions extends UIAction { private static final String CLICK = "doClick"; Actions(String key) { super(key); } public void actionPerformed(ActionEvent e) { JMenuItem mi = (JMenuItem)e.getSource(); MenuSelectionManager.defaultManager().clearSelectedPath(); mi.doClick(); } } /** {@collect.stats} * Call this method when a menu item is to be activated. * This method handles some of the details of menu item activation * such as clearing the selected path and messaging the * JMenuItem's doClick() method. * * @param msm A MenuSelectionManager. The visual feedback and * internal bookkeeping tasks are delegated to * this MenuSelectionManager. If <code>null</code> is * passed as this argument, the * <code>MenuSelectionManager.defaultManager</code> is * used. * @see MenuSelectionManager * @see JMenuItem#doClick(int) * @since 1.4 */ protected void doClick(MenuSelectionManager msm) { // Auditory cue if (! isInternalFrameSystemMenu()) { BasicLookAndFeel.playSound(menuItem, getPropertyPrefix() + ".commandSound"); } // Visual feedback if (msm == null) { msm = MenuSelectionManager.defaultManager(); } msm.clearSelectedPath(); menuItem.doClick(0); } /** {@collect.stats} * This is to see if the menu item in question is part of the * system menu on an internal frame. * The Strings that are being checked can be found in * MetalInternalFrameTitlePaneUI.java, * WindowsInternalFrameTitlePaneUI.java, and * MotifInternalFrameTitlePaneUI.java. * * @since 1.4 */ private boolean isInternalFrameSystemMenu() { String actionCommand = menuItem.getActionCommand(); if ((actionCommand == "Close") || (actionCommand == "Minimize") || (actionCommand == "Restore") || (actionCommand == "Maximize")) { return true; } else { return false; } } // BasicMenuUI subclasses this. class Handler implements MenuDragMouseListener, MouseInputListener, PropertyChangeListener { // // MouseInputListener // public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { if (!menuItem.isEnabled()) { return; } MenuSelectionManager manager = MenuSelectionManager.defaultManager(); Point p = e.getPoint(); if(p.x >= 0 && p.x < menuItem.getWidth() && p.y >= 0 && p.y < menuItem.getHeight()) { doClick(manager); } else { manager.processMouseEvent(e); } } public void mouseEntered(MouseEvent e) { MenuSelectionManager manager = MenuSelectionManager.defaultManager(); int modifiers = e.getModifiers(); // 4188027: drag enter/exit added in JDK 1.1.7A, JDK1.2 if ((modifiers & (InputEvent.BUTTON1_MASK | InputEvent.BUTTON2_MASK | InputEvent.BUTTON3_MASK)) !=0 ) { MenuSelectionManager.defaultManager().processMouseEvent(e); } else { manager.setSelectedPath(getPath()); } } public void mouseExited(MouseEvent e) { MenuSelectionManager manager = MenuSelectionManager.defaultManager(); int modifiers = e.getModifiers(); // 4188027: drag enter/exit added in JDK 1.1.7A, JDK1.2 if ((modifiers & (InputEvent.BUTTON1_MASK | InputEvent.BUTTON2_MASK | InputEvent.BUTTON3_MASK)) !=0 ) { MenuSelectionManager.defaultManager().processMouseEvent(e); } else { MenuElement path[] = manager.getSelectedPath(); if (path.length > 1 && path[path.length-1] == menuItem) { MenuElement newPath[] = new MenuElement[path.length-1]; int i,c; for(i=0,c=path.length-1;i<c;i++) newPath[i] = path[i]; manager.setSelectedPath(newPath); } } } public void mouseDragged(MouseEvent e) { MenuSelectionManager.defaultManager().processMouseEvent(e); } public void mouseMoved(MouseEvent e) { } // // MenuDragListener // public void menuDragMouseEntered(MenuDragMouseEvent e) { MenuSelectionManager manager = e.getMenuSelectionManager(); MenuElement path[] = e.getPath(); manager.setSelectedPath(path); } public void menuDragMouseDragged(MenuDragMouseEvent e) { MenuSelectionManager manager = e.getMenuSelectionManager(); MenuElement path[] = e.getPath(); manager.setSelectedPath(path); } public void menuDragMouseExited(MenuDragMouseEvent e) {} public void menuDragMouseReleased(MenuDragMouseEvent e) { if (!menuItem.isEnabled()) { return; } MenuSelectionManager manager = e.getMenuSelectionManager(); MenuElement path[] = e.getPath(); Point p = e.getPoint(); if (p.x >= 0 && p.x < menuItem.getWidth() && p.y >= 0 && p.y < menuItem.getHeight()) { doClick(manager); } else { manager.clearSelectedPath(); } } // // PropertyChangeListener // public void propertyChange(PropertyChangeEvent e) { String name = e.getPropertyName(); if (name == "labelFor" || name == "displayedMnemonic" || name == "accelerator") { updateAcceleratorBinding(); } else if (name == "text" || "font" == name || "foreground" == name) { // remove the old html view client property if one // existed, and install a new one if the text installed // into the JLabel is html source. JMenuItem lbl = ((JMenuItem) e.getSource()); String text = lbl.getText(); BasicHTML.updateRenderer(lbl, text); } else if (name == "iconTextGap") { defaultTextIconGap = ((Number)e.getNewValue()).intValue(); } } } }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.event.ActionEvent; import java.awt.KeyboardFocusManager; import java.awt.Component; import java.awt.Point; import java.awt.Rectangle; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.*; import javax.swing.plaf.*; import sun.swing.DefaultLookup; import sun.swing.UIAction; /** {@collect.stats} * Basic implementation of RootPaneUI, there is one shared between all * JRootPane instances. * * @author Scott Violet * @since 1.3 */ public class BasicRootPaneUI extends RootPaneUI implements PropertyChangeListener { private static RootPaneUI rootPaneUI = new BasicRootPaneUI(); public static ComponentUI createUI(JComponent c) { return rootPaneUI; } public void installUI(JComponent c) { installDefaults((JRootPane)c); installComponents((JRootPane)c); installListeners((JRootPane)c); installKeyboardActions((JRootPane)c); } public void uninstallUI(JComponent c) { uninstallDefaults((JRootPane)c); uninstallComponents((JRootPane)c); uninstallListeners((JRootPane)c); uninstallKeyboardActions((JRootPane)c); } protected void installDefaults(JRootPane c){ LookAndFeel.installProperty(c, "opaque", Boolean.FALSE); } protected void installComponents(JRootPane root) { } protected void installListeners(JRootPane root) { root.addPropertyChangeListener(this); } protected void installKeyboardActions(JRootPane root) { InputMap km = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, root); SwingUtilities.replaceUIInputMap(root, JComponent.WHEN_IN_FOCUSED_WINDOW, km); km = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, root); SwingUtilities.replaceUIInputMap(root, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, km); LazyActionMap.installLazyActionMap(root, BasicRootPaneUI.class, "RootPane.actionMap"); updateDefaultButtonBindings(root); } protected void uninstallDefaults(JRootPane root) { } protected void uninstallComponents(JRootPane root) { } protected void uninstallListeners(JRootPane root) { root.removePropertyChangeListener(this); } protected void uninstallKeyboardActions(JRootPane root) { SwingUtilities.replaceUIInputMap(root, JComponent. WHEN_IN_FOCUSED_WINDOW, null); SwingUtilities.replaceUIActionMap(root, null); } InputMap getInputMap(int condition, JComponent c) { if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) { return (InputMap)DefaultLookup.get(c, this, "RootPane.ancestorInputMap"); } if (condition == JComponent.WHEN_IN_FOCUSED_WINDOW) { return createInputMap(condition, c); } return null; } ComponentInputMap createInputMap(int condition, JComponent c) { return new RootPaneInputMap(c); } static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.PRESS)); map.put(new Actions(Actions.RELEASE)); map.put(new Actions(Actions.POST_POPUP)); } /** {@collect.stats} * Invoked when the default button property has changed. This reloads * the bindings from the defaults table with name * <code>RootPane.defaultButtonWindowKeyBindings</code>. */ void updateDefaultButtonBindings(JRootPane root) { InputMap km = SwingUtilities.getUIInputMap(root, JComponent. WHEN_IN_FOCUSED_WINDOW); while (km != null && !(km instanceof RootPaneInputMap)) { km = km.getParent(); } if (km != null) { km.clear(); if (root.getDefaultButton() != null) { Object[] bindings = (Object[])DefaultLookup.get(root, this, "RootPane.defaultButtonWindowKeyBindings"); if (bindings != null) { LookAndFeel.loadKeyBindings(km, bindings); } } } } /** {@collect.stats} * Invoked when a property changes on the root pane. If the event * indicates the <code>defaultButton</code> has changed, this will * reinstall the keyboard actions. */ public void propertyChange(PropertyChangeEvent e) { if(e.getPropertyName().equals("defaultButton")) { JRootPane rootpane = (JRootPane)e.getSource(); updateDefaultButtonBindings(rootpane); if (rootpane.getClientProperty("temporaryDefaultButton") == null) { rootpane.putClientProperty("initialDefaultButton", e.getNewValue()); } } } static class Actions extends UIAction { public static final String PRESS = "press"; public static final String RELEASE = "release"; public static final String POST_POPUP = "postPopup"; Actions(String name) { super(name); } public void actionPerformed(ActionEvent evt) { JRootPane root = (JRootPane)evt.getSource(); JButton owner = root.getDefaultButton(); String key = getName(); if (key == POST_POPUP) { // Action to post popup Component c = KeyboardFocusManager .getCurrentKeyboardFocusManager() .getFocusOwner(); if(c instanceof JComponent) { JComponent src = (JComponent) c; JPopupMenu jpm = src.getComponentPopupMenu(); if(jpm != null) { Point pt = src.getPopupLocation(null); if(pt == null) { Rectangle vis = src.getVisibleRect(); pt = new Point(vis.x+vis.width/2, vis.y+vis.height/2); } jpm.show(c, pt.x, pt.y); } } } else if (owner != null && SwingUtilities.getRootPane(owner) == root) { if (key == PRESS) { owner.doClick(20); } } } public boolean isEnabled(Object sender) { String key = getName(); if(key == POST_POPUP) { MenuElement[] elems = MenuSelectionManager .defaultManager() .getSelectedPath(); if(elems != null && elems.length != 0) { return false; // We shall not interfere with already opened menu } Component c = KeyboardFocusManager .getCurrentKeyboardFocusManager() .getFocusOwner(); if(c instanceof JComponent) { JComponent src = (JComponent) c; return src.getComponentPopupMenu() != null; } return false; } if (sender != null && sender instanceof JRootPane) { JButton owner = ((JRootPane)sender).getDefaultButton(); return (owner != null && owner.getModel().isEnabled()); } return true; } } private static class RootPaneInputMap extends ComponentInputMapUIResource { public RootPaneInputMap(JComponent c) { super(c); } } }
Java
/* * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.accessibility.AccessibleContext; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.LineBorder; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.io.Serializable; /** {@collect.stats} * This is a basic implementation of the <code>ComboPopup</code> interface. * * This class represents the ui for the popup portion of the combo box. * <p> * All event handling is handled by listener classes created with the * <code>createxxxListener()</code> methods and internal classes. * You can change the behavior of this class by overriding the * <code>createxxxListener()</code> methods and supplying your own * event listeners or subclassing from the ones supplied in this class. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Tom Santos * @author Mark Davidson */ public class BasicComboPopup extends JPopupMenu implements ComboPopup { // An empty ListMode, this is used when the UI changes to allow // the JList to be gc'ed. private static class EmptyListModelClass implements ListModel, Serializable { public int getSize() { return 0; } public Object getElementAt(int index) { return null; } public void addListDataListener(ListDataListener l) {} public void removeListDataListener(ListDataListener l) {} }; static final ListModel EmptyListModel = new EmptyListModelClass(); private static Border LIST_BORDER = new LineBorder(Color.BLACK, 1); protected JComboBox comboBox; /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. Use the accessor methods instead. * * @see #getList * @see #createList */ protected JList list; /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. Use the create method instead * * @see #createScroller */ protected JScrollPane scroller; /** {@collect.stats} * As of Java 2 platform v1.4 this previously undocumented field is no * longer used. */ protected boolean valueIsAdjusting = false; // Listeners that are required by the ComboPopup interface /** {@collect.stats} * Implementation of all the listener classes. */ private Handler handler; /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. Use the accessor or create methods instead. * * @see #getMouseMotionListener * @see #createMouseMotionListener */ protected MouseMotionListener mouseMotionListener; /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. Use the accessor or create methods instead. * * @see #getMouseListener * @see #createMouseListener */ protected MouseListener mouseListener; /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. Use the accessor or create methods instead. * * @see #getKeyListener * @see #createKeyListener */ protected KeyListener keyListener; /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. Use the create method instead. * * @see #createListSelectionListener */ protected ListSelectionListener listSelectionListener; // Listeners that are attached to the list /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. Use the create method instead. * * @see #createListMouseListener */ protected MouseListener listMouseListener; /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. Use the create method instead * * @see #createListMouseMotionListener */ protected MouseMotionListener listMouseMotionListener; // Added to the combo box for bound properties /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. Use the create method instead * * @see #createPropertyChangeListener */ protected PropertyChangeListener propertyChangeListener; // Added to the combo box model /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. Use the create method instead * * @see #createListDataListener */ protected ListDataListener listDataListener; /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. Use the create method instead * * @see #createItemListener */ protected ItemListener itemListener; /** {@collect.stats} * This protected field is implementation specific. Do not access directly * or override. */ protected Timer autoscrollTimer; protected boolean hasEntered = false; protected boolean isAutoScrolling = false; protected int scrollDirection = SCROLL_UP; protected static final int SCROLL_UP = 0; protected static final int SCROLL_DOWN = 1; //======================================== // begin ComboPopup method implementations // /** {@collect.stats} * Implementation of ComboPopup.show(). */ public void show() { setListSelection(comboBox.getSelectedIndex()); Point location = getPopupLocation(); show( comboBox, location.x, location.y ); } /** {@collect.stats} * Implementation of ComboPopup.hide(). */ public void hide() { MenuSelectionManager manager = MenuSelectionManager.defaultManager(); MenuElement [] selection = manager.getSelectedPath(); for ( int i = 0 ; i < selection.length ; i++ ) { if ( selection[i] == this ) { manager.clearSelectedPath(); break; } } if (selection.length > 0) { comboBox.repaint(); } } /** {@collect.stats} * Implementation of ComboPopup.getList(). */ public JList getList() { return list; } /** {@collect.stats} * Implementation of ComboPopup.getMouseListener(). * * @return a <code>MouseListener</code> or null * @see ComboPopup#getMouseListener */ public MouseListener getMouseListener() { if (mouseListener == null) { mouseListener = createMouseListener(); } return mouseListener; } /** {@collect.stats} * Implementation of ComboPopup.getMouseMotionListener(). * * @return a <code>MouseMotionListener</code> or null * @see ComboPopup#getMouseMotionListener */ public MouseMotionListener getMouseMotionListener() { if (mouseMotionListener == null) { mouseMotionListener = createMouseMotionListener(); } return mouseMotionListener; } /** {@collect.stats} * Implementation of ComboPopup.getKeyListener(). * * @return a <code>KeyListener</code> or null * @see ComboPopup#getKeyListener */ public KeyListener getKeyListener() { if (keyListener == null) { keyListener = createKeyListener(); } return keyListener; } /** {@collect.stats} * Called when the UI is uninstalling. Since this popup isn't in the component * tree, it won't get it's uninstallUI() called. It removes the listeners that * were added in addComboBoxListeners(). */ public void uninstallingUI() { if (propertyChangeListener != null) { comboBox.removePropertyChangeListener( propertyChangeListener ); } if (itemListener != null) { comboBox.removeItemListener( itemListener ); } uninstallComboBoxModelListeners(comboBox.getModel()); uninstallKeyboardActions(); uninstallListListeners(); // We do this, otherwise the listener the ui installs on // the model (the combobox model in this case) will keep a // reference to the list, causing the list (and us) to never get gced. list.setModel(EmptyListModel); } // // end ComboPopup method implementations //====================================== /** {@collect.stats} * Removes the listeners from the combo box model * * @param model The combo box model to install listeners * @see #installComboBoxModelListeners */ protected void uninstallComboBoxModelListeners( ComboBoxModel model ) { if (model != null && listDataListener != null) { model.removeListDataListener(listDataListener); } } protected void uninstallKeyboardActions() { // XXX - shouldn't call this method // comboBox.unregisterKeyboardAction( KeyStroke.getKeyStroke( KeyEvent.VK_ENTER, 0 ) ); } //=================================================================== // begin Initialization routines // public BasicComboPopup( JComboBox combo ) { super(); setName("ComboPopup.popup"); comboBox = combo; setLightWeightPopupEnabled( comboBox.isLightWeightPopupEnabled() ); // UI construction of the popup. list = createList(); list.setName("ComboBox.list"); configureList(); scroller = createScroller(); scroller.setName("ComboBox.scrollPane"); configureScroller(); configurePopup(); installComboBoxListeners(); installKeyboardActions(); } // Overriden PopupMenuListener notification methods to inform combo box // PopupMenuListeners. protected void firePopupMenuWillBecomeVisible() { super.firePopupMenuWillBecomeVisible(); comboBox.firePopupMenuWillBecomeVisible(); } protected void firePopupMenuWillBecomeInvisible() { super.firePopupMenuWillBecomeInvisible(); comboBox.firePopupMenuWillBecomeInvisible(); } protected void firePopupMenuCanceled() { super.firePopupMenuCanceled(); comboBox.firePopupMenuCanceled(); } /** {@collect.stats} * Creates a listener * that will watch for mouse-press and release events on the combo box. * * <strong>Warning:</strong> * When overriding this method, make sure to maintain the existing * behavior. * * @return a <code>MouseListener</code> which will be added to * the combo box or null */ protected MouseListener createMouseListener() { return getHandler(); } /** {@collect.stats} * Creates the mouse motion listener which will be added to the combo * box. * * <strong>Warning:</strong> * When overriding this method, make sure to maintain the existing * behavior. * * @return a <code>MouseMotionListener</code> which will be added to * the combo box or null */ protected MouseMotionListener createMouseMotionListener() { return getHandler(); } /** {@collect.stats} * Creates the key listener that will be added to the combo box. If * this method returns null then it will not be added to the combo box. * * @return a <code>KeyListener</code> or null */ protected KeyListener createKeyListener() { return null; } /** {@collect.stats} * Creates a list selection listener that watches for selection changes in * the popup's list. If this method returns null then it will not * be added to the popup list. * * @return an instance of a <code>ListSelectionListener</code> or null */ protected ListSelectionListener createListSelectionListener() { return null; } /** {@collect.stats} * Creates a list data listener which will be added to the * <code>ComboBoxModel</code>. If this method returns null then * it will not be added to the combo box model. * * @return an instance of a <code>ListDataListener</code> or null */ protected ListDataListener createListDataListener() { return null; } /** {@collect.stats} * Creates a mouse listener that watches for mouse events in * the popup's list. If this method returns null then it will * not be added to the combo box. * * @return an instance of a <code>MouseListener</code> or null */ protected MouseListener createListMouseListener() { return getHandler(); } /** {@collect.stats} * Creates a mouse motion listener that watches for mouse motion * events in the popup's list. If this method returns null then it will * not be added to the combo box. * * @return an instance of a <code>MouseMotionListener</code> or null */ protected MouseMotionListener createListMouseMotionListener() { return getHandler(); } /** {@collect.stats} * Creates a <code>PropertyChangeListener</code> which will be added to * the combo box. If this method returns null then it will not * be added to the combo box. * * @return an instance of a <code>PropertyChangeListener</code> or null */ protected PropertyChangeListener createPropertyChangeListener() { return getHandler(); } /** {@collect.stats} * Creates an <code>ItemListener</code> which will be added to the * combo box. If this method returns null then it will not * be added to the combo box. * <p> * Subclasses may override this method to return instances of their own * ItemEvent handlers. * * @return an instance of an <code>ItemListener</code> or null */ protected ItemListener createItemListener() { return getHandler(); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } /** {@collect.stats} * Creates the JList used in the popup to display * the items in the combo box model. This method is called when the UI class * is created. * * @return a <code>JList</code> used to display the combo box items */ protected JList createList() { return new JList( comboBox.getModel() ) { public void processMouseEvent(MouseEvent e) { if (e.isControlDown()) { // Fix for 4234053. Filter out the Control Key from the list. // ie., don't allow CTRL key deselection. e = new MouseEvent((Component)e.getSource(), e.getID(), e.getWhen(), e.getModifiers() ^ InputEvent.CTRL_MASK, e.getX(), e.getY(), e.getXOnScreen(), e.getYOnScreen(), e.getClickCount(), e.isPopupTrigger(), MouseEvent.NOBUTTON); } super.processMouseEvent(e); } }; } /** {@collect.stats} * Configures the list which is used to hold the combo box items in the * popup. This method is called when the UI class * is created. * * @see #createList */ protected void configureList() { list.setFont( comboBox.getFont() ); list.setForeground( comboBox.getForeground() ); list.setBackground( comboBox.getBackground() ); list.setSelectionForeground( UIManager.getColor( "ComboBox.selectionForeground" ) ); list.setSelectionBackground( UIManager.getColor( "ComboBox.selectionBackground" ) ); list.setBorder( null ); list.setCellRenderer( comboBox.getRenderer() ); list.setFocusable( false ); list.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); setListSelection( comboBox.getSelectedIndex() ); installListListeners(); } /** {@collect.stats} * Adds the listeners to the list control. */ protected void installListListeners() { if ((listMouseListener = createListMouseListener()) != null) { list.addMouseListener( listMouseListener ); } if ((listMouseMotionListener = createListMouseMotionListener()) != null) { list.addMouseMotionListener( listMouseMotionListener ); } if ((listSelectionListener = createListSelectionListener()) != null) { list.addListSelectionListener( listSelectionListener ); } } void uninstallListListeners() { if (listMouseListener != null) { list.removeMouseListener(listMouseListener); listMouseListener = null; } if (listMouseMotionListener != null) { list.removeMouseMotionListener(listMouseMotionListener); listMouseMotionListener = null; } if (listSelectionListener != null) { list.removeListSelectionListener(listSelectionListener); listSelectionListener = null; } handler = null; } /** {@collect.stats} * Creates the scroll pane which houses the scrollable list. */ protected JScrollPane createScroller() { JScrollPane sp = new JScrollPane( list, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ); sp.setHorizontalScrollBar(null); return sp; } /** {@collect.stats} * Configures the scrollable portion which holds the list within * the combo box popup. This method is called when the UI class * is created. */ protected void configureScroller() { scroller.setFocusable( false ); scroller.getVerticalScrollBar().setFocusable( false ); scroller.setBorder( null ); } /** {@collect.stats} * Configures the popup portion of the combo box. This method is called * when the UI class is created. */ protected void configurePopup() { setLayout( new BoxLayout( this, BoxLayout.Y_AXIS ) ); setBorderPainted( true ); setBorder(LIST_BORDER); setOpaque( false ); add( scroller ); setDoubleBuffered( true ); setFocusable( false ); } /** {@collect.stats} * This method adds the necessary listeners to the JComboBox. */ protected void installComboBoxListeners() { if ((propertyChangeListener = createPropertyChangeListener()) != null) { comboBox.addPropertyChangeListener(propertyChangeListener); } if ((itemListener = createItemListener()) != null) { comboBox.addItemListener(itemListener); } installComboBoxModelListeners(comboBox.getModel()); } /** {@collect.stats} * Installs the listeners on the combo box model. Any listeners installed * on the combo box model should be removed in * <code>uninstallComboBoxModelListeners</code>. * * @param model The combo box model to install listeners * @see #uninstallComboBoxModelListeners */ protected void installComboBoxModelListeners( ComboBoxModel model ) { if (model != null && (listDataListener = createListDataListener()) != null) { model.addListDataListener(listDataListener); } } protected void installKeyboardActions() { /* XXX - shouldn't call this method. take it out for testing. ActionListener action = new ActionListener() { public void actionPerformed(ActionEvent e){ } }; comboBox.registerKeyboardAction( action, KeyStroke.getKeyStroke( KeyEvent.VK_ENTER, 0 ), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT ); */ } // // end Initialization routines //================================================================= //=================================================================== // begin Event Listenters // /** {@collect.stats} * A listener to be registered upon the combo box * (<em>not</em> its popup menu) * to handle mouse events * that affect the state of the popup menu. * The main purpose of this listener is to make the popup menu * appear and disappear. * This listener also helps * with click-and-drag scenarios by setting the selection if the mouse was * released over the list during a drag. * * <p> * <strong>Warning:</strong> * We recommend that you <em>not</em> * create subclasses of this class. * If you absolutely must create a subclass, * be sure to invoke the superclass * version of each method. * * @see BasicComboPopup#createMouseListener */ protected class InvocationMouseHandler extends MouseAdapter { /** {@collect.stats} * Responds to mouse-pressed events on the combo box. * * @param e the mouse-press event to be handled */ public void mousePressed( MouseEvent e ) { getHandler().mousePressed(e); } /** {@collect.stats} * Responds to the user terminating * a click or drag that began on the combo box. * * @param e the mouse-release event to be handled */ public void mouseReleased( MouseEvent e ) { getHandler().mouseReleased(e); } } /** {@collect.stats} * This listener watches for dragging and updates the current selection in the * list if it is dragging over the list. */ protected class InvocationMouseMotionHandler extends MouseMotionAdapter { public void mouseDragged( MouseEvent e ) { getHandler().mouseDragged(e); } } /** {@collect.stats} * As of Java 2 platform v 1.4, this class is now obsolete and is only included for * backwards API compatibility. Do not instantiate or subclass. * <p> * All the functionality of this class has been included in * BasicComboBoxUI ActionMap/InputMap methods. */ public class InvocationKeyHandler extends KeyAdapter { public void keyReleased( KeyEvent e ) {} } /** {@collect.stats} * As of Java 2 platform v 1.4, this class is now obsolete, doesn't do anything, and * is only included for backwards API compatibility. Do not call or * override. */ protected class ListSelectionHandler implements ListSelectionListener { public void valueChanged( ListSelectionEvent e ) {} } /** {@collect.stats} * As of 1.4, this class is now obsolete, doesn't do anything, and * is only included for backwards API compatibility. Do not call or * override. * <p> * The functionality has been migrated into <code>ItemHandler</code>. * * @see #createItemListener */ public class ListDataHandler implements ListDataListener { public void contentsChanged( ListDataEvent e ) {} public void intervalAdded( ListDataEvent e ) { } public void intervalRemoved( ListDataEvent e ) { } } /** {@collect.stats} * This listener hides the popup when the mouse is released in the list. */ protected class ListMouseHandler extends MouseAdapter { public void mousePressed( MouseEvent e ) { } public void mouseReleased(MouseEvent anEvent) { getHandler().mouseReleased(anEvent); } } /** {@collect.stats} * This listener changes the selected item as you move the mouse over the list. * The selection change is not committed to the model, this is for user feedback only. */ protected class ListMouseMotionHandler extends MouseMotionAdapter { public void mouseMoved( MouseEvent anEvent ) { getHandler().mouseMoved(anEvent); } } /** {@collect.stats} * This listener watches for changes to the selection in the * combo box. */ protected class ItemHandler implements ItemListener { public void itemStateChanged( ItemEvent e ) { getHandler().itemStateChanged(e); } } /** {@collect.stats} * This listener watches for bound properties that have changed in the * combo box. * <p> * Subclasses which wish to listen to combo box property changes should * call the superclass methods to ensure that the combo popup correctly * handles property changes. * * @see #createPropertyChangeListener */ protected class PropertyChangeHandler implements PropertyChangeListener { public void propertyChange( PropertyChangeEvent e ) { getHandler().propertyChange(e); } } private class AutoScrollActionHandler implements ActionListener { private int direction; AutoScrollActionHandler(int direction) { this.direction = direction; } public void actionPerformed(ActionEvent e) { if (direction == SCROLL_UP) { autoScrollUp(); } else { autoScrollDown(); } } } private class Handler implements ItemListener, MouseListener, MouseMotionListener, PropertyChangeListener, Serializable { // // MouseListener // NOTE: this is added to both the JList and JComboBox // public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { if (e.getSource() == list) { return; } if (!SwingUtilities.isLeftMouseButton(e) || !comboBox.isEnabled()) return; if ( comboBox.isEditable() ) { Component comp = comboBox.getEditor().getEditorComponent(); if ((!(comp instanceof JComponent)) || ((JComponent)comp).isRequestFocusEnabled()) { comp.requestFocus(); } } else if (comboBox.isRequestFocusEnabled()) { comboBox.requestFocus(); } togglePopup(); } public void mouseReleased(MouseEvent e) { if (e.getSource() == list) { if (list.getModel().getSize() > 0) { // JList mouse listener if (comboBox.getSelectedIndex() != list.getSelectedIndex()) { comboBox.setSelectedIndex( list.getSelectedIndex() ); } else { comboBox.getEditor().setItem( list.getSelectedValue() ); } } comboBox.setPopupVisible(false); // workaround for cancelling an edited item (bug 4530953) if (comboBox.isEditable() && comboBox.getEditor() != null) { comboBox.configureEditor(comboBox.getEditor(), comboBox.getSelectedItem()); } return; } // JComboBox mouse listener Component source = (Component)e.getSource(); Dimension size = source.getSize(); Rectangle bounds = new Rectangle( 0, 0, size.width - 1, size.height - 1 ); if ( !bounds.contains( e.getPoint() ) ) { MouseEvent newEvent = convertMouseEvent( e ); Point location = newEvent.getPoint(); Rectangle r = new Rectangle(); list.computeVisibleRect( r ); if ( r.contains( location ) ) { if (comboBox.getSelectedIndex() != list.getSelectedIndex()) { comboBox.setSelectedIndex( list.getSelectedIndex() ); } else { comboBox.getEditor().setItem( list.getSelectedValue() ); } } comboBox.setPopupVisible(false); } hasEntered = false; stopAutoScrolling(); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } // // MouseMotionListener: // NOTE: this is added to both the List and ComboBox // public void mouseMoved(MouseEvent anEvent) { if (anEvent.getSource() == list) { Point location = anEvent.getPoint(); Rectangle r = new Rectangle(); list.computeVisibleRect( r ); if ( r.contains( location ) ) { updateListBoxSelectionForEvent( anEvent, false ); } } } public void mouseDragged( MouseEvent e ) { if (e.getSource() == list) { return; } if ( isVisible() ) { MouseEvent newEvent = convertMouseEvent( e ); Rectangle r = new Rectangle(); list.computeVisibleRect( r ); if ( newEvent.getPoint().y >= r.y && newEvent.getPoint().y <= r.y + r.height - 1 ) { hasEntered = true; if ( isAutoScrolling ) { stopAutoScrolling(); } Point location = newEvent.getPoint(); if ( r.contains( location ) ) { updateListBoxSelectionForEvent( newEvent, false ); } } else { if ( hasEntered ) { int directionToScroll = newEvent.getPoint().y < r.y ? SCROLL_UP : SCROLL_DOWN; if ( isAutoScrolling && scrollDirection != directionToScroll ) { stopAutoScrolling(); startAutoScrolling( directionToScroll ); } else if ( !isAutoScrolling ) { startAutoScrolling( directionToScroll ); } } else { if ( e.getPoint().y < 0 ) { hasEntered = true; startAutoScrolling( SCROLL_UP ); } } } } } // // PropertyChangeListener // public void propertyChange(PropertyChangeEvent e) { JComboBox comboBox = (JComboBox)e.getSource(); String propertyName = e.getPropertyName(); if ( propertyName == "model" ) { ComboBoxModel oldModel = (ComboBoxModel)e.getOldValue(); ComboBoxModel newModel = (ComboBoxModel)e.getNewValue(); uninstallComboBoxModelListeners(oldModel); installComboBoxModelListeners(newModel); list.setModel(newModel); if ( isVisible() ) { hide(); } } else if ( propertyName == "renderer" ) { list.setCellRenderer( comboBox.getRenderer() ); if ( isVisible() ) { hide(); } } else if (propertyName == "componentOrientation") { // Pass along the new component orientation // to the list and the scroller ComponentOrientation o =(ComponentOrientation)e.getNewValue(); JList list = getList(); if (list!=null && list.getComponentOrientation()!=o) { list.setComponentOrientation(o); } if (scroller!=null && scroller.getComponentOrientation()!=o) { scroller.setComponentOrientation(o); } if (o!=getComponentOrientation()) { setComponentOrientation(o); } } else if (propertyName == "lightWeightPopupEnabled") { setLightWeightPopupEnabled(comboBox.isLightWeightPopupEnabled()); } } // // ItemListener // public void itemStateChanged( ItemEvent e ) { if (e.getStateChange() == ItemEvent.SELECTED) { JComboBox comboBox = (JComboBox)e.getSource(); setListSelection(comboBox.getSelectedIndex()); } } } // // end Event Listeners //================================================================= /** {@collect.stats} * Overridden to unconditionally return false. */ public boolean isFocusTraversable() { return false; } //=================================================================== // begin Autoscroll methods // /** {@collect.stats} * This protected method is implementation specific and should be private. * do not call or override. */ protected void startAutoScrolling( int direction ) { // XXX - should be a private method within InvocationMouseMotionHandler // if possible. if ( isAutoScrolling ) { autoscrollTimer.stop(); } isAutoScrolling = true; if ( direction == SCROLL_UP ) { scrollDirection = SCROLL_UP; Point convertedPoint = SwingUtilities.convertPoint( scroller, new Point( 1, 1 ), list ); int top = list.locationToIndex( convertedPoint ); list.setSelectedIndex( top ); autoscrollTimer = new Timer( 100, new AutoScrollActionHandler( SCROLL_UP) ); } else if ( direction == SCROLL_DOWN ) { scrollDirection = SCROLL_DOWN; Dimension size = scroller.getSize(); Point convertedPoint = SwingUtilities.convertPoint( scroller, new Point( 1, (size.height - 1) - 2 ), list ); int bottom = list.locationToIndex( convertedPoint ); list.setSelectedIndex( bottom ); autoscrollTimer = new Timer(100, new AutoScrollActionHandler( SCROLL_DOWN)); } autoscrollTimer.start(); } /** {@collect.stats} * This protected method is implementation specific and should be private. * do not call or override. */ protected void stopAutoScrolling() { isAutoScrolling = false; if ( autoscrollTimer != null ) { autoscrollTimer.stop(); autoscrollTimer = null; } } /** {@collect.stats} * This protected method is implementation specific and should be private. * do not call or override. */ protected void autoScrollUp() { int index = list.getSelectedIndex(); if ( index > 0 ) { list.setSelectedIndex( index - 1 ); list.ensureIndexIsVisible( index - 1 ); } } /** {@collect.stats} * This protected method is implementation specific and should be private. * do not call or override. */ protected void autoScrollDown() { int index = list.getSelectedIndex(); int lastItem = list.getModel().getSize() - 1; if ( index < lastItem ) { list.setSelectedIndex( index + 1 ); list.ensureIndexIsVisible( index + 1 ); } } // // end Autoscroll methods //================================================================= //=================================================================== // begin Utility methods // /** {@collect.stats} * Gets the AccessibleContext associated with this BasicComboPopup. * The AccessibleContext will have its parent set to the ComboBox. * * @return an AccessibleContext for the BasicComboPopup * @since 1.5 */ public AccessibleContext getAccessibleContext() { AccessibleContext context = super.getAccessibleContext(); context.setAccessibleParent(comboBox); return context; } /** {@collect.stats} * This is is a utility method that helps event handlers figure out where to * send the focus when the popup is brought up. The standard implementation * delegates the focus to the editor (if the combo box is editable) or to * the JComboBox if it is not editable. */ protected void delegateFocus( MouseEvent e ) { if ( comboBox.isEditable() ) { Component comp = comboBox.getEditor().getEditorComponent(); if ((!(comp instanceof JComponent)) || ((JComponent)comp).isRequestFocusEnabled()) { comp.requestFocus(); } } else if (comboBox.isRequestFocusEnabled()) { comboBox.requestFocus(); } } /** {@collect.stats} * Makes the popup visible if it is hidden and makes it hidden if it is * visible. */ protected void togglePopup() { if ( isVisible() ) { hide(); } else { show(); } } /** {@collect.stats} * Sets the list selection index to the selectedIndex. This * method is used to synchronize the list selection with the * combo box selection. * * @param selectedIndex the index to set the list */ private void setListSelection(int selectedIndex) { if ( selectedIndex == -1 ) { list.clearSelection(); } else { list.setSelectedIndex( selectedIndex ); list.ensureIndexIsVisible( selectedIndex ); } } protected MouseEvent convertMouseEvent( MouseEvent e ) { Point convertedPoint = SwingUtilities.convertPoint( (Component)e.getSource(), e.getPoint(), list ); MouseEvent newEvent = new MouseEvent( (Component)e.getSource(), e.getID(), e.getWhen(), e.getModifiers(), convertedPoint.x, convertedPoint.y, e.getXOnScreen(), e.getYOnScreen(), e.getClickCount(), e.isPopupTrigger(), MouseEvent.NOBUTTON ); return newEvent; } /** {@collect.stats} * Retrieves the height of the popup based on the current * ListCellRenderer and the maximum row count. */ protected int getPopupHeightForRowCount(int maxRowCount) { // Set the cached value of the minimum row count int minRowCount = Math.min( maxRowCount, comboBox.getItemCount() ); int height = 0; ListCellRenderer renderer = list.getCellRenderer(); Object value = null; for ( int i = 0; i < minRowCount; ++i ) { value = list.getModel().getElementAt( i ); Component c = renderer.getListCellRendererComponent( list, value, i, false, false ); height += c.getPreferredSize().height; } if (height == 0) { height = comboBox.getHeight(); } Border border = scroller.getViewportBorder(); if (border != null) { Insets insets = border.getBorderInsets(null); height += insets.top + insets.bottom; } border = scroller.getBorder(); if (border != null) { Insets insets = border.getBorderInsets(null); height += insets.top + insets.bottom; } return height; } /** {@collect.stats} * Calculate the placement and size of the popup portion of the combo box based * on the combo box location and the enclosing screen bounds. If * no transformations are required, then the returned rectangle will * have the same values as the parameters. * * @param px starting x location * @param py starting y location * @param pw starting width * @param ph starting height * @return a rectangle which represents the placement and size of the popup */ protected Rectangle computePopupBounds(int px,int py,int pw,int ph) { Toolkit toolkit = Toolkit.getDefaultToolkit(); Rectangle screenBounds; // Calculate the desktop dimensions relative to the combo box. GraphicsConfiguration gc = comboBox.getGraphicsConfiguration(); Point p = new Point(); SwingUtilities.convertPointFromScreen(p, comboBox); if (gc != null) { Insets screenInsets = toolkit.getScreenInsets(gc); screenBounds = gc.getBounds(); screenBounds.width -= (screenInsets.left + screenInsets.right); screenBounds.height -= (screenInsets.top + screenInsets.bottom); screenBounds.x += (p.x + screenInsets.left); screenBounds.y += (p.y + screenInsets.top); } else { screenBounds = new Rectangle(p, toolkit.getScreenSize()); } Rectangle rect = new Rectangle(px,py,pw,ph); if (py+ph > screenBounds.y+screenBounds.height && ph < screenBounds.height) { rect.y = -rect.height; } return rect; } /** {@collect.stats} * Calculates the upper left location of the Popup. */ private Point getPopupLocation() { Dimension popupSize = comboBox.getSize(); Insets insets = getInsets(); // reduce the width of the scrollpane by the insets so that the popup // is the same width as the combo box. popupSize.setSize(popupSize.width - (insets.right + insets.left), getPopupHeightForRowCount( comboBox.getMaximumRowCount())); Rectangle popupBounds = computePopupBounds( 0, comboBox.getBounds().height, popupSize.width, popupSize.height); Dimension scrollSize = popupBounds.getSize(); Point popupLocation = popupBounds.getLocation(); scroller.setMaximumSize( scrollSize ); scroller.setPreferredSize( scrollSize ); scroller.setMinimumSize( scrollSize ); list.revalidate(); return popupLocation; } /** {@collect.stats} * A utility method used by the event listeners. Given a mouse event, it changes * the list selection to the list item below the mouse. */ protected void updateListBoxSelectionForEvent(MouseEvent anEvent,boolean shouldScroll) { // XXX - only seems to be called from this class. shouldScroll flag is // never true Point location = anEvent.getPoint(); if ( list == null ) return; int index = list.locationToIndex(location); if ( index == -1 ) { if ( location.y < 0 ) index = 0; else index = comboBox.getModel().getSize() - 1; } if ( list.getSelectedIndex() != index ) { list.setSelectedIndex(index); if ( shouldScroll ) list.ensureIndexIsVisible(index); } } // // end Utility methods //================================================================= }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import sun.swing.SwingUtilities2; import java.awt.*; import java.awt.event.*; import javax.accessibility.AccessibleContext; import javax.swing.*; import javax.swing.plaf.*; import javax.swing.border.*; import javax.swing.event.InternalFrameEvent; import java.util.EventListener; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.beans.VetoableChangeListener; import java.beans.PropertyVetoException; import sun.swing.DefaultLookup; import sun.swing.UIAction; /** {@collect.stats} * The class that manages a basic title bar * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author David Kloba * @author Steve Wilson */ public class BasicInternalFrameTitlePane extends JComponent { protected JMenuBar menuBar; protected JButton iconButton; protected JButton maxButton; protected JButton closeButton; protected JMenu windowMenu; protected JInternalFrame frame; protected Color selectedTitleColor; protected Color selectedTextColor; protected Color notSelectedTitleColor; protected Color notSelectedTextColor; protected Icon maxIcon; protected Icon minIcon; protected Icon iconIcon; protected Icon closeIcon; protected PropertyChangeListener propertyChangeListener; protected Action closeAction; protected Action maximizeAction; protected Action iconifyAction; protected Action restoreAction; protected Action moveAction; protected Action sizeAction; protected static final String CLOSE_CMD = UIManager.getString("InternalFrameTitlePane.closeButtonText"); protected static final String ICONIFY_CMD = UIManager.getString("InternalFrameTitlePane.minimizeButtonText"); protected static final String RESTORE_CMD = UIManager.getString("InternalFrameTitlePane.restoreButtonText"); protected static final String MAXIMIZE_CMD = UIManager.getString("InternalFrameTitlePane.maximizeButtonText"); protected static final String MOVE_CMD = UIManager.getString("InternalFrameTitlePane.moveButtonText"); protected static final String SIZE_CMD = UIManager.getString("InternalFrameTitlePane.sizeButtonText"); private String closeButtonToolTip; private String iconButtonToolTip; private String restoreButtonToolTip; private String maxButtonToolTip; private Handler handler; public BasicInternalFrameTitlePane(JInternalFrame f) { frame = f; installTitlePane(); } protected void installTitlePane() { installDefaults(); installListeners(); createActions(); enableActions(); createActionMap(); setLayout(createLayout()); assembleSystemMenu(); createButtons(); addSubComponents(); } protected void addSubComponents() { add(menuBar); add(iconButton); add(maxButton); add(closeButton); } protected void createActions() { maximizeAction = new MaximizeAction(); iconifyAction = new IconifyAction(); closeAction = new CloseAction(); restoreAction = new RestoreAction(); moveAction = new MoveAction(); sizeAction = new SizeAction(); } ActionMap createActionMap() { ActionMap map = new ActionMapUIResource(); map.put("showSystemMenu", new ShowSystemMenuAction(true)); map.put("hideSystemMenu", new ShowSystemMenuAction(false)); return map; } protected void installListeners() { if( propertyChangeListener == null ) { propertyChangeListener = createPropertyChangeListener(); } frame.addPropertyChangeListener(propertyChangeListener); } protected void uninstallListeners() { frame.removePropertyChangeListener(propertyChangeListener); handler = null; } protected void installDefaults() { maxIcon = UIManager.getIcon("InternalFrame.maximizeIcon"); minIcon = UIManager.getIcon("InternalFrame.minimizeIcon"); iconIcon = UIManager.getIcon("InternalFrame.iconifyIcon"); closeIcon = UIManager.getIcon("InternalFrame.closeIcon"); selectedTitleColor = UIManager.getColor("InternalFrame.activeTitleBackground"); selectedTextColor = UIManager.getColor("InternalFrame.activeTitleForeground"); notSelectedTitleColor = UIManager.getColor("InternalFrame.inactiveTitleBackground"); notSelectedTextColor = UIManager.getColor("InternalFrame.inactiveTitleForeground"); setFont(UIManager.getFont("InternalFrame.titleFont")); closeButtonToolTip = UIManager.getString("InternalFrame.closeButtonToolTip"); iconButtonToolTip = UIManager.getString("InternalFrame.iconButtonToolTip"); restoreButtonToolTip = UIManager.getString("InternalFrame.restoreButtonToolTip"); maxButtonToolTip = UIManager.getString("InternalFrame.maxButtonToolTip"); } protected void uninstallDefaults() { } protected void createButtons() { iconButton = new NoFocusButton( "InternalFrameTitlePane.iconifyButtonAccessibleName", "InternalFrameTitlePane.iconifyButtonOpacity"); iconButton.addActionListener(iconifyAction); if (iconButtonToolTip != null && iconButtonToolTip.length() != 0) { iconButton.setToolTipText(iconButtonToolTip); } maxButton = new NoFocusButton( "InternalFrameTitlePane.maximizeButtonAccessibleName", "InternalFrameTitlePane.maximizeButtonOpacity"); maxButton.addActionListener(maximizeAction); closeButton = new NoFocusButton( "InternalFrameTitlePane.closeButtonAccessibleName", "InternalFrameTitlePane.closeButtonOpacity"); closeButton.addActionListener(closeAction); if (closeButtonToolTip != null && closeButtonToolTip.length() != 0) { closeButton.setToolTipText(closeButtonToolTip); } setButtonIcons(); } protected void setButtonIcons() { if(frame.isIcon()) { if (minIcon != null) { iconButton.setIcon(minIcon); } if (restoreButtonToolTip != null && restoreButtonToolTip.length() != 0) { iconButton.setToolTipText(restoreButtonToolTip); } if (maxIcon != null) { maxButton.setIcon(maxIcon); } if (maxButtonToolTip != null && maxButtonToolTip.length() != 0) { maxButton.setToolTipText(maxButtonToolTip); } } else if (frame.isMaximum()) { if (iconIcon != null) { iconButton.setIcon(iconIcon); } if (iconButtonToolTip != null && iconButtonToolTip.length() != 0) { iconButton.setToolTipText(iconButtonToolTip); } if (minIcon != null) { maxButton.setIcon(minIcon); } if (restoreButtonToolTip != null && restoreButtonToolTip.length() != 0) { maxButton.setToolTipText(restoreButtonToolTip); } } else { if (iconIcon != null) { iconButton.setIcon(iconIcon); } if (iconButtonToolTip != null && iconButtonToolTip.length() != 0) { iconButton.setToolTipText(iconButtonToolTip); } if (maxIcon != null) { maxButton.setIcon(maxIcon); } if (maxButtonToolTip != null && maxButtonToolTip.length() != 0) { maxButton.setToolTipText(maxButtonToolTip); } } if (closeIcon != null) { closeButton.setIcon(closeIcon); } } protected void assembleSystemMenu() { menuBar = createSystemMenuBar(); windowMenu = createSystemMenu(); menuBar.add(windowMenu); addSystemMenuItems(windowMenu); enableActions(); } protected void addSystemMenuItems(JMenu systemMenu) { JMenuItem mi = (JMenuItem)systemMenu.add(restoreAction); mi.setMnemonic('R'); mi = (JMenuItem)systemMenu.add(moveAction); mi.setMnemonic('M'); mi = (JMenuItem)systemMenu.add(sizeAction); mi.setMnemonic('S'); mi = (JMenuItem)systemMenu.add(iconifyAction); mi.setMnemonic('n'); mi = (JMenuItem)systemMenu.add(maximizeAction); mi.setMnemonic('x'); systemMenu.add(new JSeparator()); mi = (JMenuItem)systemMenu.add(closeAction); mi.setMnemonic('C'); } protected JMenu createSystemMenu() { return new JMenu(" "); } protected JMenuBar createSystemMenuBar() { menuBar = new SystemMenuBar(); menuBar.setBorderPainted(false); return menuBar; } protected void showSystemMenu(){ // windowMenu.setPopupMenuVisible(true); // windowMenu.setVisible(true); windowMenu.doClick(); } public void paintComponent(Graphics g) { paintTitleBackground(g); if(frame.getTitle() != null) { boolean isSelected = frame.isSelected(); Font f = g.getFont(); g.setFont(getFont()); if(isSelected) g.setColor(selectedTextColor); else g.setColor(notSelectedTextColor); // Center text vertically. FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g); int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; int titleX; Rectangle r = new Rectangle(0, 0, 0, 0); if (frame.isIconifiable()) r = iconButton.getBounds(); else if (frame.isMaximizable()) r = maxButton.getBounds(); else if (frame.isClosable()) r = closeButton.getBounds(); int titleW; String title = frame.getTitle(); if( BasicGraphicsUtils.isLeftToRight(frame) ) { if (r.x == 0) r.x = frame.getWidth()-frame.getInsets().right; titleX = menuBar.getX() + menuBar.getWidth() + 2; titleW = r.x - titleX - 3; title = getTitle(frame.getTitle(), fm, titleW); } else { titleX = menuBar.getX() - 2 - SwingUtilities2.stringWidth(frame,fm,title); } SwingUtilities2.drawString(frame, g, title, titleX, baseline); g.setFont(f); } } /** {@collect.stats} * Invoked from paintComponent. * Paints the background of the titlepane. All text and icons will * then be rendered on top of this background. * @param g the graphics to use to render the background * @since 1.4 */ protected void paintTitleBackground(Graphics g) { boolean isSelected = frame.isSelected(); if(isSelected) g.setColor(selectedTitleColor); else g.setColor(notSelectedTitleColor); g.fillRect(0, 0, getWidth(), getHeight()); } protected String getTitle(String text, FontMetrics fm, int availTextWidth) { return SwingUtilities2.clipStringIfNecessary( frame, fm, text, availTextWidth); } /** {@collect.stats} * Post a WINDOW_CLOSING-like event to the frame, so that it can * be treated like a regular Frame. */ protected void postClosingEvent(JInternalFrame frame) { InternalFrameEvent e = new InternalFrameEvent( frame, InternalFrameEvent.INTERNAL_FRAME_CLOSING); // Try posting event, unless there's a SecurityManager. if (JInternalFrame.class.getClassLoader() == null) { try { Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(e); return; } catch (SecurityException se) { // Use dispatchEvent instead. } } frame.dispatchEvent(e); } protected void enableActions() { restoreAction.setEnabled(frame.isMaximum() || frame.isIcon()); maximizeAction.setEnabled( (frame.isMaximizable() && !frame.isMaximum() && !frame.isIcon()) || (frame.isMaximizable() && frame.isIcon())); iconifyAction.setEnabled(frame.isIconifiable() && !frame.isIcon()); closeAction.setEnabled(frame.isClosable()); sizeAction.setEnabled(false); moveAction.setEnabled(false); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } protected PropertyChangeListener createPropertyChangeListener() { return getHandler(); } protected LayoutManager createLayout() { return getHandler(); } private class Handler implements LayoutManager, PropertyChangeListener { // // PropertyChangeListener // public void propertyChange(PropertyChangeEvent evt) { String prop = (String)evt.getPropertyName(); if (prop == JInternalFrame.IS_SELECTED_PROPERTY) { repaint(); return; } if (prop == JInternalFrame.IS_ICON_PROPERTY || prop == JInternalFrame.IS_MAXIMUM_PROPERTY) { setButtonIcons(); enableActions(); return; } if ("closable" == prop) { if ((Boolean)evt.getNewValue() == Boolean.TRUE) { add(closeButton); } else { remove(closeButton); } } else if ("maximizable" == prop) { if ((Boolean)evt.getNewValue() == Boolean.TRUE) { add(maxButton); } else { remove(maxButton); } } else if ("iconable" == prop) { if ((Boolean)evt.getNewValue() == Boolean.TRUE) { add(iconButton); } else { remove(iconButton); } } enableActions(); revalidate(); repaint(); } // // LayoutManager // public void addLayoutComponent(String name, Component c) {} public void removeLayoutComponent(Component c) {} public Dimension preferredLayoutSize(Container c) { return minimumLayoutSize(c); } public Dimension minimumLayoutSize(Container c) { // Calculate width. int width = 22; if (frame.isClosable()) { width += 19; } if (frame.isMaximizable()) { width += 19; } if (frame.isIconifiable()) { width += 19; } FontMetrics fm = frame.getFontMetrics(getFont()); String frameTitle = frame.getTitle(); int title_w = frameTitle != null ? SwingUtilities2.stringWidth( frame, fm, frameTitle) : 0; int title_length = frameTitle != null ? frameTitle.length() : 0; // Leave room for three characters in the title. if (title_length > 3) { int subtitle_w = SwingUtilities2.stringWidth( frame, fm, frameTitle.substring(0, 3) + "..."); width += (title_w < subtitle_w) ? title_w : subtitle_w; } else { width += title_w; } // Calculate height. Icon icon = frame.getFrameIcon(); int fontHeight = fm.getHeight(); fontHeight += 2; int iconHeight = 0; if (icon != null) { // SystemMenuBar forces the icon to be 16x16 or less. iconHeight = Math.min(icon.getIconHeight(), 16); } iconHeight += 2; int height = Math.max( fontHeight, iconHeight ); Dimension dim = new Dimension(width, height); // Take into account the border insets if any. if (getBorder() != null) { Insets insets = getBorder().getBorderInsets(c); dim.height += insets.top + insets.bottom; dim.width += insets.left + insets.right; } return dim; } public void layoutContainer(Container c) { boolean leftToRight = BasicGraphicsUtils.isLeftToRight(frame); int w = getWidth(); int h = getHeight(); int x; int buttonHeight = closeButton.getIcon().getIconHeight(); Icon icon = frame.getFrameIcon(); int iconHeight = 0; if (icon != null) { iconHeight = icon.getIconHeight(); } x = (leftToRight) ? 2 : w - 16 - 2; menuBar.setBounds(x, (h - iconHeight) / 2, 16, 16); x = (leftToRight) ? w - 16 - 2 : 2; if (frame.isClosable()) { closeButton.setBounds(x, (h - buttonHeight) / 2, 16, 14); x += (leftToRight) ? -(16 + 2) : 16 + 2; } if (frame.isMaximizable()) { maxButton.setBounds(x, (h - buttonHeight) / 2, 16, 14); x += (leftToRight) ? -(16 + 2) : 16 + 2; } if (frame.isIconifiable()) { iconButton.setBounds(x, (h - buttonHeight) / 2, 16, 14); } } } /** {@collect.stats} * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of <Foo>. */ public class PropertyChangeHandler implements PropertyChangeListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void propertyChange(PropertyChangeEvent evt) { getHandler().propertyChange(evt); } } /** {@collect.stats} * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of <Foo>. */ public class TitlePaneLayout implements LayoutManager { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void addLayoutComponent(String name, Component c) { getHandler().addLayoutComponent(name, c); } public void removeLayoutComponent(Component c) { getHandler().removeLayoutComponent(c); } public Dimension preferredLayoutSize(Container c) { return getHandler().preferredLayoutSize(c); } public Dimension minimumLayoutSize(Container c) { return getHandler().minimumLayoutSize(c); } public void layoutContainer(Container c) { getHandler().layoutContainer(c); } } /** {@collect.stats} * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of <Foo>. */ public class CloseAction extends AbstractAction { public CloseAction() { super(CLOSE_CMD); } public void actionPerformed(ActionEvent e) { if(frame.isClosable()) { frame.doDefaultCloseAction(); } } } // end CloseAction /** {@collect.stats} * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of <Foo>. */ public class MaximizeAction extends AbstractAction { public MaximizeAction() { super(MAXIMIZE_CMD); } public void actionPerformed(ActionEvent evt) { if (frame.isMaximizable()) { if (frame.isMaximum() && frame.isIcon()) { try { frame.setIcon(false); } catch (PropertyVetoException e) { } } else if (!frame.isMaximum()) { try { frame.setMaximum(true); } catch (PropertyVetoException e) { } } else { try { frame.setMaximum(false); } catch (PropertyVetoException e) { } } } } } /** {@collect.stats} * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of <Foo>. */ public class IconifyAction extends AbstractAction { public IconifyAction() { super(ICONIFY_CMD); } public void actionPerformed(ActionEvent e) { if(frame.isIconifiable()) { if(!frame.isIcon()) { try { frame.setIcon(true); } catch (PropertyVetoException e1) { } } else{ try { frame.setIcon(false); } catch (PropertyVetoException e1) { } } } } } // end IconifyAction /** {@collect.stats} * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of <Foo>. */ public class RestoreAction extends AbstractAction { public RestoreAction() { super(RESTORE_CMD); } public void actionPerformed(ActionEvent evt) { if (frame.isMaximizable() && frame.isMaximum() && frame.isIcon()) { try { frame.setIcon(false); } catch (PropertyVetoException e) { } } else if (frame.isMaximizable() && frame.isMaximum()) { try { frame.setMaximum(false); } catch (PropertyVetoException e) { } } else if (frame.isIconifiable() && frame.isIcon()) { try { frame.setIcon(false); } catch (PropertyVetoException e) { } } } } /** {@collect.stats} * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of <Foo>. */ public class MoveAction extends AbstractAction { public MoveAction() { super(MOVE_CMD); } public void actionPerformed(ActionEvent e) { // This action is currently undefined } } // end MoveAction /* * Handles showing and hiding the system menu. */ private class ShowSystemMenuAction extends AbstractAction { private boolean show; // whether to show the menu public ShowSystemMenuAction(boolean show) { this.show = show; } public void actionPerformed(ActionEvent e) { if (show) { windowMenu.doClick(); } else { windowMenu.setVisible(false); } } } /** {@collect.stats} * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of <Foo>. */ public class SizeAction extends AbstractAction { public SizeAction() { super(SIZE_CMD); } public void actionPerformed(ActionEvent e) { // This action is currently undefined } } // end SizeAction /** {@collect.stats} * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of <Foo>. */ public class SystemMenuBar extends JMenuBar { public boolean isFocusTraversable() { return false; } public void requestFocus() {} public void paint(Graphics g) { Icon icon = frame.getFrameIcon(); if (icon == null) { icon = (Icon)DefaultLookup.get(frame, frame.getUI(), "InternalFrame.icon"); } if (icon != null) { // Resize to 16x16 if necessary. if (icon instanceof ImageIcon && (icon.getIconWidth() > 16 || icon.getIconHeight() > 16)) { Image img = ((ImageIcon)icon).getImage(); ((ImageIcon)icon).setImage(img.getScaledInstance(16, 16, Image.SCALE_SMOOTH)); } icon.paintIcon(this, g, 0, 0); } } public boolean isOpaque() { return true; } } // end SystemMenuBar private class NoFocusButton extends JButton { private String uiKey; public NoFocusButton(String uiKey, String opacityKey) { setFocusPainted(false); setMargin(new Insets(0,0,0,0)); this.uiKey = uiKey; Object opacity = UIManager.get(opacityKey); if (opacity instanceof Boolean) { setOpaque(((Boolean)opacity).booleanValue()); } } public boolean isFocusTraversable() { return false; } public void requestFocus() {}; public AccessibleContext getAccessibleContext() { AccessibleContext ac = super.getAccessibleContext(); if (uiKey != null) { ac.setAccessibleName(UIManager.getString(uiKey)); uiKey = null; } return ac; } }; // end NoFocusButton } // End Title Pane Class
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.swing.*; import javax.swing.plaf.*; import java.beans.*; import java.awt.event.*; import java.awt.Dimension; import java.awt.Insets; import java.awt.Graphics; import java.awt.KeyboardFocusManager; import java.awt.*; import java.util.Vector; import sun.swing.DefaultLookup; import sun.swing.UIAction; import sun.awt.AppContext; /** {@collect.stats} * Basic L&F for a desktop. * * @author Steve Wilson */ public class BasicDesktopPaneUI extends DesktopPaneUI { // Old actions forward to an instance of this. private static final Actions SHARED_ACTION = new Actions(); private static Dimension minSize = new Dimension(0,0); private static Dimension maxSize = new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); private Handler handler; private PropertyChangeListener pcl; protected JDesktopPane desktop; protected DesktopManager desktopManager; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of 1.3. */ @Deprecated protected KeyStroke minimizeKey; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of 1.3. */ @Deprecated protected KeyStroke maximizeKey; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of 1.3. */ @Deprecated protected KeyStroke closeKey; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of 1.3. */ @Deprecated protected KeyStroke navigateKey; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of 1.3. */ @Deprecated protected KeyStroke navigateKey2; public static ComponentUI createUI(JComponent c) { return new BasicDesktopPaneUI(); } public BasicDesktopPaneUI() { } public void installUI(JComponent c) { desktop = (JDesktopPane)c; installDefaults(); installDesktopManager(); installListeners(); installKeyboardActions(); } public void uninstallUI(JComponent c) { uninstallKeyboardActions(); uninstallListeners(); uninstallDesktopManager(); uninstallDefaults(); desktop = null; handler = null; } protected void installDefaults() { if (desktop.getBackground() == null || desktop.getBackground() instanceof UIResource) { desktop.setBackground(UIManager.getColor("Desktop.background")); } LookAndFeel.installProperty(desktop, "opaque", Boolean.TRUE); } protected void uninstallDefaults() { } /** {@collect.stats} * Installs the <code>PropertyChangeListener</code> returned from * <code>createPropertyChangeListener</code> on the * <code>JDesktopPane</code>. * * @since 1.5 * @see #createPropertyChangeListener */ protected void installListeners() { pcl = createPropertyChangeListener(); desktop.addPropertyChangeListener(pcl); } /** {@collect.stats} * Uninstalls the <code>PropertyChangeListener</code> returned from * <code>createPropertyChangeListener</code> from the * <code>JDesktopPane</code>. * * @since 1.5 * @see #createPropertyChangeListener */ protected void uninstallListeners() { desktop.removePropertyChangeListener(pcl); pcl = null; } protected void installDesktopManager() { desktopManager = desktop.getDesktopManager(); if(desktopManager == null) { desktopManager = new BasicDesktopManager(); desktop.setDesktopManager(desktopManager); } } protected void uninstallDesktopManager() { if(desktop.getDesktopManager() instanceof UIResource) { desktop.setDesktopManager(null); } desktopManager = null; } protected void installKeyboardActions(){ InputMap inputMap = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); if (inputMap != null) { SwingUtilities.replaceUIInputMap(desktop, JComponent.WHEN_IN_FOCUSED_WINDOW, inputMap); } inputMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); if (inputMap != null) { SwingUtilities.replaceUIInputMap(desktop, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, inputMap); } LazyActionMap.installLazyActionMap(desktop, BasicDesktopPaneUI.class, "DesktopPane.actionMap"); registerKeyboardActions(); } protected void registerKeyboardActions(){ } protected void unregisterKeyboardActions(){ } InputMap getInputMap(int condition) { if (condition == JComponent.WHEN_IN_FOCUSED_WINDOW) { return createInputMap(condition); } else if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) { return (InputMap)DefaultLookup.get(desktop, this, "Desktop.ancestorInputMap"); } return null; } InputMap createInputMap(int condition) { if (condition == JComponent.WHEN_IN_FOCUSED_WINDOW) { Object[] bindings = (Object[])DefaultLookup.get(desktop, this, "Desktop.windowBindings"); if (bindings != null) { return LookAndFeel.makeComponentInputMap(desktop, bindings); } } return null; } static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.RESTORE)); map.put(new Actions(Actions.CLOSE)); map.put(new Actions(Actions.MOVE)); map.put(new Actions(Actions.RESIZE)); map.put(new Actions(Actions.LEFT)); map.put(new Actions(Actions.SHRINK_LEFT)); map.put(new Actions(Actions.RIGHT)); map.put(new Actions(Actions.SHRINK_RIGHT)); map.put(new Actions(Actions.UP)); map.put(new Actions(Actions.SHRINK_UP)); map.put(new Actions(Actions.DOWN)); map.put(new Actions(Actions.SHRINK_DOWN)); map.put(new Actions(Actions.ESCAPE)); map.put(new Actions(Actions.MINIMIZE)); map.put(new Actions(Actions.MAXIMIZE)); map.put(new Actions(Actions.NEXT_FRAME)); map.put(new Actions(Actions.PREVIOUS_FRAME)); map.put(new Actions(Actions.NAVIGATE_NEXT)); map.put(new Actions(Actions.NAVIGATE_PREVIOUS)); } protected void uninstallKeyboardActions(){ unregisterKeyboardActions(); SwingUtilities.replaceUIInputMap(desktop, JComponent. WHEN_IN_FOCUSED_WINDOW, null); SwingUtilities.replaceUIInputMap(desktop, JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null); SwingUtilities.replaceUIActionMap(desktop, null); } public void paint(Graphics g, JComponent c) {} public Dimension getPreferredSize(JComponent c) {return null;} public Dimension getMinimumSize(JComponent c) { return minSize; } public Dimension getMaximumSize(JComponent c){ return maxSize; } /** {@collect.stats} * Returns the <code>PropertyChangeListener</code> to install on * the <code>JDesktopPane</code>. * * @since 1.5 * @return The PropertyChangeListener that will be added to track * changes in the desktop pane. */ protected PropertyChangeListener createPropertyChangeListener() { return getHandler(); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } private class Handler implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if ("desktopManager" == propertyName) { installDesktopManager(); } } } /** {@collect.stats} * The default DesktopManager installed by the UI. */ private class BasicDesktopManager extends DefaultDesktopManager implements UIResource { } private static class Actions extends UIAction { private static String CLOSE = "close"; private static String ESCAPE = "escape"; private static String MAXIMIZE = "maximize"; private static String MINIMIZE = "minimize"; private static String MOVE = "move"; private static String RESIZE = "resize"; private static String RESTORE = "restore"; private static String LEFT = "left"; private static String RIGHT = "right"; private static String UP = "up"; private static String DOWN = "down"; private static String SHRINK_LEFT = "shrinkLeft"; private static String SHRINK_RIGHT = "shrinkRight"; private static String SHRINK_UP = "shrinkUp"; private static String SHRINK_DOWN = "shrinkDown"; private static String NEXT_FRAME = "selectNextFrame"; private static String PREVIOUS_FRAME = "selectPreviousFrame"; private static String NAVIGATE_NEXT = "navigateNext"; private static String NAVIGATE_PREVIOUS = "navigatePrevious"; private final int MOVE_RESIZE_INCREMENT = 10; private static boolean moving = false; private static boolean resizing = false; private static JInternalFrame sourceFrame = null; private static Component focusOwner = null; Actions() { super(null); } Actions(String name) { super(name); } public void actionPerformed(ActionEvent e) { JDesktopPane dp = (JDesktopPane)e.getSource(); String key = getName(); if (CLOSE == key || MAXIMIZE == key || MINIMIZE == key || RESTORE == key) { setState(dp, key); } else if (ESCAPE == key) { if (sourceFrame == dp.getSelectedFrame() && focusOwner != null) { focusOwner.requestFocus(); } moving = false; resizing = false; sourceFrame = null; focusOwner = null; } else if (MOVE == key || RESIZE == key) { sourceFrame = dp.getSelectedFrame(); if (sourceFrame == null) { return; } moving = (key == MOVE) ? true : false; resizing = (key == RESIZE) ? true : false; focusOwner = KeyboardFocusManager. getCurrentKeyboardFocusManager().getFocusOwner(); if (!SwingUtilities.isDescendingFrom(focusOwner, sourceFrame)) { focusOwner = null; } sourceFrame.requestFocus(); } else if (LEFT == key || RIGHT == key || UP == key || DOWN == key || SHRINK_RIGHT == key || SHRINK_LEFT == key || SHRINK_UP == key || SHRINK_DOWN == key) { JInternalFrame c = dp.getSelectedFrame(); if (sourceFrame == null || c != sourceFrame || KeyboardFocusManager. getCurrentKeyboardFocusManager().getFocusOwner() != sourceFrame) { return; } Insets minOnScreenInsets = UIManager.getInsets("Desktop.minOnScreenInsets"); Dimension size = c.getSize(); Dimension minSize = c.getMinimumSize(); int dpWidth = dp.getWidth(); int dpHeight = dp.getHeight(); int delta; Point loc = c.getLocation(); if (LEFT == key) { if (moving) { c.setLocation( loc.x + size.width - MOVE_RESIZE_INCREMENT < minOnScreenInsets.right ? -size.width + minOnScreenInsets.right : loc.x - MOVE_RESIZE_INCREMENT, loc.y); } else if (resizing) { c.setLocation(loc.x - MOVE_RESIZE_INCREMENT, loc.y); c.setSize(size.width + MOVE_RESIZE_INCREMENT, size.height); } } else if (RIGHT == key) { if (moving) { c.setLocation( loc.x + MOVE_RESIZE_INCREMENT > dpWidth - minOnScreenInsets.left ? dpWidth - minOnScreenInsets.left : loc.x + MOVE_RESIZE_INCREMENT, loc.y); } else if (resizing) { c.setSize(size.width + MOVE_RESIZE_INCREMENT, size.height); } } else if (UP == key) { if (moving) { c.setLocation(loc.x, loc.y + size.height - MOVE_RESIZE_INCREMENT < minOnScreenInsets.bottom ? -size.height + minOnScreenInsets.bottom : loc.y - MOVE_RESIZE_INCREMENT); } else if (resizing) { c.setLocation(loc.x, loc.y - MOVE_RESIZE_INCREMENT); c.setSize(size.width, size.height + MOVE_RESIZE_INCREMENT); } } else if (DOWN == key) { if (moving) { c.setLocation(loc.x, loc.y + MOVE_RESIZE_INCREMENT > dpHeight - minOnScreenInsets.top ? dpHeight - minOnScreenInsets.top : loc.y + MOVE_RESIZE_INCREMENT); } else if (resizing) { c.setSize(size.width, size.height + MOVE_RESIZE_INCREMENT); } } else if (SHRINK_LEFT == key && resizing) { // Make sure we don't resize less than minimum size. if (minSize.width < (size.width - MOVE_RESIZE_INCREMENT)) { delta = MOVE_RESIZE_INCREMENT; } else { delta = size.width - minSize.width; } // Ensure that we keep the internal frame on the desktop. if (loc.x + size.width - delta < minOnScreenInsets.left) { delta = loc.x + size.width - minOnScreenInsets.left; } c.setSize(size.width - delta, size.height); } else if (SHRINK_RIGHT == key && resizing) { // Make sure we don't resize less than minimum size. if (minSize.width < (size.width - MOVE_RESIZE_INCREMENT)) { delta = MOVE_RESIZE_INCREMENT; } else { delta = size.width - minSize.width; } // Ensure that we keep the internal frame on the desktop. if (loc.x + delta > dpWidth - minOnScreenInsets.right) { delta = (dpWidth - minOnScreenInsets.right) - loc.x; } c.setLocation(loc.x + delta, loc.y); c.setSize(size.width - delta, size.height); } else if (SHRINK_UP == key && resizing) { // Make sure we don't resize less than minimum size. if (minSize.height < (size.height - MOVE_RESIZE_INCREMENT)) { delta = MOVE_RESIZE_INCREMENT; } else { delta = size.height - minSize.height; } // Ensure that we keep the internal frame on the desktop. if (loc.y + size.height - delta < minOnScreenInsets.bottom) { delta = loc.y + size.height - minOnScreenInsets.bottom; } c.setSize(size.width, size.height - delta); } else if (SHRINK_DOWN == key && resizing) { // Make sure we don't resize less than minimum size. if (minSize.height < (size.height - MOVE_RESIZE_INCREMENT)) { delta = MOVE_RESIZE_INCREMENT; } else { delta = size.height - minSize.height; } // Ensure that we keep the internal frame on the desktop. if (loc.y + delta > dpHeight - minOnScreenInsets.top) { delta = (dpHeight - minOnScreenInsets.top) - loc.y; } c.setLocation(loc.x, loc.y + delta); c.setSize(size.width, size.height - delta); } } else if (NEXT_FRAME == key || PREVIOUS_FRAME == key) { dp.selectFrame((key == NEXT_FRAME) ? true : false); } else if (NAVIGATE_NEXT == key || NAVIGATE_PREVIOUS == key) { boolean moveForward = true; if (NAVIGATE_PREVIOUS == key) { moveForward = false; } Container cycleRoot = dp.getFocusCycleRootAncestor(); if (cycleRoot != null) { FocusTraversalPolicy policy = cycleRoot.getFocusTraversalPolicy(); if (policy != null && policy instanceof SortingFocusTraversalPolicy) { SortingFocusTraversalPolicy sPolicy = (SortingFocusTraversalPolicy)policy; boolean idc = sPolicy.getImplicitDownCycleTraversal(); try { sPolicy.setImplicitDownCycleTraversal(false); if (moveForward) { KeyboardFocusManager. getCurrentKeyboardFocusManager(). focusNextComponent(dp); } else { KeyboardFocusManager. getCurrentKeyboardFocusManager(). focusPreviousComponent(dp); } } finally { sPolicy.setImplicitDownCycleTraversal(idc); } } } } } private void setState(JDesktopPane dp, String state) { if (state == CLOSE) { JInternalFrame f = dp.getSelectedFrame(); if (f == null) { return; } f.doDefaultCloseAction(); } else if (state == MAXIMIZE) { // maximize the selected frame JInternalFrame f = dp.getSelectedFrame(); if (f == null) { return; } if (!f.isMaximum()) { if (f.isIcon()) { try { f.setIcon(false); f.setMaximum(true); } catch (PropertyVetoException pve) {} } else { try { f.setMaximum(true); } catch (PropertyVetoException pve) { } } } } else if (state == MINIMIZE) { // minimize the selected frame JInternalFrame f = dp.getSelectedFrame(); if (f == null) { return; } if (!f.isIcon()) { try { f.setIcon(true); } catch (PropertyVetoException pve) { } } } else if (state == RESTORE) { // restore the selected minimized or maximized frame JInternalFrame f = dp.getSelectedFrame(); if (f == null) { return; } try { if (f.isIcon()) { f.setIcon(false); } else if (f.isMaximum()) { f.setMaximum(false); } f.setSelected(true); } catch (PropertyVetoException pve) { } } } public boolean isEnabled(Object sender) { if (sender instanceof JDesktopPane) { JDesktopPane dp = (JDesktopPane)sender; String action = getName(); if (action == Actions.NEXT_FRAME || action == Actions.PREVIOUS_FRAME) { return true; } JInternalFrame iFrame = dp.getSelectedFrame(); if (iFrame == null) { return false; } else if (action == Actions.CLOSE) { return iFrame.isClosable(); } else if (action == Actions.MINIMIZE) { return iFrame.isIconifiable(); } else if (action == Actions.MAXIMIZE) { return iFrame.isMaximizable(); } return true; } return false; } } /** {@collect.stats} * Handles restoring a minimized or maximized internal frame. * @since 1.3 */ protected class OpenAction extends AbstractAction { public void actionPerformed(ActionEvent evt) { JDesktopPane dp = (JDesktopPane)evt.getSource(); SHARED_ACTION.setState(dp, Actions.RESTORE); } public boolean isEnabled() { return true; } } /** {@collect.stats} * Handles closing an internal frame. */ protected class CloseAction extends AbstractAction { public void actionPerformed(ActionEvent evt) { JDesktopPane dp = (JDesktopPane)evt.getSource(); SHARED_ACTION.setState(dp, Actions.CLOSE); } public boolean isEnabled() { JInternalFrame iFrame = desktop.getSelectedFrame(); if (iFrame != null) { return iFrame.isClosable(); } return false; } } /** {@collect.stats} * Handles minimizing an internal frame. */ protected class MinimizeAction extends AbstractAction { public void actionPerformed(ActionEvent evt) { JDesktopPane dp = (JDesktopPane)evt.getSource(); SHARED_ACTION.setState(dp, Actions.MINIMIZE); } public boolean isEnabled() { JInternalFrame iFrame = desktop.getSelectedFrame(); if (iFrame != null) { return iFrame.isIconifiable(); } return false; } } /** {@collect.stats} * Handles maximizing an internal frame. */ protected class MaximizeAction extends AbstractAction { public void actionPerformed(ActionEvent evt) { JDesktopPane dp = (JDesktopPane)evt.getSource(); SHARED_ACTION.setState(dp, Actions.MAXIMIZE); } public boolean isEnabled() { JInternalFrame iFrame = desktop.getSelectedFrame(); if (iFrame != null) { return iFrame.isMaximizable(); } return false; } } /** {@collect.stats} * Handles navigating to the next internal frame. */ protected class NavigateAction extends AbstractAction { public void actionPerformed(ActionEvent evt) { JDesktopPane dp = (JDesktopPane)evt.getSource(); dp.selectFrame(true); } public boolean isEnabled() { return true; } } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.*; import javax.swing.border.Border; import java.beans.*; import sun.swing.DefaultLookup; /** {@collect.stats} * Divider used by BasicSplitPaneUI. Subclassers may wish to override * paint to do something more interesting. * The border effect is drawn in BasicSplitPaneUI, so if you don't like * that border, reset it there. * To conditionally drag from certain areas subclass mousePressed and * call super when you wish the dragging to begin. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Scott Violet */ public class BasicSplitPaneDivider extends Container implements PropertyChangeListener { /** {@collect.stats} * Width or height of the divider based on orientation * BasicSplitPaneUI adds two to this. */ protected static final int ONE_TOUCH_SIZE = 6; protected static final int ONE_TOUCH_OFFSET = 2; /** {@collect.stats} * Handles mouse dragging message to do the actual dragging. */ protected DragController dragger; /** {@collect.stats} * UI this instance was created from. */ protected BasicSplitPaneUI splitPaneUI; /** {@collect.stats} * Size of the divider. */ protected int dividerSize = 0; // default - SET TO 0??? /** {@collect.stats} * Divider that is used for noncontinuous layout mode. */ protected Component hiddenDivider; /** {@collect.stats} * JSplitPane the receiver is contained in. */ protected JSplitPane splitPane; /** {@collect.stats} * Handles mouse events from both this class, and the split pane. * Mouse events are handled for the splitpane since you want to be able * to drag when clicking on the border of the divider, which is not * drawn by the divider. */ protected MouseHandler mouseHandler; /** {@collect.stats} * Orientation of the JSplitPane. */ protected int orientation; /** {@collect.stats} * Button for quickly toggling the left component. */ protected JButton leftButton; /** {@collect.stats} * Button for quickly toggling the right component. */ protected JButton rightButton; /** {@collect.stats} Border. */ private Border border; /** {@collect.stats} * Is the mouse over the divider? */ private boolean mouseOver; private int oneTouchSize; private int oneTouchOffset; /** {@collect.stats} * If true the one touch buttons are centered on the divider. */ private boolean centerOneTouchButtons; /** {@collect.stats} * Creates an instance of BasicSplitPaneDivider. Registers this * instance for mouse events and mouse dragged events. */ public BasicSplitPaneDivider(BasicSplitPaneUI ui) { oneTouchSize = DefaultLookup.getInt(ui.getSplitPane(), ui, "SplitPane.oneTouchButtonSize", ONE_TOUCH_SIZE); oneTouchOffset = DefaultLookup.getInt(ui.getSplitPane(), ui, "SplitPane.oneTouchButtonOffset", ONE_TOUCH_OFFSET); centerOneTouchButtons = DefaultLookup.getBoolean(ui.getSplitPane(), ui, "SplitPane.centerOneTouchButtons", true); setLayout(new DividerLayout()); setBasicSplitPaneUI(ui); orientation = splitPane.getOrientation(); setCursor((orientation == JSplitPane.HORIZONTAL_SPLIT) ? Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR) : Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)); setBackground(UIManager.getColor("SplitPane.background")); } private void revalidate() { invalidate(); if (splitPane != null) { splitPane.revalidate(); } } /** {@collect.stats} * Sets the SplitPaneUI that is using the receiver. */ public void setBasicSplitPaneUI(BasicSplitPaneUI newUI) { if (splitPane != null) { splitPane.removePropertyChangeListener(this); if (mouseHandler != null) { splitPane.removeMouseListener(mouseHandler); splitPane.removeMouseMotionListener(mouseHandler); removeMouseListener(mouseHandler); removeMouseMotionListener(mouseHandler); mouseHandler = null; } } splitPaneUI = newUI; if (newUI != null) { splitPane = newUI.getSplitPane(); if (splitPane != null) { if (mouseHandler == null) mouseHandler = new MouseHandler(); splitPane.addMouseListener(mouseHandler); splitPane.addMouseMotionListener(mouseHandler); addMouseListener(mouseHandler); addMouseMotionListener(mouseHandler); splitPane.addPropertyChangeListener(this); if (splitPane.isOneTouchExpandable()) { oneTouchExpandableChanged(); } } } else { splitPane = null; } } /** {@collect.stats} * Returns the <code>SplitPaneUI</code> the receiver is currently * in. */ public BasicSplitPaneUI getBasicSplitPaneUI() { return splitPaneUI; } /** {@collect.stats} * Sets the size of the divider to <code>newSize</code>. That is * the width if the splitpane is <code>HORIZONTAL_SPLIT</code>, or * the height of <code>VERTICAL_SPLIT</code>. */ public void setDividerSize(int newSize) { dividerSize = newSize; } /** {@collect.stats} * Returns the size of the divider, that is the width if the splitpane * is HORIZONTAL_SPLIT, or the height of VERTICAL_SPLIT. */ public int getDividerSize() { return dividerSize; } /** {@collect.stats} * Sets the border of this component. * @since 1.3 */ public void setBorder(Border border) { Border oldBorder = this.border; this.border = border; } /** {@collect.stats} * Returns the border of this component or null if no border is * currently set. * * @return the border object for this component * @see #setBorder * @since 1.3 */ public Border getBorder() { return border; } /** {@collect.stats} * If a border has been set on this component, returns the * border's insets, else calls super.getInsets. * * @return the value of the insets property. * @see #setBorder */ public Insets getInsets() { Border border = getBorder(); if (border != null) { return border.getBorderInsets(this); } return super.getInsets(); } /** {@collect.stats} * Sets whether or not the mouse is currently over the divider. * * @param mouseOver whether or not the mouse is currently over the divider * @since 1.5 */ protected void setMouseOver(boolean mouseOver) { this.mouseOver = mouseOver; } /** {@collect.stats} * Returns whether or not the mouse is currently over the divider * * @return whether or not the mouse is currently over the divider * @since 1.5 */ public boolean isMouseOver() { return mouseOver; } /** {@collect.stats} * Returns dividerSize x dividerSize */ public Dimension getPreferredSize() { // Ideally this would return the size from the layout manager, // but that could result in the layed out size being different from // the dividerSize, which may break developers as well as // BasicSplitPaneUI. if (orientation == JSplitPane.HORIZONTAL_SPLIT) { return new Dimension(getDividerSize(), 1); } return new Dimension(1, getDividerSize()); } /** {@collect.stats} * Returns dividerSize x dividerSize */ public Dimension getMinimumSize() { return getPreferredSize(); } /** {@collect.stats} * Property change event, presumably from the JSplitPane, will message * updateOrientation if necessary. */ public void propertyChange(PropertyChangeEvent e) { if (e.getSource() == splitPane) { if (e.getPropertyName() == JSplitPane.ORIENTATION_PROPERTY) { orientation = splitPane.getOrientation(); setCursor((orientation == JSplitPane.HORIZONTAL_SPLIT) ? Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR) : Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)); revalidate(); } else if (e.getPropertyName() == JSplitPane. ONE_TOUCH_EXPANDABLE_PROPERTY) { oneTouchExpandableChanged(); } } } /** {@collect.stats} * Paints the divider. */ public void paint(Graphics g) { super.paint(g); // Paint the border. Border border = getBorder(); if (border != null) { Dimension size = getSize(); border.paintBorder(this, g, 0, 0, size.width, size.height); } } /** {@collect.stats} * Messaged when the oneTouchExpandable value of the JSplitPane the * receiver is contained in changes. Will create the * <code>leftButton</code> and <code>rightButton</code> if they * are null. invalidates the receiver as well. */ protected void oneTouchExpandableChanged() { if (!DefaultLookup.getBoolean(splitPane, splitPaneUI, "SplitPane.supportsOneTouchButtons", true)) { // Look and feel doesn't want to support one touch buttons, bail. return; } if (splitPane.isOneTouchExpandable() && leftButton == null && rightButton == null) { /* Create the left button and add an action listener to expand/collapse it. */ leftButton = createLeftOneTouchButton(); if (leftButton != null) leftButton.addActionListener(new OneTouchActionHandler(true)); /* Create the right button and add an action listener to expand/collapse it. */ rightButton = createRightOneTouchButton(); if (rightButton != null) rightButton.addActionListener(new OneTouchActionHandler (false)); if (leftButton != null && rightButton != null) { add(leftButton); add(rightButton); } } revalidate(); } /** {@collect.stats} * Creates and return an instance of JButton that can be used to * collapse the left component in the split pane. */ protected JButton createLeftOneTouchButton() { JButton b = new JButton() { public void setBorder(Border b) { } public void paint(Graphics g) { if (splitPane != null) { int[] xs = new int[3]; int[] ys = new int[3]; int blockSize; // Fill the background first ... g.setColor(this.getBackground()); g.fillRect(0, 0, this.getWidth(), this.getHeight()); // ... then draw the arrow. g.setColor(Color.black); if (orientation == JSplitPane.VERTICAL_SPLIT) { blockSize = Math.min(getHeight(), oneTouchSize); xs[0] = blockSize; xs[1] = 0; xs[2] = blockSize << 1; ys[0] = 0; ys[1] = ys[2] = blockSize; g.drawPolygon(xs, ys, 3); // Little trick to make the // arrows of equal size } else { blockSize = Math.min(getWidth(), oneTouchSize); xs[0] = xs[2] = blockSize; xs[1] = 0; ys[0] = 0; ys[1] = blockSize; ys[2] = blockSize << 1; } g.fillPolygon(xs, ys, 3); } } // Don't want the button to participate in focus traversable. public boolean isFocusTraversable() { return false; } }; b.setMinimumSize(new Dimension(oneTouchSize, oneTouchSize)); b.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); b.setFocusPainted(false); b.setBorderPainted(false); b.setRequestFocusEnabled(false); return b; } /** {@collect.stats} * Creates and return an instance of JButton that can be used to * collapse the right component in the split pane. */ protected JButton createRightOneTouchButton() { JButton b = new JButton() { public void setBorder(Border border) { } public void paint(Graphics g) { if (splitPane != null) { int[] xs = new int[3]; int[] ys = new int[3]; int blockSize; // Fill the background first ... g.setColor(this.getBackground()); g.fillRect(0, 0, this.getWidth(), this.getHeight()); // ... then draw the arrow. if (orientation == JSplitPane.VERTICAL_SPLIT) { blockSize = Math.min(getHeight(), oneTouchSize); xs[0] = blockSize; xs[1] = blockSize << 1; xs[2] = 0; ys[0] = blockSize; ys[1] = ys[2] = 0; } else { blockSize = Math.min(getWidth(), oneTouchSize); xs[0] = xs[2] = 0; xs[1] = blockSize; ys[0] = 0; ys[1] = blockSize; ys[2] = blockSize << 1; } g.setColor(Color.black); g.fillPolygon(xs, ys, 3); } } // Don't want the button to participate in focus traversable. public boolean isFocusTraversable() { return false; } }; b.setMinimumSize(new Dimension(oneTouchSize, oneTouchSize)); b.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); b.setFocusPainted(false); b.setBorderPainted(false); b.setRequestFocusEnabled(false); return b; } /** {@collect.stats} * Message to prepare for dragging. This messages the BasicSplitPaneUI * with startDragging. */ protected void prepareForDragging() { splitPaneUI.startDragging(); } /** {@collect.stats} * Messages the BasicSplitPaneUI with dragDividerTo that this instance * is contained in. */ protected void dragDividerTo(int location) { splitPaneUI.dragDividerTo(location); } /** {@collect.stats} * Messages the BasicSplitPaneUI with finishDraggingTo that this instance * is contained in. */ protected void finishDraggingTo(int location) { splitPaneUI.finishDraggingTo(location); } /** {@collect.stats} * MouseHandler is responsible for converting mouse events * (released, dragged...) into the appropriate DragController * methods. * <p> */ protected class MouseHandler extends MouseAdapter implements MouseMotionListener { /** {@collect.stats} * Starts the dragging session by creating the appropriate instance * of DragController. */ public void mousePressed(MouseEvent e) { if ((e.getSource() == BasicSplitPaneDivider.this || e.getSource() == splitPane) && dragger == null &&splitPane.isEnabled()) { Component newHiddenDivider = splitPaneUI. getNonContinuousLayoutDivider(); if (hiddenDivider != newHiddenDivider) { if (hiddenDivider != null) { hiddenDivider.removeMouseListener(this); hiddenDivider.removeMouseMotionListener(this); } hiddenDivider = newHiddenDivider; if (hiddenDivider != null) { hiddenDivider.addMouseMotionListener(this); hiddenDivider.addMouseListener(this); } } if (splitPane.getLeftComponent() != null && splitPane.getRightComponent() != null) { if (orientation == JSplitPane.HORIZONTAL_SPLIT) { dragger = new DragController(e); } else { dragger = new VerticalDragController(e); } if (!dragger.isValid()) { dragger = null; } else { prepareForDragging(); dragger.continueDrag(e); } } e.consume(); } } /** {@collect.stats} * If dragger is not null it is messaged with completeDrag. */ public void mouseReleased(MouseEvent e) { if (dragger != null) { if (e.getSource() == splitPane) { dragger.completeDrag(e.getX(), e.getY()); } else if (e.getSource() == BasicSplitPaneDivider.this) { Point ourLoc = getLocation(); dragger.completeDrag(e.getX() + ourLoc.x, e.getY() + ourLoc.y); } else if (e.getSource() == hiddenDivider) { Point hDividerLoc = hiddenDivider.getLocation(); int ourX = e.getX() + hDividerLoc.x; int ourY = e.getY() + hDividerLoc.y; dragger.completeDrag(ourX, ourY); } dragger = null; e.consume(); } } // // MouseMotionListener // /** {@collect.stats} * If dragger is not null it is messaged with continueDrag. */ public void mouseDragged(MouseEvent e) { if (dragger != null) { if (e.getSource() == splitPane) { dragger.continueDrag(e.getX(), e.getY()); } else if (e.getSource() == BasicSplitPaneDivider.this) { Point ourLoc = getLocation(); dragger.continueDrag(e.getX() + ourLoc.x, e.getY() + ourLoc.y); } else if (e.getSource() == hiddenDivider) { Point hDividerLoc = hiddenDivider.getLocation(); int ourX = e.getX() + hDividerLoc.x; int ourY = e.getY() + hDividerLoc.y; dragger.continueDrag(ourX, ourY); } e.consume(); } } /** {@collect.stats} * Resets the cursor based on the orientation. */ public void mouseMoved(MouseEvent e) { } /** {@collect.stats} * Invoked when the mouse enters a component. * * @param e MouseEvent describing the details of the enter event. * @since 1.5 */ public void mouseEntered(MouseEvent e) { if (e.getSource() == BasicSplitPaneDivider.this) { setMouseOver(true); } } /** {@collect.stats} * Invoked when the mouse exits a component. * * @param e MouseEvent describing the details of the exit event. * @since 1.5 */ public void mouseExited(MouseEvent e) { if (e.getSource() == BasicSplitPaneDivider.this) { setMouseOver(false); } } } /** {@collect.stats} * Handles the events during a dragging session for a * HORIZONTAL_SPLIT oriented split pane. This continually * messages <code>dragDividerTo</code> and then when done messages * <code>finishDraggingTo</code>. When an instance is created it should be * messaged with <code>isValid</code> to insure that dragging can happen * (dragging won't be allowed if the two views can not be resized). * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. */ protected class DragController { /** {@collect.stats} * Initial location of the divider. */ int initialX; /** {@collect.stats} * Maximum and minimum positions to drag to. */ int maxX, minX; /** {@collect.stats} * Initial location the mouse down happened at. */ int offset; protected DragController(MouseEvent e) { JSplitPane splitPane = splitPaneUI.getSplitPane(); Component leftC = splitPane.getLeftComponent(); Component rightC = splitPane.getRightComponent(); initialX = getLocation().x; if (e.getSource() == BasicSplitPaneDivider.this) { offset = e.getX(); } else { // splitPane offset = e.getX() - initialX; } if (leftC == null || rightC == null || offset < -1 || offset >= getSize().width) { // Don't allow dragging. maxX = -1; } else { Insets insets = splitPane.getInsets(); if (leftC.isVisible()) { minX = leftC.getMinimumSize().width; if (insets != null) { minX += insets.left; } } else { minX = 0; } if (rightC.isVisible()) { int right = (insets != null) ? insets.right : 0; maxX = Math.max(0, splitPane.getSize().width - (getSize().width + right) - rightC.getMinimumSize().width); } else { int right = (insets != null) ? insets.right : 0; maxX = Math.max(0, splitPane.getSize().width - (getSize().width + right)); } if (maxX < minX) minX = maxX = 0; } } /** {@collect.stats} * Returns true if the dragging session is valid. */ protected boolean isValid() { return (maxX > 0); } /** {@collect.stats} * Returns the new position to put the divider at based on * the passed in MouseEvent. */ protected int positionForMouseEvent(MouseEvent e) { int newX = (e.getSource() == BasicSplitPaneDivider.this) ? (e.getX() + getLocation().x) : e.getX(); newX = Math.min(maxX, Math.max(minX, newX - offset)); return newX; } /** {@collect.stats} * Returns the x argument, since this is used for horizontal * splits. */ protected int getNeededLocation(int x, int y) { int newX; newX = Math.min(maxX, Math.max(minX, x - offset)); return newX; } protected void continueDrag(int newX, int newY) { dragDividerTo(getNeededLocation(newX, newY)); } /** {@collect.stats} * Messages dragDividerTo with the new location for the mouse * event. */ protected void continueDrag(MouseEvent e) { dragDividerTo(positionForMouseEvent(e)); } protected void completeDrag(int x, int y) { finishDraggingTo(getNeededLocation(x, y)); } /** {@collect.stats} * Messages finishDraggingTo with the new location for the mouse * event. */ protected void completeDrag(MouseEvent e) { finishDraggingTo(positionForMouseEvent(e)); } } // End of BasicSplitPaneDivider.DragController /** {@collect.stats} * Handles the events during a dragging session for a * VERTICAL_SPLIT oriented split pane. This continually * messages <code>dragDividerTo</code> and then when done messages * <code>finishDraggingTo</code>. When an instance is created it should be * messaged with <code>isValid</code> to insure that dragging can happen * (dragging won't be allowed if the two views can not be resized). */ protected class VerticalDragController extends DragController { /* DragControllers ivars are now in terms of y, not x. */ protected VerticalDragController(MouseEvent e) { super(e); JSplitPane splitPane = splitPaneUI.getSplitPane(); Component leftC = splitPane.getLeftComponent(); Component rightC = splitPane.getRightComponent(); initialX = getLocation().y; if (e.getSource() == BasicSplitPaneDivider.this) { offset = e.getY(); } else { offset = e.getY() - initialX; } if (leftC == null || rightC == null || offset < -1 || offset > getSize().height) { // Don't allow dragging. maxX = -1; } else { Insets insets = splitPane.getInsets(); if (leftC.isVisible()) { minX = leftC.getMinimumSize().height; if (insets != null) { minX += insets.top; } } else { minX = 0; } if (rightC.isVisible()) { int bottom = (insets != null) ? insets.bottom : 0; maxX = Math.max(0, splitPane.getSize().height - (getSize().height + bottom) - rightC.getMinimumSize().height); } else { int bottom = (insets != null) ? insets.bottom : 0; maxX = Math.max(0, splitPane.getSize().height - (getSize().height + bottom)); } if (maxX < minX) minX = maxX = 0; } } /** {@collect.stats} * Returns the y argument, since this is used for vertical * splits. */ protected int getNeededLocation(int x, int y) { int newY; newY = Math.min(maxX, Math.max(minX, y - offset)); return newY; } /** {@collect.stats} * Returns the new position to put the divider at based on * the passed in MouseEvent. */ protected int positionForMouseEvent(MouseEvent e) { int newY = (e.getSource() == BasicSplitPaneDivider.this) ? (e.getY() + getLocation().y) : e.getY(); newY = Math.min(maxX, Math.max(minX, newY - offset)); return newY; } } // End of BasicSplitPaneDividier.VerticalDragController /** {@collect.stats} * Used to layout a <code>BasicSplitPaneDivider</code>. * Layout for the divider * involves appropriately moving the left/right buttons around. * <p> */ protected class DividerLayout implements LayoutManager { public void layoutContainer(Container c) { if (leftButton != null && rightButton != null && c == BasicSplitPaneDivider.this) { if (splitPane.isOneTouchExpandable()) { Insets insets = getInsets(); if (orientation == JSplitPane.VERTICAL_SPLIT) { int extraX = (insets != null) ? insets.left : 0; int blockSize = getHeight(); if (insets != null) { blockSize -= (insets.top + insets.bottom); blockSize = Math.max(blockSize, 0); } blockSize = Math.min(blockSize, oneTouchSize); int y = (c.getSize().height - blockSize) / 2; if (!centerOneTouchButtons) { y = (insets != null) ? insets.top : 0; extraX = 0; } leftButton.setBounds(extraX + oneTouchOffset, y, blockSize * 2, blockSize); rightButton.setBounds(extraX + oneTouchOffset + oneTouchSize * 2, y, blockSize * 2, blockSize); } else { int extraY = (insets != null) ? insets.top : 0; int blockSize = getWidth(); if (insets != null) { blockSize -= (insets.left + insets.right); blockSize = Math.max(blockSize, 0); } blockSize = Math.min(blockSize, oneTouchSize); int x = (c.getSize().width - blockSize) / 2; if (!centerOneTouchButtons) { x = (insets != null) ? insets.left : 0; extraY = 0; } leftButton.setBounds(x, extraY + oneTouchOffset, blockSize, blockSize * 2); rightButton.setBounds(x, extraY + oneTouchOffset + oneTouchSize * 2, blockSize, blockSize * 2); } } else { leftButton.setBounds(-5, -5, 1, 1); rightButton.setBounds(-5, -5, 1, 1); } } } public Dimension minimumLayoutSize(Container c) { // NOTE: This isn't really used, refer to // BasicSplitPaneDivider.getPreferredSize for the reason. // I leave it in hopes of having this used at some point. if (c != BasicSplitPaneDivider.this || splitPane == null) { return new Dimension(0,0); } Dimension buttonMinSize = null; if (splitPane.isOneTouchExpandable() && leftButton != null) { buttonMinSize = leftButton.getMinimumSize(); } Insets insets = getInsets(); int width = getDividerSize(); int height = width; if (orientation == JSplitPane.VERTICAL_SPLIT) { if (buttonMinSize != null) { int size = buttonMinSize.height; if (insets != null) { size += insets.top + insets.bottom; } height = Math.max(height, size); } width = 1; } else { if (buttonMinSize != null) { int size = buttonMinSize.width; if (insets != null) { size += insets.left + insets.right; } width = Math.max(width, size); } height = 1; } return new Dimension(width, height); } public Dimension preferredLayoutSize(Container c) { return minimumLayoutSize(c); } public void removeLayoutComponent(Component c) {} public void addLayoutComponent(String string, Component c) {} } // End of class BasicSplitPaneDivider.DividerLayout /** {@collect.stats} * Listeners installed on the one touch expandable buttons. */ private class OneTouchActionHandler implements ActionListener { /** {@collect.stats} True indicates the resize should go the minimum (top or left) * vs false which indicates the resize should go to the maximum. */ private boolean toMinimum; OneTouchActionHandler(boolean toMinimum) { this.toMinimum = toMinimum; } public void actionPerformed(ActionEvent e) { Insets insets = splitPane.getInsets(); int lastLoc = splitPane.getLastDividerLocation(); int currentLoc = splitPaneUI.getDividerLocation(splitPane); int newLoc; // We use the location from the UI directly, as the location the // JSplitPane itself maintains is not necessarly correct. if (toMinimum) { if (orientation == JSplitPane.VERTICAL_SPLIT) { if (currentLoc >= (splitPane.getHeight() - insets.bottom - getHeight())) { int maxLoc = splitPane.getMaximumDividerLocation(); newLoc = Math.min(lastLoc, maxLoc); splitPaneUI.setKeepHidden(false); } else { newLoc = insets.top; splitPaneUI.setKeepHidden(true); } } else { if (currentLoc >= (splitPane.getWidth() - insets.right - getWidth())) { int maxLoc = splitPane.getMaximumDividerLocation(); newLoc = Math.min(lastLoc, maxLoc); splitPaneUI.setKeepHidden(false); } else { newLoc = insets.left; splitPaneUI.setKeepHidden(true); } } } else { if (orientation == JSplitPane.VERTICAL_SPLIT) { if (currentLoc == insets.top) { int maxLoc = splitPane.getMaximumDividerLocation(); newLoc = Math.min(lastLoc, maxLoc); splitPaneUI.setKeepHidden(false); } else { newLoc = splitPane.getHeight() - getHeight() - insets.top; splitPaneUI.setKeepHidden(true); } } else { if (currentLoc == insets.left) { int maxLoc = splitPane.getMaximumDividerLocation(); newLoc = Math.min(lastLoc, maxLoc); splitPaneUI.setKeepHidden(false); } else { newLoc = splitPane.getWidth() - getWidth() - insets.left; splitPaneUI.setKeepHidden(true); } } } if (currentLoc != newLoc) { splitPane.setDividerLocation(newLoc); // We do this in case the dividers notion of the location // differs from the real location. splitPane.setLastDividerLocation(currentLoc); } } } // End of class BasicSplitPaneDivider.LeftActionListener }
Java
/* * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import sun.awt.AppContext; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.plaf.*; import javax.swing.text.View; /** {@collect.stats} * BasicToggleButton implementation * <p> * * @author Jeff Dinkins */ public class BasicToggleButtonUI extends BasicButtonUI { private static final Object BASIC_TOGGLE_BUTTON_UI_KEY = new Object(); private final static String propertyPrefix = "ToggleButton" + "."; // ******************************** // Create PLAF // ******************************** public static ComponentUI createUI(JComponent b) { AppContext appContext = AppContext.getAppContext(); BasicToggleButtonUI toggleButtonUI = (BasicToggleButtonUI) appContext.get(BASIC_TOGGLE_BUTTON_UI_KEY); if (toggleButtonUI == null) { toggleButtonUI = new BasicToggleButtonUI(); appContext.put(BASIC_TOGGLE_BUTTON_UI_KEY, toggleButtonUI); } return toggleButtonUI; } protected String getPropertyPrefix() { return propertyPrefix; } // ******************************** // Paint Methods // ******************************** public void paint(Graphics g, JComponent c) { AbstractButton b = (AbstractButton) c; ButtonModel model = b.getModel(); Dimension size = b.getSize(); FontMetrics fm = g.getFontMetrics(); Insets i = c.getInsets(); Rectangle viewRect = new Rectangle(size); viewRect.x += i.left; viewRect.y += i.top; viewRect.width -= (i.right + viewRect.x); viewRect.height -= (i.bottom + viewRect.y); Rectangle iconRect = new Rectangle(); Rectangle textRect = new Rectangle(); Font f = c.getFont(); g.setFont(f); // layout the text and icon String text = SwingUtilities.layoutCompoundLabel( c, fm, b.getText(), b.getIcon(), b.getVerticalAlignment(), b.getHorizontalAlignment(), b.getVerticalTextPosition(), b.getHorizontalTextPosition(), viewRect, iconRect, textRect, b.getText() == null ? 0 : b.getIconTextGap()); g.setColor(b.getBackground()); if (model.isArmed() && model.isPressed() || model.isSelected()) { paintButtonPressed(g,b); } // Paint the Icon if(b.getIcon() != null) { paintIcon(g, b, iconRect); } // Draw the Text if(text != null && !text.equals("")) { View v = (View) c.getClientProperty(BasicHTML.propertyKey); if (v != null) { v.paint(g, textRect); } else { paintText(g, b, textRect, text); } } // draw the dashed focus line. if (b.isFocusPainted() && b.hasFocus()) { paintFocus(g, b, viewRect, textRect, iconRect); } } protected void paintIcon(Graphics g, AbstractButton b, Rectangle iconRect) { ButtonModel model = b.getModel(); Icon icon = null; if(!model.isEnabled()) { if(model.isSelected()) { icon = (Icon) b.getDisabledSelectedIcon(); } else { icon = (Icon) b.getDisabledIcon(); } } else if(model.isPressed() && model.isArmed()) { icon = (Icon) b.getPressedIcon(); if(icon == null) { // Use selected icon icon = (Icon) b.getSelectedIcon(); } } else if(model.isSelected()) { if(b.isRolloverEnabled() && model.isRollover()) { icon = (Icon) b.getRolloverSelectedIcon(); if (icon == null) { icon = (Icon) b.getSelectedIcon(); } } else { icon = (Icon) b.getSelectedIcon(); } } else if(b.isRolloverEnabled() && model.isRollover()) { icon = (Icon) b.getRolloverIcon(); } if(icon == null) { icon = (Icon) b.getIcon(); } icon.paintIcon(b, g, iconRect.x, iconRect.y); } /** {@collect.stats} * Overriden so that the text will not be rendered as shifted for * Toggle buttons and subclasses. */ protected int getTextShiftOffset() { return 0; } }
Java
/* * Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.*; import java.applet.Applet; import java.awt.Component; import java.awt.KeyboardFocusManager; import java.awt.Window; import java.awt.event.*; import java.awt.AWTEvent; import java.awt.Toolkit; import java.util.*; import sun.swing.UIAction; import sun.awt.AppContext; /** {@collect.stats} * A Windows L&F implementation of PopupMenuUI. This implementation * is a "combined" view/controller. * * @author Georges Saab * @author David Karlton * @author Arnaud Weber */ public class BasicPopupMenuUI extends PopupMenuUI { static final Object MOUSE_GRABBER_KEY = new Object(); // javax.swing.plaf.basic.BasicPopupMenuUI.MouseGrabber static final Object MENU_KEYBOARD_HELPER_KEY = new Object(); // javax.swing.plaf.basic.BasicPopupMenuUI.MenuKeyboardHelper protected JPopupMenu popupMenu = null; private transient PopupMenuListener popupMenuListener = null; private MenuKeyListener menuKeyListener = null; private static boolean checkedUnpostPopup; private static boolean unpostPopup; public static ComponentUI createUI(JComponent x) { return new BasicPopupMenuUI(); } public BasicPopupMenuUI() { BasicLookAndFeel.needsEventHelper = true; LookAndFeel laf = UIManager.getLookAndFeel(); if (laf instanceof BasicLookAndFeel) { ((BasicLookAndFeel)laf).installAWTEventListener(); } } public void installUI(JComponent c) { popupMenu = (JPopupMenu) c; installDefaults(); installListeners(); installKeyboardActions(); } public void installDefaults() { if (popupMenu.getLayout() == null || popupMenu.getLayout() instanceof UIResource) popupMenu.setLayout(new DefaultMenuLayout(popupMenu, BoxLayout.Y_AXIS)); LookAndFeel.installProperty(popupMenu, "opaque", Boolean.TRUE); LookAndFeel.installBorder(popupMenu, "PopupMenu.border"); LookAndFeel.installColorsAndFont(popupMenu, "PopupMenu.background", "PopupMenu.foreground", "PopupMenu.font"); } protected void installListeners() { if (popupMenuListener == null) { popupMenuListener = new BasicPopupMenuListener(); } popupMenu.addPopupMenuListener(popupMenuListener); if (menuKeyListener == null) { menuKeyListener = new BasicMenuKeyListener(); } popupMenu.addMenuKeyListener(menuKeyListener); AppContext context = AppContext.getAppContext(); synchronized (MOUSE_GRABBER_KEY) { MouseGrabber mouseGrabber = (MouseGrabber)context.get( MOUSE_GRABBER_KEY); if (mouseGrabber == null) { mouseGrabber = new MouseGrabber(); context.put(MOUSE_GRABBER_KEY, mouseGrabber); } } synchronized (MENU_KEYBOARD_HELPER_KEY) { MenuKeyboardHelper helper = (MenuKeyboardHelper)context.get(MENU_KEYBOARD_HELPER_KEY); if (helper == null) { helper = new MenuKeyboardHelper(); context.put(MENU_KEYBOARD_HELPER_KEY, helper); MenuSelectionManager msm = MenuSelectionManager.defaultManager(); msm.addChangeListener(helper); } } } protected void installKeyboardActions() { } static InputMap getInputMap(JPopupMenu popup, JComponent c) { InputMap windowInputMap = null; Object[] bindings = (Object[])UIManager.get("PopupMenu.selectedWindowInputMapBindings"); if (bindings != null) { windowInputMap = LookAndFeel.makeComponentInputMap(c, bindings); if (!popup.getComponentOrientation().isLeftToRight()) { Object[] km = (Object[])UIManager.get("PopupMenu.selectedWindowInputMapBindings.RightToLeft"); if (km != null) { InputMap rightToLeftInputMap = LookAndFeel.makeComponentInputMap(c, km); rightToLeftInputMap.setParent(windowInputMap); windowInputMap = rightToLeftInputMap; } } } return windowInputMap; } static ActionMap getActionMap() { return LazyActionMap.getActionMap(BasicPopupMenuUI.class, "PopupMenu.actionMap"); } static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.CANCEL)); map.put(new Actions(Actions.SELECT_NEXT)); map.put(new Actions(Actions.SELECT_PREVIOUS)); map.put(new Actions(Actions.SELECT_PARENT)); map.put(new Actions(Actions.SELECT_CHILD)); map.put(new Actions(Actions.RETURN)); BasicLookAndFeel.installAudioActionMap(map); } public void uninstallUI(JComponent c) { uninstallDefaults(); uninstallListeners(); uninstallKeyboardActions(); popupMenu = null; } protected void uninstallDefaults() { LookAndFeel.uninstallBorder(popupMenu); } protected void uninstallListeners() { if (popupMenuListener != null) { popupMenu.removePopupMenuListener(popupMenuListener); } if (menuKeyListener != null) { popupMenu.removeMenuKeyListener(menuKeyListener); } } protected void uninstallKeyboardActions() { SwingUtilities.replaceUIActionMap(popupMenu, null); SwingUtilities.replaceUIInputMap(popupMenu, JComponent.WHEN_IN_FOCUSED_WINDOW, null); } static MenuElement getFirstPopup() { MenuSelectionManager msm = MenuSelectionManager.defaultManager(); MenuElement[] p = msm.getSelectedPath(); MenuElement me = null; for(int i = 0 ; me == null && i < p.length ; i++) { if (p[i] instanceof JPopupMenu) me = p[i]; } return me; } static JPopupMenu getLastPopup() { MenuSelectionManager msm = MenuSelectionManager.defaultManager(); MenuElement[] p = msm.getSelectedPath(); JPopupMenu popup = null; for(int i = p.length - 1; popup == null && i >= 0; i--) { if (p[i] instanceof JPopupMenu) popup = (JPopupMenu)p[i]; } return popup; } static List getPopups() { MenuSelectionManager msm = MenuSelectionManager.defaultManager(); MenuElement[] p = msm.getSelectedPath(); List list = new ArrayList(p.length); for(int i = 0; i < p.length; i++) { if (p[i] instanceof JPopupMenu) { list.add((JPopupMenu)p[i]); } } return list; } public boolean isPopupTrigger(MouseEvent e) { return ((e.getID()==MouseEvent.MOUSE_RELEASED) && ((e.getModifiers() & MouseEvent.BUTTON3_MASK)!=0)); } private static boolean checkInvokerEqual(MenuElement present, MenuElement last) { Component invokerPresent = present.getComponent(); Component invokerLast = last.getComponent(); if (invokerPresent instanceof JPopupMenu) { invokerPresent = ((JPopupMenu)invokerPresent).getInvoker(); } if (invokerLast instanceof JPopupMenu) { invokerLast = ((JPopupMenu)invokerLast).getInvoker(); } return (invokerPresent == invokerLast); } /** {@collect.stats} * This Listener fires the Action that provides the correct auditory * feedback. * * @since 1.4 */ private class BasicPopupMenuListener implements PopupMenuListener { public void popupMenuCanceled(PopupMenuEvent e) { } public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { } public void popupMenuWillBecomeVisible(PopupMenuEvent e) { BasicLookAndFeel.playSound((JPopupMenu)e.getSource(), "PopupMenu.popupSound"); } } /** {@collect.stats} * Handles mnemonic for children JMenuItems. * @since 1.5 */ private class BasicMenuKeyListener implements MenuKeyListener { MenuElement menuToOpen = null; public void menuKeyTyped(MenuKeyEvent e) { if (menuToOpen != null) { // we have a submenu to open JPopupMenu subpopup = ((JMenu)menuToOpen).getPopupMenu(); MenuElement subitem = findEnabledChild( subpopup.getSubElements(), -1, true); ArrayList lst = new ArrayList(Arrays.asList(e.getPath())); lst.add(menuToOpen); lst.add(subpopup); if (subitem != null) { lst.add(subitem); } MenuElement newPath[] = new MenuElement[0];; newPath = (MenuElement[])lst.toArray(newPath); MenuSelectionManager.defaultManager().setSelectedPath(newPath); e.consume(); } menuToOpen = null; } public void menuKeyPressed(MenuKeyEvent e) { char keyChar = e.getKeyChar(); // Handle the case for Escape or Enter... if (!Character.isLetterOrDigit(keyChar)) { return; } MenuSelectionManager manager = e.getMenuSelectionManager(); MenuElement path[] = e.getPath(); MenuElement items[] = popupMenu.getSubElements(); int currentIndex = -1; int matches = 0; int firstMatch = -1; int indexes[] = null; for (int j = 0; j < items.length; j++) { if (! (items[j] instanceof JMenuItem)) { continue; } JMenuItem item = (JMenuItem)items[j]; int mnemonic = item.getMnemonic(); if (item.isEnabled() && item.isVisible() && lower(keyChar) == lower(mnemonic)) { if (matches == 0) { firstMatch = j; matches++; } else { if (indexes == null) { indexes = new int[items.length]; indexes[0] = firstMatch; } indexes[matches++] = j; } } if (item.isArmed()) { currentIndex = matches - 1; } } if (matches == 0) { ; // no op } else if (matches == 1) { // Invoke the menu action JMenuItem item = (JMenuItem)items[firstMatch]; if (item instanceof JMenu) { // submenus are handled in menuKeyTyped menuToOpen = item; } else if (item.isEnabled()) { // we have a menu item manager.clearSelectedPath(); item.doClick(); } e.consume(); } else { // Select the menu item with the matching mnemonic. If // the same mnemonic has been invoked then select the next // menu item in the cycle. MenuElement newItem = null; newItem = items[indexes[(currentIndex + 1) % matches]]; MenuElement newPath[] = new MenuElement[path.length+1]; System.arraycopy(path, 0, newPath, 0, path.length); newPath[path.length] = newItem; manager.setSelectedPath(newPath); e.consume(); } return; } public void menuKeyReleased(MenuKeyEvent e) { } private char lower(char keyChar) { return Character.toLowerCase(keyChar); } private char lower(int mnemonic) { return Character.toLowerCase((char) mnemonic); } } private static class Actions extends UIAction { // Types of actions private static final String CANCEL = "cancel"; private static final String SELECT_NEXT = "selectNext"; private static final String SELECT_PREVIOUS = "selectPrevious"; private static final String SELECT_PARENT = "selectParent"; private static final String SELECT_CHILD = "selectChild"; private static final String RETURN = "return"; // Used for next/previous actions private static final boolean FORWARD = true; private static final boolean BACKWARD = false; // Used for parent/child actions private static final boolean PARENT = false; private static final boolean CHILD = true; Actions(String key) { super(key); } public void actionPerformed(ActionEvent e) { String key = getName(); if (key == CANCEL) { cancel(); } else if (key == SELECT_NEXT) { selectItem(FORWARD); } else if (key == SELECT_PREVIOUS) { selectItem(BACKWARD); } else if (key == SELECT_PARENT) { selectParentChild(PARENT); } else if (key == SELECT_CHILD) { selectParentChild(CHILD); } else if (key == RETURN) { doReturn(); } } private void doReturn() { KeyboardFocusManager fmgr = KeyboardFocusManager.getCurrentKeyboardFocusManager(); Component focusOwner = fmgr.getFocusOwner(); if(focusOwner != null && !(focusOwner instanceof JRootPane)) { return; } MenuSelectionManager msm = MenuSelectionManager.defaultManager(); MenuElement path[] = msm.getSelectedPath(); MenuElement lastElement; if(path.length > 0) { lastElement = path[path.length-1]; if(lastElement instanceof JMenu) { MenuElement newPath[] = new MenuElement[path.length+1]; System.arraycopy(path,0,newPath,0,path.length); newPath[path.length] = ((JMenu)lastElement).getPopupMenu(); msm.setSelectedPath(newPath); } else if(lastElement instanceof JMenuItem) { JMenuItem mi = (JMenuItem)lastElement; if (mi.getUI() instanceof BasicMenuItemUI) { ((BasicMenuItemUI)mi.getUI()).doClick(msm); } else { msm.clearSelectedPath(); mi.doClick(0); } } } } private void selectParentChild(boolean direction) { MenuSelectionManager msm = MenuSelectionManager.defaultManager(); MenuElement path[] = msm.getSelectedPath(); int len = path.length; if (direction == PARENT) { // selecting parent int popupIndex = len-1; if (len > 2 && // check if we have an open submenu. A submenu item may or // may not be selected, so submenu popup can be either the // last or next to the last item. (path[popupIndex] instanceof JPopupMenu || path[--popupIndex] instanceof JPopupMenu) && !((JMenu)path[popupIndex-1]).isTopLevelMenu()) { // we have a submenu, just close it MenuElement newPath[] = new MenuElement[popupIndex]; System.arraycopy(path, 0, newPath, 0, popupIndex); msm.setSelectedPath(newPath); return; } } else { // selecting child if (len > 0 && path[len-1] instanceof JMenu && !((JMenu)path[len-1]).isTopLevelMenu()) { // we have a submenu, open it JMenu menu = (JMenu)path[len-1]; JPopupMenu popup = menu.getPopupMenu(); MenuElement[] subs = popup.getSubElements(); MenuElement item = findEnabledChild(subs, -1, true); MenuElement[] newPath; if (item == null) { newPath = new MenuElement[len+1]; } else { newPath = new MenuElement[len+2]; newPath[len+1] = item; } System.arraycopy(path, 0, newPath, 0, len); newPath[len] = popup; msm.setSelectedPath(newPath); return; } } // check if we have a toplevel menu selected. // If this is the case, we select another toplevel menu if (len > 1 && path[0] instanceof JMenuBar) { MenuElement currentMenu = path[1]; MenuElement nextMenu = findEnabledChild( path[0].getSubElements(), currentMenu, direction); if (nextMenu != null && nextMenu != currentMenu) { MenuElement newSelection[]; if (len == 2) { // menu is selected but its popup not shown newSelection = new MenuElement[2]; newSelection[0] = path[0]; newSelection[1] = nextMenu; } else { // menu is selected and its popup is shown newSelection = new MenuElement[3]; newSelection[0] = path[0]; newSelection[1] = nextMenu; newSelection[2] = ((JMenu)nextMenu).getPopupMenu(); } msm.setSelectedPath(newSelection); } } } private void selectItem(boolean direction) { MenuSelectionManager msm = MenuSelectionManager.defaultManager(); MenuElement path[] = msm.getSelectedPath(); if (path.length == 0) { return; } int len = path.length; if (len == 1 && path[0] instanceof JPopupMenu) { JPopupMenu popup = (JPopupMenu) path[0]; MenuElement[] newPath = new MenuElement[2]; newPath[0] = popup; newPath[1] = findEnabledChild(popup.getSubElements(), -1, direction); msm.setSelectedPath(newPath); } else if (len == 2 && path[0] instanceof JMenuBar && path[1] instanceof JMenu) { // a toplevel menu is selected, but its popup not shown. // Show the popup and select the first item JPopupMenu popup = ((JMenu)path[1]).getPopupMenu(); MenuElement next = findEnabledChild(popup.getSubElements(), -1, FORWARD); MenuElement[] newPath; if (next != null) { // an enabled item found -- include it in newPath newPath = new MenuElement[4]; newPath[3] = next; } else { // menu has no enabled items -- still must show the popup newPath = new MenuElement[3]; } System.arraycopy(path, 0, newPath, 0, 2); newPath[2] = popup; msm.setSelectedPath(newPath); } else if (path[len-1] instanceof JPopupMenu && path[len-2] instanceof JMenu) { // a menu (not necessarily toplevel) is open and its popup // shown. Select the appropriate menu item JMenu menu = (JMenu)path[len-2]; JPopupMenu popup = menu.getPopupMenu(); MenuElement next = findEnabledChild(popup.getSubElements(), -1, direction); if (next != null) { MenuElement[] newPath = new MenuElement[len+1]; System.arraycopy(path, 0, newPath, 0, len); newPath[len] = next; msm.setSelectedPath(newPath); } else { // all items in the popup are disabled. // We're going to find the parent popup menu and select // its next item. If there's no parent popup menu (i.e. // current menu is toplevel), do nothing if (len > 2 && path[len-3] instanceof JPopupMenu) { popup = ((JPopupMenu)path[len-3]); next = findEnabledChild(popup.getSubElements(), menu, direction); if (next != null && next != menu) { MenuElement[] newPath = new MenuElement[len-1]; System.arraycopy(path, 0, newPath, 0, len-2); newPath[len-2] = next; msm.setSelectedPath(newPath); } } } } else { // just select the next item, no path expansion needed MenuElement subs[] = path[len-2].getSubElements(); MenuElement nextChild = findEnabledChild(subs, path[len-1], direction); if (nextChild == null) { nextChild = findEnabledChild(subs, -1, direction); } if (nextChild != null) { path[len-1] = nextChild; msm.setSelectedPath(path); } } } private void cancel() { // 4234793: This action should call JPopupMenu.firePopupMenuCanceled but it's // a protected method. The real solution could be to make // firePopupMenuCanceled public and call it directly. JPopupMenu lastPopup = (JPopupMenu)getLastPopup(); if (lastPopup != null) { lastPopup.putClientProperty("JPopupMenu.firePopupMenuCanceled", Boolean.TRUE); } String mode = UIManager.getString("Menu.cancelMode"); if ("hideMenuTree".equals(mode)) { MenuSelectionManager.defaultManager().clearSelectedPath(); } else { shortenSelectedPath(); } } private void shortenSelectedPath() { MenuElement path[] = MenuSelectionManager.defaultManager().getSelectedPath(); if (path.length <= 2) { MenuSelectionManager.defaultManager().clearSelectedPath(); return; } // unselect MenuItem and its Popup by default int value = 2; MenuElement lastElement = path[path.length - 1]; JPopupMenu lastPopup = getLastPopup(); if (lastElement == lastPopup) { MenuElement previousElement = path[path.length - 2]; if (previousElement instanceof JMenu) { JMenu lastMenu = (JMenu) previousElement; if (lastMenu.isEnabled() && lastPopup.getComponentCount() > 0) { // unselect the last visible popup only value = 1; } else { // unselect invisible popup and two visible elements value = 3; } } } if (path.length - value <= 2 && !UIManager.getBoolean("Menu.preserveTopLevelSelection")) { // clear selection for the topLevelMenu value = path.length; } MenuElement newPath[] = new MenuElement[path.length - value]; System.arraycopy(path, 0, newPath, 0, path.length - value); MenuSelectionManager.defaultManager().setSelectedPath(newPath); } } private static MenuElement nextEnabledChild(MenuElement e[], int fromIndex, int toIndex) { for (int i=fromIndex; i<=toIndex; i++) { if (e[i] != null) { Component comp = e[i].getComponent(); if ( comp != null && (comp.isEnabled() || UIManager.getBoolean("MenuItem.disabledAreNavigable")) && comp.isVisible()) { return e[i]; } } } return null; } private static MenuElement previousEnabledChild(MenuElement e[], int fromIndex, int toIndex) { for (int i=fromIndex; i>=toIndex; i--) { if (e[i] != null) { Component comp = e[i].getComponent(); if ( comp != null && (comp.isEnabled() || UIManager.getBoolean("MenuItem.disabledAreNavigable")) && comp.isVisible()) { return e[i]; } } } return null; } static MenuElement findEnabledChild(MenuElement e[], int fromIndex, boolean forward) { MenuElement result = null; if (forward) { result = nextEnabledChild(e, fromIndex+1, e.length-1); if (result == null) result = nextEnabledChild(e, 0, fromIndex-1); } else { result = previousEnabledChild(e, fromIndex-1, 0); if (result == null) result = previousEnabledChild(e, e.length-1, fromIndex+1); } return result; } static MenuElement findEnabledChild(MenuElement e[], MenuElement elem, boolean forward) { for (int i=0; i<e.length; i++) { if (e[i] == elem) { return findEnabledChild(e, i, forward); } } return null; } static class MouseGrabber implements ChangeListener, AWTEventListener, ComponentListener, WindowListener { Window grabbedWindow; MenuElement[] lastPathSelected; public MouseGrabber() { MenuSelectionManager msm = MenuSelectionManager.defaultManager(); msm.addChangeListener(this); this.lastPathSelected = msm.getSelectedPath(); if(this.lastPathSelected.length != 0) { grabWindow(this.lastPathSelected); } } void uninstall() { synchronized (MOUSE_GRABBER_KEY) { MenuSelectionManager.defaultManager().removeChangeListener(this); ungrabWindow(); AppContext.getAppContext().remove(MOUSE_GRABBER_KEY); } } void grabWindow(MenuElement[] newPath) { // A grab needs to be added final Toolkit tk = Toolkit.getDefaultToolkit(); java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Object run() { tk.addAWTEventListener(MouseGrabber.this, AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_WHEEL_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK | sun.awt.SunToolkit.GRAB_EVENT_MASK); return null; } } ); Component invoker = newPath[0].getComponent(); if (invoker instanceof JPopupMenu) { invoker = ((JPopupMenu)invoker).getInvoker(); } grabbedWindow = invoker instanceof Window? (Window)invoker : SwingUtilities.getWindowAncestor(invoker); if(grabbedWindow != null) { if(tk instanceof sun.awt.SunToolkit) { ((sun.awt.SunToolkit)tk).grab(grabbedWindow); } else { grabbedWindow.addComponentListener(this); grabbedWindow.addWindowListener(this); } } } void ungrabWindow() { final Toolkit tk = Toolkit.getDefaultToolkit(); // The grab should be removed java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Object run() { tk.removeAWTEventListener(MouseGrabber.this); return null; } } ); realUngrabWindow(); } void realUngrabWindow() { Toolkit tk = Toolkit.getDefaultToolkit(); if(grabbedWindow != null) { if(tk instanceof sun.awt.SunToolkit) { ((sun.awt.SunToolkit)tk).ungrab(grabbedWindow); } else { grabbedWindow.removeComponentListener(this); grabbedWindow.removeWindowListener(this); } grabbedWindow = null; } } public void stateChanged(ChangeEvent e) { MenuSelectionManager msm = MenuSelectionManager.defaultManager(); MenuElement[] p = msm.getSelectedPath(); if (lastPathSelected.length == 0 && p.length != 0) { grabWindow(p); } if (lastPathSelected.length != 0 && p.length == 0) { ungrabWindow(); } lastPathSelected = p; } public void eventDispatched(AWTEvent ev) { if(ev instanceof sun.awt.UngrabEvent) { // Popup should be canceled in case of ungrab event cancelPopupMenu( ); return; } if (!(ev instanceof MouseEvent)) { // We are interested in MouseEvents only return; } MouseEvent me = (MouseEvent) ev; Component src = me.getComponent(); switch (me.getID()) { case MouseEvent.MOUSE_PRESSED: if (isInPopup(src) || (src instanceof JMenu && ((JMenu)src).isSelected())) { return; } if (!(src instanceof JComponent) || ! (((JComponent)src).getClientProperty("doNotCancelPopup") == BasicComboBoxUI.HIDE_POPUP_KEY)) { // Cancel popup only if this property was not set. // If this property is set to TRUE component wants // to deal with this event by himself. cancelPopupMenu(); // Ask UIManager about should we consume event that closes // popup. This made to match native apps behaviour. boolean consumeEvent = UIManager.getBoolean("PopupMenu.consumeEventOnClose"); // Consume the event so that normal processing stops. if(consumeEvent && !(src instanceof MenuElement)) { me.consume(); } } break; case MouseEvent.MOUSE_RELEASED: if(!(src instanceof MenuElement)) { // Do not forward event to MSM, let component handle it if (isInPopup(src)) { break; } } if(src instanceof JMenu || !(src instanceof JMenuItem)) { MenuSelectionManager.defaultManager(). processMouseEvent(me); } break; case MouseEvent.MOUSE_DRAGGED: if(!(src instanceof MenuElement)) { // For the MOUSE_DRAGGED event the src is // the Component in which mouse button was pressed. // If the src is in popupMenu, // do not forward event to MSM, let component handle it. if (isInPopup(src)) { break; } } MenuSelectionManager.defaultManager(). processMouseEvent(me); break; case MouseEvent.MOUSE_WHEEL: if (isInPopup(src)) { return; } cancelPopupMenu(); break; } } boolean isInPopup(Component src) { for (Component c=src; c!=null; c=c.getParent()) { if (c instanceof Applet || c instanceof Window) { break; } else if (c instanceof JPopupMenu) { return true; } } return false; } void cancelPopupMenu() { // We should ungrab window if a user code throws // an unexpected runtime exception. See 6495920. try { // 4234793: This action should call firePopupMenuCanceled but it's // a protected method. The real solution could be to make // firePopupMenuCanceled public and call it directly. List popups = getPopups(); Iterator iter = popups.iterator(); while (iter.hasNext()) { JPopupMenu popup = (JPopupMenu) iter.next(); popup.putClientProperty("JPopupMenu.firePopupMenuCanceled", Boolean.TRUE); } MenuSelectionManager.defaultManager().clearSelectedPath(); } catch (RuntimeException ex) { realUngrabWindow(); throw ex; } catch (Error err) { realUngrabWindow(); throw err; } } public void componentResized(ComponentEvent e) { cancelPopupMenu(); } public void componentMoved(ComponentEvent e) { cancelPopupMenu(); } public void componentShown(ComponentEvent e) { cancelPopupMenu(); } public void componentHidden(ComponentEvent e) { cancelPopupMenu(); } public void windowClosing(WindowEvent e) { cancelPopupMenu(); } public void windowClosed(WindowEvent e) { cancelPopupMenu(); } public void windowIconified(WindowEvent e) { cancelPopupMenu(); } public void windowDeactivated(WindowEvent e) { cancelPopupMenu(); } public void windowOpened(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} } /** {@collect.stats} * This helper is added to MenuSelectionManager as a ChangeListener to * listen to menu selection changes. When a menu is activated, it passes * focus to its parent JRootPane, and installs an ActionMap/InputMap pair * on that JRootPane. Those maps are necessary in order for menu * navigation to work. When menu is being deactivated, it restores focus * to the component that has had it before menu activation, and uninstalls * the maps. * This helper is also installed as a KeyListener on root pane when menu * is active. It forwards key events to MenuSelectionManager for mnemonic * keys handling. */ static class MenuKeyboardHelper implements ChangeListener, KeyListener { private Component lastFocused = null; private MenuElement[] lastPathSelected = new MenuElement[0]; private JPopupMenu lastPopup; private JRootPane invokerRootPane; private ActionMap menuActionMap = getActionMap(); private InputMap menuInputMap; private boolean focusTraversalKeysEnabled; /* * Fix for 4213634 * If this is false, KEY_TYPED and KEY_RELEASED events are NOT * processed. This is needed to avoid activating a menuitem when * the menu and menuitem share the same mnemonic. */ private boolean receivedKeyPressed = false; void removeItems() { if (lastFocused != null) { if(!lastFocused.requestFocusInWindow()) { // Workarounr for 4810575. // If lastFocused is not in currently focused window // requestFocusInWindow will fail. In this case we must // request focus by requestFocus() if it was not // transferred from our popup. Window cfw = KeyboardFocusManager .getCurrentKeyboardFocusManager() .getFocusedWindow(); if(cfw != null && "###focusableSwingPopup###".equals(cfw.getName())) { lastFocused.requestFocus(); } } lastFocused = null; } if (invokerRootPane != null) { invokerRootPane.removeKeyListener(this); invokerRootPane.setFocusTraversalKeysEnabled(focusTraversalKeysEnabled); removeUIInputMap(invokerRootPane, menuInputMap); removeUIActionMap(invokerRootPane, menuActionMap); invokerRootPane = null; } receivedKeyPressed = false; } private FocusListener rootPaneFocusListener = new FocusAdapter() { public void focusGained(FocusEvent ev) { Component opposite = ev.getOppositeComponent(); if (opposite != null) { lastFocused = opposite; } ev.getComponent().removeFocusListener(this); } }; /** {@collect.stats} * Return the last JPopupMenu in <code>path</code>, * or <code>null</code> if none found */ JPopupMenu getActivePopup(MenuElement[] path) { for (int i=path.length-1; i>=0; i--) { MenuElement elem = path[i]; if (elem instanceof JPopupMenu) { return (JPopupMenu)elem; } } return null; } void addUIInputMap(JComponent c, InputMap map) { InputMap lastNonUI = null; InputMap parent = c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); while (parent != null && !(parent instanceof UIResource)) { lastNonUI = parent; parent = parent.getParent(); } if (lastNonUI == null) { c.setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, map); } else { lastNonUI.setParent(map); } map.setParent(parent); } void addUIActionMap(JComponent c, ActionMap map) { ActionMap lastNonUI = null; ActionMap parent = c.getActionMap(); while (parent != null && !(parent instanceof UIResource)) { lastNonUI = parent; parent = parent.getParent(); } if (lastNonUI == null) { c.setActionMap(map); } else { lastNonUI.setParent(map); } map.setParent(parent); } void removeUIInputMap(JComponent c, InputMap map) { InputMap im = null; InputMap parent = c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); while (parent != null) { if (parent == map) { if (im == null) { c.setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, map.getParent()); } else { im.setParent(map.getParent()); } break; } im = parent; parent = parent.getParent(); } } void removeUIActionMap(JComponent c, ActionMap map) { ActionMap im = null; ActionMap parent = c.getActionMap(); while (parent != null) { if (parent == map) { if (im == null) { c.setActionMap(map.getParent()); } else { im.setParent(map.getParent()); } break; } im = parent; parent = parent.getParent(); } } public void stateChanged(ChangeEvent ev) { if (!(UIManager.getLookAndFeel() instanceof BasicLookAndFeel)) { uninstall(); return; } MenuSelectionManager msm = (MenuSelectionManager)ev.getSource(); MenuElement[] p = msm.getSelectedPath(); JPopupMenu popup = getActivePopup(p); if (popup != null && !popup.isFocusable()) { // Do nothing for non-focusable popups return; } if (lastPathSelected.length != 0 && p.length != 0 ) { if (!checkInvokerEqual(p[0],lastPathSelected[0])) { removeItems(); lastPathSelected = new MenuElement[0]; } } if (lastPathSelected.length == 0 && p.length > 0) { // menu posted JComponent invoker; if (popup == null) { if (p.length == 2 && p[0] instanceof JMenuBar && p[1] instanceof JMenu) { // a menu has been selected but not open invoker = (JComponent)p[1]; popup = ((JMenu)invoker).getPopupMenu(); } else { return; } } else { Component c = popup.getInvoker(); if(c instanceof JFrame) { invoker = ((JFrame)c).getRootPane(); } else if(c instanceof JDialog) { invoker = ((JDialog)c).getRootPane(); } else if(c instanceof JApplet) { invoker = ((JApplet)c).getRootPane(); } else { while (!(c instanceof JComponent)) { if (c == null) { return; } c = c.getParent(); } invoker = (JComponent)c; } } // remember current focus owner lastFocused = KeyboardFocusManager. getCurrentKeyboardFocusManager().getFocusOwner(); // request focus on root pane and install keybindings // used for menu navigation invokerRootPane = SwingUtilities.getRootPane(invoker); if (invokerRootPane != null) { invokerRootPane.addFocusListener(rootPaneFocusListener); invokerRootPane.requestFocus(true); invokerRootPane.addKeyListener(this); focusTraversalKeysEnabled = invokerRootPane. getFocusTraversalKeysEnabled(); invokerRootPane.setFocusTraversalKeysEnabled(false); menuInputMap = getInputMap(popup, invokerRootPane); addUIInputMap(invokerRootPane, menuInputMap); addUIActionMap(invokerRootPane, menuActionMap); } } else if (lastPathSelected.length != 0 && p.length == 0) { // menu hidden -- return focus to where it had been before // and uninstall menu keybindings removeItems(); } else { if (popup != lastPopup) { receivedKeyPressed = false; } } // Remember the last path selected lastPathSelected = p; lastPopup = popup; } public void keyPressed(KeyEvent ev) { receivedKeyPressed = true; MenuSelectionManager.defaultManager().processKeyEvent(ev); } public void keyReleased(KeyEvent ev) { if (receivedKeyPressed) { receivedKeyPressed = false; MenuSelectionManager.defaultManager().processKeyEvent(ev); } } public void keyTyped(KeyEvent ev) { if (receivedKeyPressed) { MenuSelectionManager.defaultManager().processKeyEvent(ev); } } void uninstall() { synchronized (MENU_KEYBOARD_HELPER_KEY) { MenuSelectionManager.defaultManager().removeChangeListener(this); AppContext.getAppContext().remove(MENU_KEYBOARD_HELPER_KEY); } } } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Color; import javax.swing.*; import javax.swing.plaf.UIResource; /** {@collect.stats} * JButton object that draws a scaled Arrow in one of the cardinal directions. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author David Kloba */ public class BasicArrowButton extends JButton implements SwingConstants { /** {@collect.stats} * The direction of the arrow. One of * {@code SwingConstants.NORTH}, {@code SwingConstants.SOUTH}, * {@code SwingConstants.EAST} or {@code SwingConstants.WEST}. */ protected int direction; private Color shadow; private Color darkShadow; private Color highlight; /** {@collect.stats} * Creates a {@code BasicArrowButton} whose arrow * is drawn in the specified direction and with the specified * colors. * * @param direction the direction of the arrow; one of * {@code SwingConstants.NORTH}, {@code SwingConstants.SOUTH}, * {@code SwingConstants.EAST} or {@code SwingConstants.WEST} * @param background the background color of the button * @param shadow the color of the shadow * @param darkShadow the color of the dark shadow * @param highlight the color of the highlight * @since 1.4 */ public BasicArrowButton(int direction, Color background, Color shadow, Color darkShadow, Color highlight) { super(); setRequestFocusEnabled(false); setDirection(direction); setBackground(background); this.shadow = shadow; this.darkShadow = darkShadow; this.highlight = highlight; } /** {@collect.stats} * Creates a {@code BasicArrowButton} whose arrow * is drawn in the specified direction. * * @param direction the direction of the arrow; one of * {@code SwingConstants.NORTH}, {@code SwingConstants.SOUTH}, * {@code SwingConstants.EAST} or {@code SwingConstants.WEST} */ public BasicArrowButton(int direction) { this(direction, UIManager.getColor("control"), UIManager.getColor("controlShadow"), UIManager.getColor("controlDkShadow"), UIManager.getColor("controlLtHighlight")); } /** {@collect.stats} * Returns the direction of the arrow. */ public int getDirection() { return direction; } /** {@collect.stats} * Sets the direction of the arrow. * * @param direction the direction of the arrow; one of * of {@code SwingConstants.NORTH}, * {@code SwingConstants.SOUTH}, * {@code SwingConstants.EAST} or {@code SwingConstants.WEST} */ public void setDirection(int direction) { this.direction = direction; } public void paint(Graphics g) { Color origColor; boolean isPressed, isEnabled; int w, h, size; w = getSize().width; h = getSize().height; origColor = g.getColor(); isPressed = getModel().isPressed(); isEnabled = isEnabled(); g.setColor(getBackground()); g.fillRect(1, 1, w-2, h-2); /// Draw the proper Border if (getBorder() != null && !(getBorder() instanceof UIResource)) { paintBorder(g); } else if (isPressed) { g.setColor(shadow); g.drawRect(0, 0, w-1, h-1); } else { // Using the background color set above g.drawLine(0, 0, 0, h-1); g.drawLine(1, 0, w-2, 0); g.setColor(highlight); // inner 3D border g.drawLine(1, 1, 1, h-3); g.drawLine(2, 1, w-3, 1); g.setColor(shadow); // inner 3D border g.drawLine(1, h-2, w-2, h-2); g.drawLine(w-2, 1, w-2, h-3); g.setColor(darkShadow); // black drop shadow __| g.drawLine(0, h-1, w-1, h-1); g.drawLine(w-1, h-1, w-1, 0); } // If there's no room to draw arrow, bail if(h < 5 || w < 5) { g.setColor(origColor); return; } if (isPressed) { g.translate(1, 1); } // Draw the arrow size = Math.min((h - 4) / 3, (w - 4) / 3); size = Math.max(size, 2); paintTriangle(g, (w - size) / 2, (h - size) / 2, size, direction, isEnabled); // Reset the Graphics back to it's original settings if (isPressed) { g.translate(-1, -1); } g.setColor(origColor); } /** {@collect.stats} * Returns the preferred size of the {@code BasicArrowButton}. * * @return the preferred size */ public Dimension getPreferredSize() { return new Dimension(16, 16); } /** {@collect.stats} * Returns the minimum size of the {@code BasicArrowButton}. * * @return the minimum size */ public Dimension getMinimumSize() { return new Dimension(5, 5); } /** {@collect.stats} * Returns the maximum size of the {@code BasicArrowButton}. * * @return the maximum size */ public Dimension getMaximumSize() { return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } /** {@collect.stats} * Returns whether the arrow button should get the focus. * {@code BasicArrowButton}s are used as a child component of * composite components such as {@code JScrollBar} and * {@code JComboBox}. Since the composite component typically gets the * focus, this method is overriden to return {@code false}. * * @return {@code false} */ public boolean isFocusTraversable() { return false; } /** {@collect.stats} * Paints a triangle. * * @param g the {@code Graphics} to draw to * @param x the x coordinate * @param y the y coordinate * @param size the size of the triangle to draw * @param direction the direction in which to draw the arrow; * one of {@code SwingConstants.NORTH}, * {@code SwingConstants.SOUTH}, {@code SwingConstants.EAST} or * {@code SwingConstants.WEST} * @param isEnabled whether or not the arrow is drawn enabled */ public void paintTriangle(Graphics g, int x, int y, int size, int direction, boolean isEnabled) { Color oldColor = g.getColor(); int mid, i, j; j = 0; size = Math.max(size, 2); mid = (size / 2) - 1; g.translate(x, y); if(isEnabled) g.setColor(darkShadow); else g.setColor(shadow); switch(direction) { case NORTH: for(i = 0; i < size; i++) { g.drawLine(mid-i, i, mid+i, i); } if(!isEnabled) { g.setColor(highlight); g.drawLine(mid-i+2, i, mid+i, i); } break; case SOUTH: if(!isEnabled) { g.translate(1, 1); g.setColor(highlight); for(i = size-1; i >= 0; i--) { g.drawLine(mid-i, j, mid+i, j); j++; } g.translate(-1, -1); g.setColor(shadow); } j = 0; for(i = size-1; i >= 0; i--) { g.drawLine(mid-i, j, mid+i, j); j++; } break; case WEST: for(i = 0; i < size; i++) { g.drawLine(i, mid-i, i, mid+i); } if(!isEnabled) { g.setColor(highlight); g.drawLine(i, mid-i+2, i, mid+i); } break; case EAST: if(!isEnabled) { g.translate(1, 1); g.setColor(highlight); for(i = size-1; i >= 0; i--) { g.drawLine(j, mid-i, j, mid+i); j++; } g.translate(-1, -1); g.setColor(shadow); } j = 0; for(i = size-1; i >= 0; i--) { g.drawLine(j, mid-i, j, mid+i); j++; } break; } g.translate(-x, -y); g.setColor(oldColor); } }
Java
/* * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.swing.*; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.Rectangle; import javax.swing.plaf.ComponentUI; /** {@collect.stats} * A Basic L&F implementation of PopupMenuSeparatorUI. This implementation * is a "combined" view/controller. * * @author Jeff Shapiro */ public class BasicPopupMenuSeparatorUI extends BasicSeparatorUI { public static ComponentUI createUI( JComponent c ) { return new BasicPopupMenuSeparatorUI(); } public void paint( Graphics g, JComponent c ) { Dimension s = c.getSize(); g.setColor( c.getForeground() ); g.drawLine( 0, 0, s.width, 0 ); g.setColor( c.getBackground() ); g.drawLine( 0, 1, s.width, 1 ); } public Dimension getPreferredSize( JComponent c ) { return new Dimension( 0, 2 ); } }
Java
/* * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.swing.*; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.Rectangle; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.SeparatorUI; /** {@collect.stats} * A Basic L&F implementation of SeparatorUI. This implementation * is a "combined" view/controller. * * @author Georges Saab * @author Jeff Shapiro */ public class BasicSeparatorUI extends SeparatorUI { protected Color shadow; protected Color highlight; public static ComponentUI createUI( JComponent c ) { return new BasicSeparatorUI(); } public void installUI( JComponent c ) { installDefaults( (JSeparator)c ); installListeners( (JSeparator)c ); } public void uninstallUI(JComponent c) { uninstallDefaults( (JSeparator)c ); uninstallListeners( (JSeparator)c ); } protected void installDefaults( JSeparator s ) { LookAndFeel.installColors( s, "Separator.background", "Separator.foreground" ); LookAndFeel.installProperty( s, "opaque", Boolean.FALSE); } protected void uninstallDefaults( JSeparator s ) { } protected void installListeners( JSeparator s ) { } protected void uninstallListeners( JSeparator s ) { } public void paint( Graphics g, JComponent c ) { Dimension s = c.getSize(); if ( ((JSeparator)c).getOrientation() == JSeparator.VERTICAL ) { g.setColor( c.getForeground() ); g.drawLine( 0, 0, 0, s.height ); g.setColor( c.getBackground() ); g.drawLine( 1, 0, 1, s.height ); } else // HORIZONTAL { g.setColor( c.getForeground() ); g.drawLine( 0, 0, s.width, 0 ); g.setColor( c.getBackground() ); g.drawLine( 0, 1, s.width, 1 ); } } public Dimension getPreferredSize( JComponent c ) { if ( ((JSeparator)c).getOrientation() == JSeparator.VERTICAL ) return new Dimension( 2, 0 ); else return new Dimension( 0, 2 ); } public Dimension getMinimumSize( JComponent c ) { return null; } public Dimension getMaximumSize( JComponent c ) { return null; } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import sun.swing.SwingUtilities2; import sun.awt.AppContext; import java.awt.*; import java.awt.event.*; import java.io.Serializable; import javax.swing.*; import javax.swing.border.*; import java.awt.*; import java.awt.event.*; import javax.swing.plaf.ButtonUI; import javax.swing.plaf.UIResource; import javax.swing.plaf.ComponentUI; import javax.swing.text.View; /** {@collect.stats} * BasicButton implementation * * @author Jeff Dinkins */ public class BasicButtonUI extends ButtonUI{ // Visual constants // NOTE: This is not used or set any where. Were we allowed to remove // fields, this would be removed. protected int defaultTextIconGap; // Amount to offset text, the value of this comes from // defaultTextShiftOffset once setTextShiftOffset has been invoked. private int shiftOffset = 0; // Value that is set in shiftOffset once setTextShiftOffset has been // invoked. The value of this comes from the defaults table. protected int defaultTextShiftOffset; private final static String propertyPrefix = "Button" + "."; private static final Object BASIC_BUTTON_UI_KEY = new Object(); // ******************************** // Create PLAF // ******************************** public static ComponentUI createUI(JComponent c) { AppContext appContext = AppContext.getAppContext(); BasicButtonUI buttonUI = (BasicButtonUI) appContext.get(BASIC_BUTTON_UI_KEY); if (buttonUI == null) { buttonUI = new BasicButtonUI(); appContext.put(BASIC_BUTTON_UI_KEY, buttonUI); } return buttonUI; } protected String getPropertyPrefix() { return propertyPrefix; } // ******************************** // Install PLAF // ******************************** public void installUI(JComponent c) { installDefaults((AbstractButton) c); installListeners((AbstractButton) c); installKeyboardActions((AbstractButton) c); BasicHTML.updateRenderer(c, ((AbstractButton) c).getText()); } protected void installDefaults(AbstractButton b) { // load shared instance defaults String pp = getPropertyPrefix(); defaultTextShiftOffset = UIManager.getInt(pp + "textShiftOffset"); // set the following defaults on the button if (b.isContentAreaFilled()) { LookAndFeel.installProperty(b, "opaque", Boolean.TRUE); } else { LookAndFeel.installProperty(b, "opaque", Boolean.FALSE); } if(b.getMargin() == null || (b.getMargin() instanceof UIResource)) { b.setMargin(UIManager.getInsets(pp + "margin")); } LookAndFeel.installColorsAndFont(b, pp + "background", pp + "foreground", pp + "font"); LookAndFeel.installBorder(b, pp + "border"); Object rollover = UIManager.get(pp + "rollover"); if (rollover != null) { LookAndFeel.installProperty(b, "rolloverEnabled", rollover); } LookAndFeel.installProperty(b, "iconTextGap", new Integer(4)); } protected void installListeners(AbstractButton b) { BasicButtonListener listener = createButtonListener(b); if(listener != null) { b.addMouseListener(listener); b.addMouseMotionListener(listener); b.addFocusListener(listener); b.addPropertyChangeListener(listener); b.addChangeListener(listener); } } protected void installKeyboardActions(AbstractButton b){ BasicButtonListener listener = getButtonListener(b); if(listener != null) { listener.installKeyboardActions(b); } } // ******************************** // Uninstall PLAF // ******************************** public void uninstallUI(JComponent c) { uninstallKeyboardActions((AbstractButton) c); uninstallListeners((AbstractButton) c); uninstallDefaults((AbstractButton) c); BasicHTML.updateRenderer(c, ""); } protected void uninstallKeyboardActions(AbstractButton b) { BasicButtonListener listener = getButtonListener(b); if(listener != null) { listener.uninstallKeyboardActions(b); } } protected void uninstallListeners(AbstractButton b) { BasicButtonListener listener = getButtonListener(b); if(listener != null) { b.removeMouseListener(listener); b.removeMouseMotionListener(listener); b.removeFocusListener(listener); b.removeChangeListener(listener); b.removePropertyChangeListener(listener); } } protected void uninstallDefaults(AbstractButton b) { LookAndFeel.uninstallBorder(b); } // ******************************** // Create Listeners // ******************************** protected BasicButtonListener createButtonListener(AbstractButton b) { return new BasicButtonListener(b); } public int getDefaultTextIconGap(AbstractButton b) { return defaultTextIconGap; } /* These rectangles/insets are allocated once for all * ButtonUI.paint() calls. Re-using rectangles rather than * allocating them in each paint call substantially reduced the time * it took paint to run. Obviously, this method can't be re-entered. */ private static Rectangle viewRect = new Rectangle(); private static Rectangle textRect = new Rectangle(); private static Rectangle iconRect = new Rectangle(); // ******************************** // Paint Methods // ******************************** public void paint(Graphics g, JComponent c) { AbstractButton b = (AbstractButton) c; ButtonModel model = b.getModel(); String text = layout(b, SwingUtilities2.getFontMetrics(b, g), b.getWidth(), b.getHeight()); clearTextShiftOffset(); // perform UI specific press action, e.g. Windows L&F shifts text if (model.isArmed() && model.isPressed()) { paintButtonPressed(g,b); } // Paint the Icon if(b.getIcon() != null) { paintIcon(g,c,iconRect); } if (text != null && !text.equals("")){ View v = (View) c.getClientProperty(BasicHTML.propertyKey); if (v != null) { v.paint(g, textRect); } else { paintText(g, b, textRect, text); } } if (b.isFocusPainted() && b.hasFocus()) { // paint UI specific focus paintFocus(g,b,viewRect,textRect,iconRect); } } protected void paintIcon(Graphics g, JComponent c, Rectangle iconRect){ AbstractButton b = (AbstractButton) c; ButtonModel model = b.getModel(); Icon icon = b.getIcon(); Icon tmpIcon = null; if(icon == null) { return; } Icon selectedIcon = null; /* the fallback icon should be based on the selected state */ if (model.isSelected()) { selectedIcon = (Icon) b.getSelectedIcon(); if (selectedIcon != null) { icon = selectedIcon; } } if(!model.isEnabled()) { if(model.isSelected()) { tmpIcon = (Icon) b.getDisabledSelectedIcon(); if (tmpIcon == null) { tmpIcon = selectedIcon; } } if (tmpIcon == null) { tmpIcon = (Icon) b.getDisabledIcon(); } } else if(model.isPressed() && model.isArmed()) { tmpIcon = (Icon) b.getPressedIcon(); if(tmpIcon != null) { // revert back to 0 offset clearTextShiftOffset(); } } else if(b.isRolloverEnabled() && model.isRollover()) { if(model.isSelected()) { tmpIcon = (Icon) b.getRolloverSelectedIcon(); if (tmpIcon == null) { tmpIcon = selectedIcon; } } if (tmpIcon == null) { tmpIcon = (Icon) b.getRolloverIcon(); } } if(tmpIcon != null) { icon = tmpIcon; } if(model.isPressed() && model.isArmed()) { icon.paintIcon(c, g, iconRect.x + getTextShiftOffset(), iconRect.y + getTextShiftOffset()); } else { icon.paintIcon(c, g, iconRect.x, iconRect.y); } } /** {@collect.stats} * As of Java 2 platform v 1.4 this method should not be used or overriden. * Use the paintText method which takes the AbstractButton argument. */ protected void paintText(Graphics g, JComponent c, Rectangle textRect, String text) { AbstractButton b = (AbstractButton) c; ButtonModel model = b.getModel(); FontMetrics fm = SwingUtilities2.getFontMetrics(c, g); int mnemonicIndex = b.getDisplayedMnemonicIndex(); /* Draw the Text */ if(model.isEnabled()) { /** {@collect.stats}* paint the text normally */ g.setColor(b.getForeground()); SwingUtilities2.drawStringUnderlineCharAt(c, g,text, mnemonicIndex, textRect.x + getTextShiftOffset(), textRect.y + fm.getAscent() + getTextShiftOffset()); } else { /** {@collect.stats}* paint the text disabled ***/ g.setColor(b.getBackground().brighter()); SwingUtilities2.drawStringUnderlineCharAt(c, g,text, mnemonicIndex, textRect.x, textRect.y + fm.getAscent()); g.setColor(b.getBackground().darker()); SwingUtilities2.drawStringUnderlineCharAt(c, g,text, mnemonicIndex, textRect.x - 1, textRect.y + fm.getAscent() - 1); } } /** {@collect.stats} * Method which renders the text of the current button. * <p> * @param g Graphics context * @param b Current button to render * @param textRect Bounding rectangle to render the text. * @param text String to render * @since 1.4 */ protected void paintText(Graphics g, AbstractButton b, Rectangle textRect, String text) { paintText(g, (JComponent)b, textRect, text); } // Method signature defined here overriden in subclasses. // Perhaps this class should be abstract? protected void paintFocus(Graphics g, AbstractButton b, Rectangle viewRect, Rectangle textRect, Rectangle iconRect){ } protected void paintButtonPressed(Graphics g, AbstractButton b){ } protected void clearTextShiftOffset(){ this.shiftOffset = 0; } protected void setTextShiftOffset(){ this.shiftOffset = defaultTextShiftOffset; } protected int getTextShiftOffset() { return shiftOffset; } // ******************************** // Layout Methods // ******************************** public Dimension getMinimumSize(JComponent c) { Dimension d = getPreferredSize(c); View v = (View) c.getClientProperty(BasicHTML.propertyKey); if (v != null) { d.width -= v.getPreferredSpan(View.X_AXIS) - v.getMinimumSpan(View.X_AXIS); } return d; } public Dimension getPreferredSize(JComponent c) { AbstractButton b = (AbstractButton)c; return BasicGraphicsUtils.getPreferredButtonSize(b, b.getIconTextGap()); } public Dimension getMaximumSize(JComponent c) { Dimension d = getPreferredSize(c); View v = (View) c.getClientProperty(BasicHTML.propertyKey); if (v != null) { d.width += v.getMaximumSpan(View.X_AXIS) - v.getPreferredSpan(View.X_AXIS); } return d; } /** {@collect.stats} * Returns the baseline. * * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public int getBaseline(JComponent c, int width, int height) { super.getBaseline(c, width, height); AbstractButton b = (AbstractButton)c; String text = b.getText(); if (text == null || "".equals(text)) { return -1; } FontMetrics fm = b.getFontMetrics(b.getFont()); layout(b, fm, width, height); return BasicHTML.getBaseline(b, textRect.y, fm.getAscent(), textRect.width, textRect.height); } /** {@collect.stats} * Returns an enum indicating how the baseline of the component * changes as the size changes. * * @throws NullPointerException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public Component.BaselineResizeBehavior getBaselineResizeBehavior( JComponent c) { super.getBaselineResizeBehavior(c); if (c.getClientProperty(BasicHTML.propertyKey) != null) { return Component.BaselineResizeBehavior.OTHER; } switch(((AbstractButton)c).getVerticalAlignment()) { case AbstractButton.TOP: return Component.BaselineResizeBehavior.CONSTANT_ASCENT; case AbstractButton.BOTTOM: return Component.BaselineResizeBehavior.CONSTANT_DESCENT; case AbstractButton.CENTER: return Component.BaselineResizeBehavior.CENTER_OFFSET; } return Component.BaselineResizeBehavior.OTHER; } private String layout(AbstractButton b, FontMetrics fm, int width, int height) { Insets i = b.getInsets(); viewRect.x = i.left; viewRect.y = i.top; viewRect.width = width - (i.right + viewRect.x); viewRect.height = height - (i.bottom + viewRect.y); textRect.x = textRect.y = textRect.width = textRect.height = 0; iconRect.x = iconRect.y = iconRect.width = iconRect.height = 0; // layout the text and icon return SwingUtilities.layoutCompoundLabel( b, fm, b.getText(), b.getIcon(), b.getVerticalAlignment(), b.getHorizontalAlignment(), b.getVerticalTextPosition(), b.getHorizontalTextPosition(), viewRect, iconRect, textRect, b.getText() == null ? 0 : b.getIconTextGap()); } /** {@collect.stats} * Returns the ButtonListener for the passed in Button, or null if one * could not be found. */ private BasicButtonListener getButtonListener(AbstractButton b) { MouseMotionListener[] listeners = b.getMouseMotionListeners(); if (listeners != null) { for (int counter = 0; counter < listeners.length; counter++) { if (listeners[counter] instanceof BasicButtonListener) { return (BasicButtonListener)listeners[counter]; } } } return null; } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import sun.swing.DefaultLookup; import sun.swing.UIAction; import java.awt.*; import java.awt.event.*; import java.beans.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.*; /** {@collect.stats} * Implementation of ScrollBarUI for the Basic Look and Feel * * @author Rich Schiavi * @author David Kloba * @author Hans Muller */ public class BasicScrollBarUI extends ScrollBarUI implements LayoutManager, SwingConstants { private static final int POSITIVE_SCROLL = 1; private static final int NEGATIVE_SCROLL = -1; private static final int MIN_SCROLL = 2; private static final int MAX_SCROLL = 3; // NOTE: DO NOT use this field directly, SynthScrollBarUI assumes you'll // call getMinimumThumbSize to access it. protected Dimension minimumThumbSize; protected Dimension maximumThumbSize; protected Color thumbHighlightColor; protected Color thumbLightShadowColor; protected Color thumbDarkShadowColor; protected Color thumbColor; protected Color trackColor; protected Color trackHighlightColor; protected JScrollBar scrollbar; protected JButton incrButton; protected JButton decrButton; protected boolean isDragging; protected TrackListener trackListener; protected ArrowButtonListener buttonListener; protected ModelListener modelListener; protected Rectangle thumbRect; protected Rectangle trackRect; protected int trackHighlight; protected static final int NO_HIGHLIGHT = 0; protected static final int DECREASE_HIGHLIGHT = 1; protected static final int INCREASE_HIGHLIGHT = 2; protected ScrollListener scrollListener; protected PropertyChangeListener propertyChangeListener; protected Timer scrollTimer; private final static int scrollSpeedThrottle = 60; // delay in milli seconds /** {@collect.stats} True indicates a middle click will absolutely position the * scrollbar. */ private boolean supportsAbsolutePositioning; /** {@collect.stats} Hint as to what width (when vertical) or height (when horizontal) * should be. */ private int scrollBarWidth; private Handler handler; private boolean thumbActive; /** {@collect.stats} * Determine whether scrollbar layout should use cached value or adjusted * value returned by scrollbar's <code>getValue</code>. */ private boolean useCachedValue = false; /** {@collect.stats} * The scrollbar value is cached to save real value if the view is adjusted. */ private int scrollBarValue; /** {@collect.stats} * Distance between the increment button and the track. This may be a negative * number. If negative, then an overlap between the button and track will occur, * which is useful for shaped buttons. * * TODO This should be made protected in a feature release */ private int incrGap; /** {@collect.stats} * Distance between the decrement button and the track. This may be a negative * number. If negative, then an overlap between the button and track will occur, * which is useful for shaped buttons. * * TODO This should be made protected in a feature release */ private int decrGap; static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.POSITIVE_UNIT_INCREMENT)); map.put(new Actions(Actions.POSITIVE_BLOCK_INCREMENT)); map.put(new Actions(Actions.NEGATIVE_UNIT_INCREMENT)); map.put(new Actions(Actions.NEGATIVE_BLOCK_INCREMENT)); map.put(new Actions(Actions.MIN_SCROLL)); map.put(new Actions(Actions.MAX_SCROLL)); } public static ComponentUI createUI(JComponent c) { return new BasicScrollBarUI(); } protected void configureScrollBarColors() { LookAndFeel.installColors(scrollbar, "ScrollBar.background", "ScrollBar.foreground"); thumbHighlightColor = UIManager.getColor("ScrollBar.thumbHighlight"); thumbLightShadowColor = UIManager.getColor("ScrollBar.thumbShadow"); thumbDarkShadowColor = UIManager.getColor("ScrollBar.thumbDarkShadow"); thumbColor = UIManager.getColor("ScrollBar.thumb"); trackColor = UIManager.getColor("ScrollBar.track"); trackHighlightColor = UIManager.getColor("ScrollBar.trackHighlight"); } public void installUI(JComponent c) { scrollbar = (JScrollBar)c; thumbRect = new Rectangle(0, 0, 0, 0); trackRect = new Rectangle(0, 0, 0, 0); installDefaults(); installComponents(); installListeners(); installKeyboardActions(); } public void uninstallUI(JComponent c) { scrollbar = (JScrollBar)c; uninstallListeners(); uninstallDefaults(); uninstallComponents(); uninstallKeyboardActions(); thumbRect = null; scrollbar = null; incrButton = null; decrButton = null; } protected void installDefaults() { scrollBarWidth = UIManager.getInt("ScrollBar.width"); if (scrollBarWidth <= 0) { scrollBarWidth = 16; } minimumThumbSize = (Dimension)UIManager.get("ScrollBar.minimumThumbSize"); maximumThumbSize = (Dimension)UIManager.get("ScrollBar.maximumThumbSize"); Boolean absB = (Boolean)UIManager.get("ScrollBar.allowsAbsolutePositioning"); supportsAbsolutePositioning = (absB != null) ? absB.booleanValue() : false; trackHighlight = NO_HIGHLIGHT; if (scrollbar.getLayout() == null || (scrollbar.getLayout() instanceof UIResource)) { scrollbar.setLayout(this); } configureScrollBarColors(); LookAndFeel.installBorder(scrollbar, "ScrollBar.border"); LookAndFeel.installProperty(scrollbar, "opaque", Boolean.TRUE); scrollBarValue = scrollbar.getValue(); incrGap = UIManager.getInt("ScrollBar.incrementButtonGap"); decrGap = UIManager.getInt("ScrollBar.decrementButtonGap"); // TODO this can be removed when incrGap/decrGap become protected // handle scaling for sizeVarients for special case components. The // key "JComponent.sizeVariant" scales for large/small/mini // components are based on Apples LAF String scaleKey = (String)scrollbar.getClientProperty( "JComponent.sizeVariant"); if (scaleKey != null){ if ("large".equals(scaleKey)){ scrollBarWidth *= 1.15; incrGap *= 1.15; decrGap *= 1.15; } else if ("small".equals(scaleKey)){ scrollBarWidth *= 0.857; incrGap *= 0.857; decrGap *= 0.714; } else if ("mini".equals(scaleKey)){ scrollBarWidth *= 0.714; incrGap *= 0.714; decrGap *= 0.714; } } } protected void installComponents(){ switch (scrollbar.getOrientation()) { case JScrollBar.VERTICAL: incrButton = createIncreaseButton(SOUTH); decrButton = createDecreaseButton(NORTH); break; case JScrollBar.HORIZONTAL: if (scrollbar.getComponentOrientation().isLeftToRight()) { incrButton = createIncreaseButton(EAST); decrButton = createDecreaseButton(WEST); } else { incrButton = createIncreaseButton(WEST); decrButton = createDecreaseButton(EAST); } break; } scrollbar.add(incrButton); scrollbar.add(decrButton); // Force the children's enabled state to be updated. scrollbar.setEnabled(scrollbar.isEnabled()); } protected void uninstallComponents(){ scrollbar.remove(incrButton); scrollbar.remove(decrButton); } protected void installListeners(){ trackListener = createTrackListener(); buttonListener = createArrowButtonListener(); modelListener = createModelListener(); propertyChangeListener = createPropertyChangeListener(); scrollbar.addMouseListener(trackListener); scrollbar.addMouseMotionListener(trackListener); scrollbar.getModel().addChangeListener(modelListener); scrollbar.addPropertyChangeListener(propertyChangeListener); scrollbar.addFocusListener(getHandler()); if (incrButton != null) { incrButton.addMouseListener(buttonListener); } if (decrButton != null) { decrButton.addMouseListener(buttonListener); } scrollListener = createScrollListener(); scrollTimer = new Timer(scrollSpeedThrottle, scrollListener); scrollTimer.setInitialDelay(300); // default InitialDelay? } protected void installKeyboardActions(){ LazyActionMap.installLazyActionMap(scrollbar, BasicScrollBarUI.class, "ScrollBar.actionMap"); InputMap inputMap = getInputMap(JComponent.WHEN_FOCUSED); SwingUtilities.replaceUIInputMap(scrollbar, JComponent.WHEN_FOCUSED, inputMap); inputMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); SwingUtilities.replaceUIInputMap(scrollbar, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, inputMap); } protected void uninstallKeyboardActions(){ SwingUtilities.replaceUIInputMap(scrollbar, JComponent.WHEN_FOCUSED, null); SwingUtilities.replaceUIActionMap(scrollbar, null); } private InputMap getInputMap(int condition) { if (condition == JComponent.WHEN_FOCUSED) { InputMap keyMap = (InputMap)DefaultLookup.get( scrollbar, this, "ScrollBar.focusInputMap"); InputMap rtlKeyMap; if (scrollbar.getComponentOrientation().isLeftToRight() || ((rtlKeyMap = (InputMap)DefaultLookup.get(scrollbar, this, "ScrollBar.focusInputMap.RightToLeft")) == null)) { return keyMap; } else { rtlKeyMap.setParent(keyMap); return rtlKeyMap; } } else if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) { InputMap keyMap = (InputMap)DefaultLookup.get( scrollbar, this, "ScrollBar.ancestorInputMap"); InputMap rtlKeyMap; if (scrollbar.getComponentOrientation().isLeftToRight() || ((rtlKeyMap = (InputMap)DefaultLookup.get(scrollbar, this, "ScrollBar.ancestorInputMap.RightToLeft")) == null)) { return keyMap; } else { rtlKeyMap.setParent(keyMap); return rtlKeyMap; } } return null; } protected void uninstallListeners() { scrollTimer.stop(); scrollTimer = null; if (decrButton != null){ decrButton.removeMouseListener(buttonListener); } if (incrButton != null){ incrButton.removeMouseListener(buttonListener); } scrollbar.getModel().removeChangeListener(modelListener); scrollbar.removeMouseListener(trackListener); scrollbar.removeMouseMotionListener(trackListener); scrollbar.removePropertyChangeListener(propertyChangeListener); scrollbar.removeFocusListener(getHandler()); handler = null; } protected void uninstallDefaults(){ LookAndFeel.uninstallBorder(scrollbar); if (scrollbar.getLayout() == this) { scrollbar.setLayout(null); } } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } protected TrackListener createTrackListener(){ return new TrackListener(); } protected ArrowButtonListener createArrowButtonListener(){ return new ArrowButtonListener(); } protected ModelListener createModelListener(){ return new ModelListener(); } protected ScrollListener createScrollListener(){ return new ScrollListener(); } protected PropertyChangeListener createPropertyChangeListener() { return getHandler(); } private void updateThumbState(int x, int y) { Rectangle rect = getThumbBounds(); setThumbRollover(rect.contains(x, y)); } /** {@collect.stats} * Sets whether or not the mouse is currently over the thumb. * * @param active True indicates the thumb is currently active. * @since 1.5 */ protected void setThumbRollover(boolean active) { if (thumbActive != active) { thumbActive = active; scrollbar.repaint(getThumbBounds()); } } /** {@collect.stats} * Returns true if the mouse is currently over the thumb. * * @return true if the thumb is currently active * @since 1.5 */ public boolean isThumbRollover() { return thumbActive; } public void paint(Graphics g, JComponent c) { paintTrack(g, c, getTrackBounds()); Rectangle thumbBounds = getThumbBounds(); if (thumbBounds.intersects(g.getClipBounds())) { paintThumb(g, c, thumbBounds); } } /** {@collect.stats} * A vertical scrollbar's preferred width is the maximum of * preferred widths of the (non <code>null</code>) * increment/decrement buttons, * and the minimum width of the thumb. The preferred height is the * sum of the preferred heights of the same parts. The basis for * the preferred size of a horizontal scrollbar is similar. * <p> * The <code>preferredSize</code> is only computed once, subsequent * calls to this method just return a cached size. * * @param c the <code>JScrollBar</code> that's delegating this method to us * @return the preferred size of a Basic JScrollBar * @see #getMaximumSize * @see #getMinimumSize */ public Dimension getPreferredSize(JComponent c) { return (scrollbar.getOrientation() == JScrollBar.VERTICAL) ? new Dimension(scrollBarWidth, 48) : new Dimension(48, scrollBarWidth); } /** {@collect.stats} * @param c The JScrollBar that's delegating this method to us. * @return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); * @see #getMinimumSize * @see #getPreferredSize */ public Dimension getMaximumSize(JComponent c) { return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } protected JButton createDecreaseButton(int orientation) { return new BasicArrowButton(orientation, UIManager.getColor("ScrollBar.thumb"), UIManager.getColor("ScrollBar.thumbShadow"), UIManager.getColor("ScrollBar.thumbDarkShadow"), UIManager.getColor("ScrollBar.thumbHighlight")); } protected JButton createIncreaseButton(int orientation) { return new BasicArrowButton(orientation, UIManager.getColor("ScrollBar.thumb"), UIManager.getColor("ScrollBar.thumbShadow"), UIManager.getColor("ScrollBar.thumbDarkShadow"), UIManager.getColor("ScrollBar.thumbHighlight")); } protected void paintDecreaseHighlight(Graphics g) { Insets insets = scrollbar.getInsets(); Rectangle thumbR = getThumbBounds(); g.setColor(trackHighlightColor); if (scrollbar.getOrientation() == JScrollBar.VERTICAL) { //paint the distance between the start of the track and top of the thumb int x = insets.left; int y = trackRect.y; int w = scrollbar.getWidth() - (insets.left + insets.right); int h = thumbR.y - y; g.fillRect(x, y, w, h); } else { //if left-to-right, fill the area between the start of the track and //the left edge of the thumb. If right-to-left, fill the area between //the end of the thumb and end of the track. int x, w; if (scrollbar.getComponentOrientation().isLeftToRight()) { x = trackRect.x; w = thumbR.x - x; } else { x = thumbR.x + thumbR.width; w = trackRect.x + trackRect.width - x; } int y = insets.top; int h = scrollbar.getHeight() - (insets.top + insets.bottom); g.fillRect(x, y, w, h); } } protected void paintIncreaseHighlight(Graphics g) { Insets insets = scrollbar.getInsets(); Rectangle thumbR = getThumbBounds(); g.setColor(trackHighlightColor); if (scrollbar.getOrientation() == JScrollBar.VERTICAL) { //fill the area between the bottom of the thumb and the end of the track. int x = insets.left; int y = thumbR.y + thumbR.height; int w = scrollbar.getWidth() - (insets.left + insets.right); int h = trackRect.y + trackRect.height - y; g.fillRect(x, y, w, h); } else { //if left-to-right, fill the area between the right of the thumb and the //end of the track. If right-to-left, then fill the area to the left of //the thumb and the start of the track. int x, w; if (scrollbar.getComponentOrientation().isLeftToRight()) { x = thumbR.x + thumbR.width; w = trackRect.x + trackRect.width - x; } else { x = trackRect.x; w = thumbR.x - x; } int y = insets.top; int h = scrollbar.getHeight() - (insets.top + insets.bottom); g.fillRect(x, y, w, h); } } protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) { g.setColor(trackColor); g.fillRect(trackBounds.x, trackBounds.y, trackBounds.width, trackBounds.height); if(trackHighlight == DECREASE_HIGHLIGHT) { paintDecreaseHighlight(g); } else if(trackHighlight == INCREASE_HIGHLIGHT) { paintIncreaseHighlight(g); } } protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) { if(thumbBounds.isEmpty() || !scrollbar.isEnabled()) { return; } int w = thumbBounds.width; int h = thumbBounds.height; g.translate(thumbBounds.x, thumbBounds.y); g.setColor(thumbDarkShadowColor); g.drawRect(0, 0, w-1, h-1); g.setColor(thumbColor); g.fillRect(0, 0, w-1, h-1); g.setColor(thumbHighlightColor); g.drawLine(1, 1, 1, h-2); g.drawLine(2, 1, w-3, 1); g.setColor(thumbLightShadowColor); g.drawLine(2, h-2, w-2, h-2); g.drawLine(w-2, 1, w-2, h-3); g.translate(-thumbBounds.x, -thumbBounds.y); } /** {@collect.stats} * Return the smallest acceptable size for the thumb. If the scrollbar * becomes so small that this size isn't available, the thumb will be * hidden. * <p> * <b>Warning </b>: the value returned by this method should not be * be modified, it's a shared static constant. * * @return The smallest acceptable size for the thumb. * @see #getMaximumThumbSize */ protected Dimension getMinimumThumbSize() { return minimumThumbSize; } /** {@collect.stats} * Return the largest acceptable size for the thumb. To create a fixed * size thumb one make this method and <code>getMinimumThumbSize</code> * return the same value. * <p> * <b>Warning </b>: the value returned by this method should not be * be modified, it's a shared static constant. * * @return The largest acceptable size for the thumb. * @see #getMinimumThumbSize */ protected Dimension getMaximumThumbSize() { return maximumThumbSize; } /* * LayoutManager Implementation */ public void addLayoutComponent(String name, Component child) {} public void removeLayoutComponent(Component child) {} public Dimension preferredLayoutSize(Container scrollbarContainer) { return getPreferredSize((JComponent)scrollbarContainer); } public Dimension minimumLayoutSize(Container scrollbarContainer) { return getMinimumSize((JComponent)scrollbarContainer); } private int getValue(JScrollBar sb) { return (useCachedValue) ? scrollBarValue : sb.getValue(); } protected void layoutVScrollbar(JScrollBar sb) { Dimension sbSize = sb.getSize(); Insets sbInsets = sb.getInsets(); /* * Width and left edge of the buttons and thumb. */ int itemW = sbSize.width - (sbInsets.left + sbInsets.right); int itemX = sbInsets.left; /* Nominal locations of the buttons, assuming their preferred * size will fit. */ boolean squareButtons = DefaultLookup.getBoolean( scrollbar, this, "ScrollBar.squareButtons", false); int decrButtonH = squareButtons ? itemW : decrButton.getPreferredSize().height; int decrButtonY = sbInsets.top; int incrButtonH = squareButtons ? itemW : incrButton.getPreferredSize().height; int incrButtonY = sbSize.height - (sbInsets.bottom + incrButtonH); /* The thumb must fit within the height left over after we * subtract the preferredSize of the buttons and the insets * and the gaps */ int sbInsetsH = sbInsets.top + sbInsets.bottom; int sbButtonsH = decrButtonH + incrButtonH; int gaps = decrGap + incrGap; float trackH = sbSize.height - (sbInsetsH + sbButtonsH) - gaps; /* Compute the height and origin of the thumb. The case * where the thumb is at the bottom edge is handled specially * to avoid numerical problems in computing thumbY. Enforce * the thumbs min/max dimensions. If the thumb doesn't * fit in the track (trackH) we'll hide it later. */ float min = sb.getMinimum(); float extent = sb.getVisibleAmount(); float range = sb.getMaximum() - min; float value = getValue(sb); int thumbH = (range <= 0) ? getMaximumThumbSize().height : (int)(trackH * (extent / range)); thumbH = Math.max(thumbH, getMinimumThumbSize().height); thumbH = Math.min(thumbH, getMaximumThumbSize().height); int thumbY = incrButtonY - incrGap - thumbH; if (value < (sb.getMaximum() - sb.getVisibleAmount())) { float thumbRange = trackH - thumbH; thumbY = (int)(0.5f + (thumbRange * ((value - min) / (range - extent)))); thumbY += decrButtonY + decrButtonH + decrGap; } /* If the buttons don't fit, allocate half of the available * space to each and move the lower one (incrButton) down. */ int sbAvailButtonH = (sbSize.height - sbInsetsH); if (sbAvailButtonH < sbButtonsH) { incrButtonH = decrButtonH = sbAvailButtonH / 2; incrButtonY = sbSize.height - (sbInsets.bottom + incrButtonH); } decrButton.setBounds(itemX, decrButtonY, itemW, decrButtonH); incrButton.setBounds(itemX, incrButtonY, itemW, incrButtonH); /* Update the trackRect field. */ int itrackY = decrButtonY + decrButtonH + decrGap; int itrackH = incrButtonY - incrGap - itrackY; trackRect.setBounds(itemX, itrackY, itemW, itrackH); /* If the thumb isn't going to fit, zero it's bounds. Otherwise * make sure it fits between the buttons. Note that setting the * thumbs bounds will cause a repaint. */ if(thumbH >= (int)trackH) { if (UIManager.getBoolean("ScrollBar.alwaysShowThumb")) { // This is used primarily for GTK L&F, which expands the // thumb to fit the track when it would otherwise be hidden. setThumbBounds(itemX, itrackY, itemW, itrackH); } else { // Other L&F's simply hide the thumb in this case. setThumbBounds(0, 0, 0, 0); } } else { if ((thumbY + thumbH) > incrButtonY - incrGap) { thumbY = incrButtonY - incrGap - thumbH; } if (thumbY < (decrButtonY + decrButtonH + decrGap)) { thumbY = decrButtonY + decrButtonH + decrGap + 1; } setThumbBounds(itemX, thumbY, itemW, thumbH); } } protected void layoutHScrollbar(JScrollBar sb) { Dimension sbSize = sb.getSize(); Insets sbInsets = sb.getInsets(); /* Height and top edge of the buttons and thumb. */ int itemH = sbSize.height - (sbInsets.top + sbInsets.bottom); int itemY = sbInsets.top; boolean ltr = sb.getComponentOrientation().isLeftToRight(); /* Nominal locations of the buttons, assuming their preferred * size will fit. */ boolean squareButtons = DefaultLookup.getBoolean( scrollbar, this, "ScrollBar.squareButtons", false); int leftButtonW = squareButtons ? itemH : decrButton.getPreferredSize().width; int rightButtonW = squareButtons ? itemH : incrButton.getPreferredSize().width; if (!ltr) { int temp = leftButtonW; leftButtonW = rightButtonW; rightButtonW = temp; } int leftButtonX = sbInsets.left; int rightButtonX = sbSize.width - (sbInsets.right + rightButtonW); int leftGap = ltr ? decrGap : incrGap; int rightGap = ltr ? incrGap : decrGap; /* The thumb must fit within the width left over after we * subtract the preferredSize of the buttons and the insets * and the gaps */ int sbInsetsW = sbInsets.left + sbInsets.right; int sbButtonsW = leftButtonW + rightButtonW; float trackW = sbSize.width - (sbInsetsW + sbButtonsW) - (leftGap + rightGap); /* Compute the width and origin of the thumb. Enforce * the thumbs min/max dimensions. The case where the thumb * is at the right edge is handled specially to avoid numerical * problems in computing thumbX. If the thumb doesn't * fit in the track (trackH) we'll hide it later. */ float min = sb.getMinimum(); float max = sb.getMaximum(); float extent = sb.getVisibleAmount(); float range = max - min; float value = getValue(sb); int thumbW = (range <= 0) ? getMaximumThumbSize().width : (int)(trackW * (extent / range)); thumbW = Math.max(thumbW, getMinimumThumbSize().width); thumbW = Math.min(thumbW, getMaximumThumbSize().width); int thumbX = ltr ? rightButtonX - rightGap - thumbW : leftButtonX + leftButtonW + leftGap; if (value < (max - sb.getVisibleAmount())) { float thumbRange = trackW - thumbW; if( ltr ) { thumbX = (int)(0.5f + (thumbRange * ((value - min) / (range - extent)))); } else { thumbX = (int)(0.5f + (thumbRange * ((max - extent - value) / (range - extent)))); } thumbX += leftButtonX + leftButtonW + leftGap; } /* If the buttons don't fit, allocate half of the available * space to each and move the right one over. */ int sbAvailButtonW = (sbSize.width - sbInsetsW); if (sbAvailButtonW < sbButtonsW) { rightButtonW = leftButtonW = sbAvailButtonW / 2; rightButtonX = sbSize.width - (sbInsets.right + rightButtonW + rightGap); } (ltr ? decrButton : incrButton).setBounds(leftButtonX, itemY, leftButtonW, itemH); (ltr ? incrButton : decrButton).setBounds(rightButtonX, itemY, rightButtonW, itemH); /* Update the trackRect field. */ int itrackX = leftButtonX + leftButtonW + leftGap; int itrackW = rightButtonX - rightGap - itrackX; trackRect.setBounds(itrackX, itemY, itrackW, itemH); /* Make sure the thumb fits between the buttons. Note * that setting the thumbs bounds causes a repaint. */ if (thumbW >= (int)trackW) { if (UIManager.getBoolean("ScrollBar.alwaysShowThumb")) { // This is used primarily for GTK L&F, which expands the // thumb to fit the track when it would otherwise be hidden. setThumbBounds(itrackX, itemY, itrackW, itemH); } else { // Other L&F's simply hide the thumb in this case. setThumbBounds(0, 0, 0, 0); } } else { if (thumbX + thumbW > rightButtonX - rightGap) { thumbX = rightButtonX - rightGap - thumbW; } if (thumbX < leftButtonX + leftButtonW + leftGap) { thumbX = leftButtonX + leftButtonW + leftGap + 1; } setThumbBounds(thumbX, itemY, thumbW, itemH); } } public void layoutContainer(Container scrollbarContainer) { /* If the user is dragging the value, we'll assume that the * scrollbars layout is OK modulo the thumb which is being * handled by the dragging code. */ if (isDragging) { return; } JScrollBar scrollbar = (JScrollBar)scrollbarContainer; switch (scrollbar.getOrientation()) { case JScrollBar.VERTICAL: layoutVScrollbar(scrollbar); break; case JScrollBar.HORIZONTAL: layoutHScrollbar(scrollbar); break; } } /** {@collect.stats} * Set the bounds of the thumb and force a repaint that includes * the old thumbBounds and the new one. * * @see #getThumbBounds */ protected void setThumbBounds(int x, int y, int width, int height) { /* If the thumbs bounds haven't changed, we're done. */ if ((thumbRect.x == x) && (thumbRect.y == y) && (thumbRect.width == width) && (thumbRect.height == height)) { return; } /* Update thumbRect, and repaint the union of x,y,w,h and * the old thumbRect. */ int minX = Math.min(x, thumbRect.x); int minY = Math.min(y, thumbRect.y); int maxX = Math.max(x + width, thumbRect.x + thumbRect.width); int maxY = Math.max(y + height, thumbRect.y + thumbRect.height); thumbRect.setBounds(x, y, width, height); scrollbar.repaint(minX, minY, maxX - minX, maxY - minY); // Once there is API to determine the mouse location this will need // to be changed. setThumbRollover(false); } /** {@collect.stats} * Return the current size/location of the thumb. * <p> * <b>Warning </b>: the value returned by this method should not be * be modified, it's a reference to the actual rectangle, not a copy. * * @return The current size/location of the thumb. * @see #setThumbBounds */ protected Rectangle getThumbBounds() { return thumbRect; } /** {@collect.stats} * Returns the current bounds of the track, i.e. the space in between * the increment and decrement buttons, less the insets. The value * returned by this method is updated each time the scrollbar is * laid out (validated). * <p> * <b>Warning </b>: the value returned by this method should not be * be modified, it's a reference to the actual rectangle, not a copy. * * @return the current bounds of the scrollbar track * @see #layoutContainer */ protected Rectangle getTrackBounds() { return trackRect; } /* * Method for scrolling by a block increment. * Added for mouse wheel scrolling support, RFE 4202656. */ static void scrollByBlock(JScrollBar scrollbar, int direction) { // This method is called from BasicScrollPaneUI to implement wheel // scrolling, and also from scrollByBlock(). int oldValue = scrollbar.getValue(); int blockIncrement = scrollbar.getBlockIncrement(direction); int delta = blockIncrement * ((direction > 0) ? +1 : -1); int newValue = oldValue + delta; // Check for overflow. if (delta > 0 && newValue < oldValue) { newValue = scrollbar.getMaximum(); } else if (delta < 0 && newValue > oldValue) { newValue = scrollbar.getMinimum(); } scrollbar.setValue(newValue); } protected void scrollByBlock(int direction) { scrollByBlock(scrollbar, direction); trackHighlight = direction > 0 ? INCREASE_HIGHLIGHT : DECREASE_HIGHLIGHT; Rectangle dirtyRect = getTrackBounds(); scrollbar.repaint(dirtyRect.x, dirtyRect.y, dirtyRect.width, dirtyRect.height); } /* * Method for scrolling by a unit increment. * Added for mouse wheel scrolling support, RFE 4202656. * * If limitByBlock is set to true, the scrollbar will scroll at least 1 * unit increment, but will not scroll farther than the block increment. * See BasicScrollPaneUI.Handler.mouseWheelMoved(). */ static void scrollByUnits(JScrollBar scrollbar, int direction, int units, boolean limitToBlock) { // This method is called from BasicScrollPaneUI to implement wheel // scrolling, as well as from scrollByUnit(). int delta; int limit = -1; if (limitToBlock) { if (direction < 0) { limit = scrollbar.getValue() - scrollbar.getBlockIncrement(direction); } else { limit = scrollbar.getValue() + scrollbar.getBlockIncrement(direction); } } for (int i=0; i<units; i++) { if (direction > 0) { delta = scrollbar.getUnitIncrement(direction); } else { delta = -scrollbar.getUnitIncrement(direction); } int oldValue = scrollbar.getValue(); int newValue = oldValue + delta; // Check for overflow. if (delta > 0 && newValue < oldValue) { newValue = scrollbar.getMaximum(); } else if (delta < 0 && newValue > oldValue) { newValue = scrollbar.getMinimum(); } if (oldValue == newValue) { break; } if (limitToBlock && i > 0) { assert limit != -1; if ((direction < 0 && newValue < limit) || (direction > 0 && newValue > limit)) { break; } } scrollbar.setValue(newValue); } } protected void scrollByUnit(int direction) { scrollByUnits(scrollbar, direction, 1, false); } /** {@collect.stats} * Indicates whether the user can absolutely position the thumb with * a mouse gesture (usually the middle mouse button). * * @return true if a mouse gesture can absolutely position the thumb * @since 1.5 */ public boolean getSupportsAbsolutePositioning() { return supportsAbsolutePositioning; } /** {@collect.stats} * A listener to listen for model changes. * */ protected class ModelListener implements ChangeListener { public void stateChanged(ChangeEvent e) { if (!useCachedValue) { scrollBarValue = scrollbar.getValue(); } layoutContainer(scrollbar); useCachedValue = false; } } /** {@collect.stats} * Track mouse drags. */ protected class TrackListener extends MouseAdapter implements MouseMotionListener { protected transient int offset; protected transient int currentMouseX, currentMouseY; private transient int direction = +1; public void mouseReleased(MouseEvent e) { if (isDragging) { updateThumbState(e.getX(), e.getY()); } if (SwingUtilities.isRightMouseButton(e) || (!getSupportsAbsolutePositioning() && SwingUtilities.isMiddleMouseButton(e))) return; if(!scrollbar.isEnabled()) return; Rectangle r = getTrackBounds(); scrollbar.repaint(r.x, r.y, r.width, r.height); trackHighlight = NO_HIGHLIGHT; isDragging = false; offset = 0; scrollTimer.stop(); useCachedValue = true; scrollbar.setValueIsAdjusting(false); } /** {@collect.stats} * If the mouse is pressed above the "thumb" component * then reduce the scrollbars value by one page ("page up"), * otherwise increase it by one page. If there is no * thumb then page up if the mouse is in the upper half * of the track. */ public void mousePressed(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e) || (!getSupportsAbsolutePositioning() && SwingUtilities.isMiddleMouseButton(e))) return; if(!scrollbar.isEnabled()) return; if (!scrollbar.hasFocus() && scrollbar.isRequestFocusEnabled()) { scrollbar.requestFocus(); } useCachedValue = true; scrollbar.setValueIsAdjusting(true); currentMouseX = e.getX(); currentMouseY = e.getY(); // Clicked in the Thumb area? if(getThumbBounds().contains(currentMouseX, currentMouseY)) { switch (scrollbar.getOrientation()) { case JScrollBar.VERTICAL: offset = currentMouseY - getThumbBounds().y; break; case JScrollBar.HORIZONTAL: offset = currentMouseX - getThumbBounds().x; break; } isDragging = true; return; } else if (getSupportsAbsolutePositioning() && SwingUtilities.isMiddleMouseButton(e)) { switch (scrollbar.getOrientation()) { case JScrollBar.VERTICAL: offset = getThumbBounds().height / 2; break; case JScrollBar.HORIZONTAL: offset = getThumbBounds().width / 2; break; } isDragging = true; setValueFrom(e); return; } isDragging = false; Dimension sbSize = scrollbar.getSize(); direction = +1; switch (scrollbar.getOrientation()) { case JScrollBar.VERTICAL: if (getThumbBounds().isEmpty()) { int scrollbarCenter = sbSize.height / 2; direction = (currentMouseY < scrollbarCenter) ? -1 : +1; } else { int thumbY = getThumbBounds().y; direction = (currentMouseY < thumbY) ? -1 : +1; } break; case JScrollBar.HORIZONTAL: if (getThumbBounds().isEmpty()) { int scrollbarCenter = sbSize.width / 2; direction = (currentMouseX < scrollbarCenter) ? -1 : +1; } else { int thumbX = getThumbBounds().x; direction = (currentMouseX < thumbX) ? -1 : +1; } if (!scrollbar.getComponentOrientation().isLeftToRight()) { direction = -direction; } break; } scrollByBlock(direction); scrollTimer.stop(); scrollListener.setDirection(direction); scrollListener.setScrollByBlock(true); startScrollTimerIfNecessary(); } /** {@collect.stats} * Set the models value to the position of the thumb's top of Vertical * scrollbar, or the left/right of Horizontal scrollbar in * left-to-right/right-to-left scrollbar relative to the origin of the * track. */ public void mouseDragged(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e) || (!getSupportsAbsolutePositioning() && SwingUtilities.isMiddleMouseButton(e))) return; if(!scrollbar.isEnabled() || getThumbBounds().isEmpty()) { return; } if (isDragging) { setValueFrom(e); } else { currentMouseX = e.getX(); currentMouseY = e.getY(); updateThumbState(currentMouseX, currentMouseY); startScrollTimerIfNecessary(); } } private void setValueFrom(MouseEvent e) { boolean active = isThumbRollover(); BoundedRangeModel model = scrollbar.getModel(); Rectangle thumbR = getThumbBounds(); float trackLength; int thumbMin, thumbMax, thumbPos; if (scrollbar.getOrientation() == JScrollBar.VERTICAL) { thumbMin = trackRect.y; thumbMax = trackRect.y + trackRect.height - thumbR.height; thumbPos = Math.min(thumbMax, Math.max(thumbMin, (e.getY() - offset))); setThumbBounds(thumbR.x, thumbPos, thumbR.width, thumbR.height); trackLength = getTrackBounds().height; } else { thumbMin = trackRect.x; thumbMax = trackRect.x + trackRect.width - thumbR.width; thumbPos = Math.min(thumbMax, Math.max(thumbMin, (e.getX() - offset))); setThumbBounds(thumbPos, thumbR.y, thumbR.width, thumbR.height); trackLength = getTrackBounds().width; } /* Set the scrollbars value. If the thumb has reached the end of * the scrollbar, then just set the value to its maximum. Otherwise * compute the value as accurately as possible. */ if (thumbPos == thumbMax) { if (scrollbar.getOrientation() == JScrollBar.VERTICAL || scrollbar.getComponentOrientation().isLeftToRight()) { scrollbar.setValue(model.getMaximum() - model.getExtent()); } else { scrollbar.setValue(model.getMinimum()); } } else { float valueMax = model.getMaximum() - model.getExtent(); float valueRange = valueMax - model.getMinimum(); float thumbValue = thumbPos - thumbMin; float thumbRange = thumbMax - thumbMin; int value; if (scrollbar.getOrientation() == JScrollBar.VERTICAL || scrollbar.getComponentOrientation().isLeftToRight()) { value = (int)(0.5 + ((thumbValue / thumbRange) * valueRange)); } else { value = (int)(0.5 + (((thumbMax - thumbPos) / thumbRange) * valueRange)); } useCachedValue = true; scrollBarValue = value + model.getMinimum(); scrollbar.setValue(adjustValueIfNecessary(scrollBarValue)); } setThumbRollover(active); } private int adjustValueIfNecessary(int value) { if (scrollbar.getParent() instanceof JScrollPane) { JScrollPane scrollpane = (JScrollPane)scrollbar.getParent(); JViewport viewport = scrollpane.getViewport(); Component view = viewport.getView(); if (view instanceof JList) { JList list = (JList)view; if (DefaultLookup.getBoolean(list, list.getUI(), "List.lockToPositionOnScroll", false)) { int adjustedValue = value; int mode = list.getLayoutOrientation(); int orientation = scrollbar.getOrientation(); if (orientation == JScrollBar.VERTICAL && mode == JList.VERTICAL) { int index = list.locationToIndex(new Point(0, value)); Rectangle rect = list.getCellBounds(index, index); if (rect != null) { adjustedValue = rect.y; } } if (orientation == JScrollBar.HORIZONTAL && (mode == JList.VERTICAL_WRAP || mode == JList.HORIZONTAL_WRAP)) { if (scrollpane.getComponentOrientation().isLeftToRight()) { int index = list.locationToIndex(new Point(value, 0)); Rectangle rect = list.getCellBounds(index, index); if (rect != null) { adjustedValue = rect.x; } } else { Point loc = new Point(value, 0); int extent = viewport.getExtentSize().width; loc.x += extent - 1; int index = list.locationToIndex(loc); Rectangle rect = list.getCellBounds(index, index); if (rect != null) { adjustedValue = rect.x + rect.width - extent; } } } value = adjustedValue; } } } return value; } private void startScrollTimerIfNecessary() { if (scrollTimer.isRunning()) { return; } Rectangle tb = getThumbBounds(); switch (scrollbar.getOrientation()) { case JScrollBar.VERTICAL: if (direction > 0) { if (tb.y + tb.height < trackListener.currentMouseY) { scrollTimer.start(); } } else if (tb.y > trackListener.currentMouseY) { scrollTimer.start(); } break; case JScrollBar.HORIZONTAL: if ((direction > 0 && isMouseAfterThumb()) || (direction < 0 && isMouseBeforeThumb())) { scrollTimer.start(); } break; } } public void mouseMoved(MouseEvent e) { if (!isDragging) { updateThumbState(e.getX(), e.getY()); } } /** {@collect.stats} * Invoked when the mouse exits the scrollbar. * * @param e MouseEvent further describing the event * @since 1.5 */ public void mouseExited(MouseEvent e) { if (!isDragging) { setThumbRollover(false); } } } /** {@collect.stats} * Listener for cursor keys. */ protected class ArrowButtonListener extends MouseAdapter { // Because we are handling both mousePressed and Actions // we need to make sure we don't fire under both conditions. // (keyfocus on scrollbars causes action without mousePress boolean handledEvent; public void mousePressed(MouseEvent e) { if(!scrollbar.isEnabled()) { return; } // not an unmodified left mouse button //if(e.getModifiers() != InputEvent.BUTTON1_MASK) {return; } if( ! SwingUtilities.isLeftMouseButton(e)) { return; } int direction = (e.getSource() == incrButton) ? 1 : -1; scrollByUnit(direction); scrollTimer.stop(); scrollListener.setDirection(direction); scrollListener.setScrollByBlock(false); scrollTimer.start(); handledEvent = true; if (!scrollbar.hasFocus() && scrollbar.isRequestFocusEnabled()) { scrollbar.requestFocus(); } } public void mouseReleased(MouseEvent e) { scrollTimer.stop(); handledEvent = false; scrollbar.setValueIsAdjusting(false); } } /** {@collect.stats} * Listener for scrolling events initiated in the * <code>ScrollPane</code>. */ protected class ScrollListener implements ActionListener { int direction = +1; boolean useBlockIncrement; public ScrollListener() { direction = +1; useBlockIncrement = false; } public ScrollListener(int dir, boolean block) { direction = dir; useBlockIncrement = block; } public void setDirection(int direction) { this.direction = direction; } public void setScrollByBlock(boolean block) { this.useBlockIncrement = block; } public void actionPerformed(ActionEvent e) { if(useBlockIncrement) { scrollByBlock(direction); // Stop scrolling if the thumb catches up with the mouse if(scrollbar.getOrientation() == JScrollBar.VERTICAL) { if(direction > 0) { if(getThumbBounds().y + getThumbBounds().height >= trackListener.currentMouseY) ((Timer)e.getSource()).stop(); } else if(getThumbBounds().y <= trackListener.currentMouseY) { ((Timer)e.getSource()).stop(); } } else { if ((direction > 0 && !isMouseAfterThumb()) || (direction < 0 && !isMouseBeforeThumb())) { ((Timer)e.getSource()).stop(); } } } else { scrollByUnit(direction); } if(direction > 0 && scrollbar.getValue()+scrollbar.getVisibleAmount() >= scrollbar.getMaximum()) ((Timer)e.getSource()).stop(); else if(direction < 0 && scrollbar.getValue() <= scrollbar.getMinimum()) ((Timer)e.getSource()).stop(); } } private boolean isMouseLeftOfThumb() { return trackListener.currentMouseX < getThumbBounds().x; } private boolean isMouseRightOfThumb() { Rectangle tb = getThumbBounds(); return trackListener.currentMouseX > tb.x + tb.width; } private boolean isMouseBeforeThumb() { return scrollbar.getComponentOrientation().isLeftToRight() ? isMouseLeftOfThumb() : isMouseRightOfThumb(); } private boolean isMouseAfterThumb() { return scrollbar.getComponentOrientation().isLeftToRight() ? isMouseRightOfThumb() : isMouseLeftOfThumb(); } private void updateButtonDirections() { int orient = scrollbar.getOrientation(); if (scrollbar.getComponentOrientation().isLeftToRight()) { if (incrButton instanceof BasicArrowButton) { ((BasicArrowButton)incrButton).setDirection( orient == HORIZONTAL? EAST : SOUTH); } if (decrButton instanceof BasicArrowButton) { ((BasicArrowButton)decrButton).setDirection( orient == HORIZONTAL? WEST : NORTH); } } else { if (incrButton instanceof BasicArrowButton) { ((BasicArrowButton)incrButton).setDirection( orient == HORIZONTAL? WEST : SOUTH); } if (decrButton instanceof BasicArrowButton) { ((BasicArrowButton)decrButton).setDirection( orient == HORIZONTAL ? EAST : NORTH); } } } public class PropertyChangeHandler implements PropertyChangeListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void propertyChange(PropertyChangeEvent e) { getHandler().propertyChange(e); } } /** {@collect.stats} * Used for scrolling the scrollbar. */ private static class Actions extends UIAction { private static final String POSITIVE_UNIT_INCREMENT = "positiveUnitIncrement"; private static final String POSITIVE_BLOCK_INCREMENT = "positiveBlockIncrement"; private static final String NEGATIVE_UNIT_INCREMENT = "negativeUnitIncrement"; private static final String NEGATIVE_BLOCK_INCREMENT = "negativeBlockIncrement"; private static final String MIN_SCROLL = "minScroll"; private static final String MAX_SCROLL = "maxScroll"; Actions(String name) { super(name); } public void actionPerformed(ActionEvent e) { JScrollBar scrollBar = (JScrollBar)e.getSource(); String key = getName(); if (key == POSITIVE_UNIT_INCREMENT) { scroll(scrollBar, POSITIVE_SCROLL, false); } else if (key == POSITIVE_BLOCK_INCREMENT) { scroll(scrollBar, POSITIVE_SCROLL, true); } else if (key == NEGATIVE_UNIT_INCREMENT) { scroll(scrollBar, NEGATIVE_SCROLL, false); } else if (key == NEGATIVE_BLOCK_INCREMENT) { scroll(scrollBar, NEGATIVE_SCROLL, true); } else if (key == MIN_SCROLL) { scroll(scrollBar, BasicScrollBarUI.MIN_SCROLL, true); } else if (key == MAX_SCROLL) { scroll(scrollBar, BasicScrollBarUI.MAX_SCROLL, true); } } private void scroll(JScrollBar scrollBar, int dir, boolean block) { if (dir == NEGATIVE_SCROLL || dir == POSITIVE_SCROLL) { int amount; // Don't use the BasicScrollBarUI.scrollByXXX methods as we // don't want to use an invokeLater to reset the trackHighlight // via an invokeLater if (block) { if (dir == NEGATIVE_SCROLL) { amount = -1 * scrollBar.getBlockIncrement(-1); } else { amount = scrollBar.getBlockIncrement(1); } } else { if (dir == NEGATIVE_SCROLL) { amount = -1 * scrollBar.getUnitIncrement(-1); } else { amount = scrollBar.getUnitIncrement(1); } } scrollBar.setValue(scrollBar.getValue() + amount); } else if (dir == BasicScrollBarUI.MIN_SCROLL) { scrollBar.setValue(scrollBar.getMinimum()); } else if (dir == BasicScrollBarUI.MAX_SCROLL) { scrollBar.setValue(scrollBar.getMaximum()); } } } // // EventHandler // private class Handler implements FocusListener, PropertyChangeListener { // // FocusListener // public void focusGained(FocusEvent e) { scrollbar.repaint(); } public void focusLost(FocusEvent e) { scrollbar.repaint(); } // // PropertyChangeListener // public void propertyChange(PropertyChangeEvent e) { String propertyName = e.getPropertyName(); if ("model" == propertyName) { BoundedRangeModel oldModel = (BoundedRangeModel)e.getOldValue(); BoundedRangeModel newModel = (BoundedRangeModel)e.getNewValue(); oldModel.removeChangeListener(modelListener); newModel.addChangeListener(modelListener); scrollbar.repaint(); scrollbar.revalidate(); } else if ("orientation" == propertyName) { updateButtonDirections(); } else if ("componentOrientation" == propertyName) { updateButtonDirections(); InputMap inputMap = getInputMap(JComponent.WHEN_FOCUSED); SwingUtilities.replaceUIInputMap(scrollbar, JComponent.WHEN_FOCUSED, inputMap); } } } }
Java
/* * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.Font; import java.awt.Color; import java.awt.SystemColor; import java.awt.event.*; import java.awt.Insets; import java.awt.Component; import java.awt.Container; import java.awt.FocusTraversalPolicy; import java.awt.AWTEvent; import java.awt.Toolkit; import java.awt.Point; import java.net.URL; import java.io.*; import java.awt.Dimension; import java.awt.KeyboardFocusManager; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.*; import java.lang.reflect.*; import javax.sound.sampled.*; import sun.awt.AppContext; import sun.swing.SwingLazyValue; import sun.swing.SwingUtilities2; import javax.swing.LookAndFeel; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.ImageIcon; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.KeyStroke; import javax.swing.JTextField; import javax.swing.DefaultListCellRenderer; import javax.swing.FocusManager; import javax.swing.LayoutFocusTraversalPolicy; import javax.swing.SwingUtilities; import javax.swing.MenuSelectionManager; import javax.swing.MenuElement; import javax.swing.border.*; import javax.swing.plaf.*; import javax.swing.text.JTextComponent; import javax.swing.text.DefaultEditorKit; import javax.swing.JInternalFrame; import java.beans.PropertyVetoException; import java.awt.Window; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; /** {@collect.stats} * A base class to use in creating a look and feel for Swing. * <p> * Each of the {@code ComponentUI}s provided by {@code * BasicLookAndFeel} derives its behavior from the defaults * table. Unless otherwise noted each of the {@code ComponentUI} * implementations in this package document the set of defaults they * use. Unless otherwise noted the defaults are installed at the time * {@code installUI} is invoked, and follow the recommendations * outlined in {@code LookAndFeel} for installing defaults. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author unattributed */ public abstract class BasicLookAndFeel extends LookAndFeel implements Serializable { /** {@collect.stats} * Whether or not the developer has created a JPopupMenu. */ static boolean needsEventHelper; /** {@collect.stats} * Lock used when manipulating clipPlaying. */ private transient Object audioLock = new Object(); /** {@collect.stats} * The Clip that is currently playing (set in AudioAction). */ private Clip clipPlaying; AWTEventHelper invocator = null; /* * Listen for our AppContext being disposed */ private PropertyChangeListener disposer = null; /** {@collect.stats} * Returns the look and feel defaults. The returned {@code UIDefaults} * is populated by invoking, in order, {@code initClassDefaults}, * {@code initSystemColorDefaults} and {@code initComponentDefaults}. * <p> * While this method is public, it should only be invoked by the * {@code UIManager} when the look and feel is set as the current * look and feel and after {@code initialize} has been invoked. * * @return the look and feel defaults * * @see #initClassDefaults * @see #initSystemColorDefaults * @see #initComponentDefaults */ public UIDefaults getDefaults() { UIDefaults table = new UIDefaults(610, 0.75f); initClassDefaults(table); initSystemColorDefaults(table); initComponentDefaults(table); return table; } /** {@collect.stats} * {@inheritDoc} */ public void initialize() { if (needsEventHelper) { installAWTEventListener(); } } void installAWTEventListener() { if (invocator == null) { invocator = new AWTEventHelper(); needsEventHelper = true; // Add a PropertyChangeListener to our AppContext so we're alerted // when the AppContext is disposed(), at which time this laf should // be uninitialize()d. disposer = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent prpChg) { uninitialize(); } }; AppContext.getAppContext().addPropertyChangeListener( AppContext.GUI_DISPOSED, disposer); } } /** {@collect.stats} * {@inheritDoc} */ public void uninitialize() { AppContext context = AppContext.getAppContext(); synchronized (BasicPopupMenuUI.MOUSE_GRABBER_KEY) { Object grabber = context.get(BasicPopupMenuUI.MOUSE_GRABBER_KEY); if (grabber != null) { ((BasicPopupMenuUI.MouseGrabber)grabber).uninstall(); } } synchronized (BasicPopupMenuUI.MENU_KEYBOARD_HELPER_KEY) { Object helper = context.get(BasicPopupMenuUI.MENU_KEYBOARD_HELPER_KEY); if (helper != null) { ((BasicPopupMenuUI.MenuKeyboardHelper)helper).uninstall(); } } if(invocator != null) { AccessController.doPrivileged(invocator); invocator = null; } if (disposer != null) { // Note that we're likely calling removePropertyChangeListener() // during the course of AppContext.firePropertyChange(). // However, EventListenerAggreggate has code to safely modify // the list under such circumstances. context.removePropertyChangeListener(AppContext.GUI_DISPOSED, disposer); disposer = null; } } /** {@collect.stats} * Populates {@code table} with mappings from {@code uiClassID} to the * fully qualified name of the ui class. The value for a * particular {@code uiClassID} is {@code * "javax.swing.plaf.basic.Basic + uiClassID"}. For example, the * value for the {@code uiClassID} {@code TreeUI} is {@code * "javax.swing.plaf.basic.BasicTreeUI"}. * * @param table the {@code UIDefaults} instance the entries are * added to * @throws NullPointerException if {@code table} is {@code null} * * @see javax.swing.LookAndFeel * @see #getDefaults */ protected void initClassDefaults(UIDefaults table) { final String basicPackageName = "javax.swing.plaf.basic."; Object[] uiDefaults = { "ButtonUI", basicPackageName + "BasicButtonUI", "CheckBoxUI", basicPackageName + "BasicCheckBoxUI", "ColorChooserUI", basicPackageName + "BasicColorChooserUI", "FormattedTextFieldUI", basicPackageName + "BasicFormattedTextFieldUI", "MenuBarUI", basicPackageName + "BasicMenuBarUI", "MenuUI", basicPackageName + "BasicMenuUI", "MenuItemUI", basicPackageName + "BasicMenuItemUI", "CheckBoxMenuItemUI", basicPackageName + "BasicCheckBoxMenuItemUI", "RadioButtonMenuItemUI", basicPackageName + "BasicRadioButtonMenuItemUI", "RadioButtonUI", basicPackageName + "BasicRadioButtonUI", "ToggleButtonUI", basicPackageName + "BasicToggleButtonUI", "PopupMenuUI", basicPackageName + "BasicPopupMenuUI", "ProgressBarUI", basicPackageName + "BasicProgressBarUI", "ScrollBarUI", basicPackageName + "BasicScrollBarUI", "ScrollPaneUI", basicPackageName + "BasicScrollPaneUI", "SplitPaneUI", basicPackageName + "BasicSplitPaneUI", "SliderUI", basicPackageName + "BasicSliderUI", "SeparatorUI", basicPackageName + "BasicSeparatorUI", "SpinnerUI", basicPackageName + "BasicSpinnerUI", "ToolBarSeparatorUI", basicPackageName + "BasicToolBarSeparatorUI", "PopupMenuSeparatorUI", basicPackageName + "BasicPopupMenuSeparatorUI", "TabbedPaneUI", basicPackageName + "BasicTabbedPaneUI", "TextAreaUI", basicPackageName + "BasicTextAreaUI", "TextFieldUI", basicPackageName + "BasicTextFieldUI", "PasswordFieldUI", basicPackageName + "BasicPasswordFieldUI", "TextPaneUI", basicPackageName + "BasicTextPaneUI", "EditorPaneUI", basicPackageName + "BasicEditorPaneUI", "TreeUI", basicPackageName + "BasicTreeUI", "LabelUI", basicPackageName + "BasicLabelUI", "ListUI", basicPackageName + "BasicListUI", "ToolBarUI", basicPackageName + "BasicToolBarUI", "ToolTipUI", basicPackageName + "BasicToolTipUI", "ComboBoxUI", basicPackageName + "BasicComboBoxUI", "TableUI", basicPackageName + "BasicTableUI", "TableHeaderUI", basicPackageName + "BasicTableHeaderUI", "InternalFrameUI", basicPackageName + "BasicInternalFrameUI", "DesktopPaneUI", basicPackageName + "BasicDesktopPaneUI", "DesktopIconUI", basicPackageName + "BasicDesktopIconUI", "OptionPaneUI", basicPackageName + "BasicOptionPaneUI", "PanelUI", basicPackageName + "BasicPanelUI", "ViewportUI", basicPackageName + "BasicViewportUI", "RootPaneUI", basicPackageName + "BasicRootPaneUI", }; table.putDefaults(uiDefaults); } /** {@collect.stats} * Populates {@code table} with system colors. This creates an * array of {@code name-color} pairs and invokes {@code * loadSystemColors}. * <p> * The name is a {@code String} that corresponds to the name of * one of the static {@code SystemColor} fields in the {@code * SystemColor} class. A name-color pair is created for every * such {@code SystemColor} field. * <p> * The {@code color} corresponds to a hex {@code String} as * understood by {@code Color.decode}. For example, one of the * {@code name-color} pairs is {@code * "desktop"-"#005C5C"}. This corresponds to the {@code * SystemColor} field {@code desktop}, with a color value of * {@code new Color(0x005C5C)}. * <p> * The following shows two of the {@code name-color} pairs: * <pre> * String[] nameColorPairs = new String[] { * "desktop", "#005C5C", * "activeCaption", "#000080" }; * loadSystemColors(table, nameColorPairs, isNativeLookAndFeel()); * </pre> * * As previously stated, this invokes {@code loadSystemColors} * with the supplied {@code table} and {@code name-color} pair * array. The last argument to {@code loadSystemColors} indicates * whether the value of the field in {@code SystemColor} should be * used. This method passes the value of {@code * isNativeLookAndFeel()} as the last argument to {@code loadSystemColors}. * * @param table the {@code UIDefaults} object the values are added to * @throws NullPointerException if {@code table} is {@code null} * * @see java.awt.SystemColor * @see #getDefaults * @see #loadSystemColors */ protected void initSystemColorDefaults(UIDefaults table) { String[] defaultSystemColors = { "desktop", "#005C5C", /* Color of the desktop background */ "activeCaption", "#000080", /* Color for captions (title bars) when they are active. */ "activeCaptionText", "#FFFFFF", /* Text color for text in captions (title bars). */ "activeCaptionBorder", "#C0C0C0", /* Border color for caption (title bar) window borders. */ "inactiveCaption", "#808080", /* Color for captions (title bars) when not active. */ "inactiveCaptionText", "#C0C0C0", /* Text color for text in inactive captions (title bars). */ "inactiveCaptionBorder", "#C0C0C0", /* Border color for inactive caption (title bar) window borders. */ "window", "#FFFFFF", /* Default color for the interior of windows */ "windowBorder", "#000000", /* ??? */ "windowText", "#000000", /* ??? */ "menu", "#C0C0C0", /* Background color for menus */ "menuText", "#000000", /* Text color for menus */ "text", "#C0C0C0", /* Text background color */ "textText", "#000000", /* Text foreground color */ "textHighlight", "#000080", /* Text background color when selected */ "textHighlightText", "#FFFFFF", /* Text color when selected */ "textInactiveText", "#808080", /* Text color when disabled */ "control", "#C0C0C0", /* Default color for controls (buttons, sliders, etc) */ "controlText", "#000000", /* Default color for text in controls */ "controlHighlight", "#C0C0C0", /* Specular highlight (opposite of the shadow) */ "controlLtHighlight", "#FFFFFF", /* Highlight color for controls */ "controlShadow", "#808080", /* Shadow color for controls */ "controlDkShadow", "#000000", /* Dark shadow color for controls */ "scrollbar", "#E0E0E0", /* Scrollbar background (usually the "track") */ "info", "#FFFFE1", /* ??? */ "infoText", "#000000" /* ??? */ }; loadSystemColors(table, defaultSystemColors, isNativeLookAndFeel()); } /** {@collect.stats} * Populates {@code table} with the {@code name-color} pairs in * {@code systemColors}. Refer to * {@link #initSystemColorDefaults(UIDefaults)} for details on * the format of {@code systemColors}. * <p> * An entry is added to {@code table} for each of the {@code name-color} * pairs in {@code systemColors}. The entry key is * the {@code name} of the {@code name-color} pair. * <p> * The value of the entry corresponds to the {@code color} of the * {@code name-color} pair. The value of the entry is calculated * in one of two ways. With either approach the value is always a * {@code ColorUIResource}. * <p> * If {@code useNative} is {@code false}, the {@code color} is * created by using {@code Color.decode} to convert the {@code * String} into a {@code Color}. If {@code decode} can not convert * the {@code String} into a {@code Color} ({@code * NumberFormatException} is thrown) then a {@code * ColorUIResource} of black is used. * <p> * If {@code useNative} is {@code true}, the {@code color} is the * value of the field in {@code SystemColor} with the same name as * the {@code name} of the {@code name-color} pair. If the field * is not valid, a {@code ColorUIResource} of black is used. * * @param table the {@code UIDefaults} object the values are added to * @param systemColors array of {@code name-color} pairs as described * in {@link #initSystemColorDefaults(UIDefaults)} * @param useNative whether the color is obtained from {@code SystemColor} * or {@code Color.decode} * @throws NullPointerException if {@code systemColors} is {@code null}; or * {@code systemColors} is not empty, and {@code table} is * {@code null}; or one of the * names of the {@code name-color} pairs is {@code null}; or * {@code useNative} is {@code false} and one of the * {@code colors} of the {@code name-color} pairs is {@code null} * @throws ArrayIndexOutOfBoundsException if {@code useNative} is * {@code false} and {@code systemColors.length} is odd * * @see #initSystemColorDefaults(javax.swing.UIDefaults) * @see java.awt.SystemColor * @see java.awt.Color#decode(String) */ protected void loadSystemColors(UIDefaults table, String[] systemColors, boolean useNative) { /* PENDING(hmuller) We don't load the system colors below because * they're not reliable. Hopefully we'll be able to do better in * a future version of AWT. */ if (useNative) { for(int i = 0; i < systemColors.length; i += 2) { Color color = Color.black; try { String name = systemColors[i]; color = (Color)(SystemColor.class.getField(name).get(null)); } catch (Exception e) { } table.put(systemColors[i], new ColorUIResource(color)); } } else { for(int i = 0; i < systemColors.length; i += 2) { Color color = Color.black; try { color = Color.decode(systemColors[i + 1]); } catch(NumberFormatException e) { e.printStackTrace(); } table.put(systemColors[i], new ColorUIResource(color)); } } } /** {@collect.stats} * Initialize the defaults table with the name of the ResourceBundle * used for getting localized defaults. Also initialize the default * locale used when no locale is passed into UIDefaults.get(). The * default locale should generally not be relied upon. It is here for * compatability with releases prior to 1.4. */ private void initResourceBundle(UIDefaults table) { table.setDefaultLocale( Locale.getDefault() ); table.addResourceBundle( "com.sun.swing.internal.plaf.basic.resources.basic" ); } /** {@collect.stats} * Populates {@code table} with the defaults for the basic look and * feel. * * @param table the {@code UIDefaults} to add the values to * @throws NullPointerException if {@code table} is {@code null} */ protected void initComponentDefaults(UIDefaults table) { initResourceBundle(table); // *** Shared Integers Integer fiveHundred = new Integer(500); // *** Shared Longs Long oneThousand = new Long(1000); // *** Shared Fonts Integer twelve = new Integer(12); Integer fontPlain = new Integer(Font.PLAIN); Integer fontBold = new Integer(Font.BOLD); Object dialogPlain12 = new SwingLazyValue( "javax.swing.plaf.FontUIResource", null, new Object[] {Font.DIALOG, fontPlain, twelve}); Object serifPlain12 = new SwingLazyValue( "javax.swing.plaf.FontUIResource", null, new Object[] {Font.SERIF, fontPlain, twelve}); Object sansSerifPlain12 = new SwingLazyValue( "javax.swing.plaf.FontUIResource", null, new Object[] {Font.SANS_SERIF, fontPlain, twelve}); Object monospacedPlain12 = new SwingLazyValue( "javax.swing.plaf.FontUIResource", null, new Object[] {Font.MONOSPACED, fontPlain, twelve}); Object dialogBold12 = new SwingLazyValue( "javax.swing.plaf.FontUIResource", null, new Object[] {Font.DIALOG, fontBold, twelve}); // *** Shared Colors ColorUIResource red = new ColorUIResource(Color.red); ColorUIResource black = new ColorUIResource(Color.black); ColorUIResource white = new ColorUIResource(Color.white); ColorUIResource yellow = new ColorUIResource(Color.yellow); ColorUIResource gray = new ColorUIResource(Color.gray); ColorUIResource lightGray = new ColorUIResource(Color.lightGray); ColorUIResource darkGray = new ColorUIResource(Color.darkGray); ColorUIResource scrollBarTrack = new ColorUIResource(224, 224, 224); Color control = table.getColor("control"); Color controlDkShadow = table.getColor("controlDkShadow"); Color controlHighlight = table.getColor("controlHighlight"); Color controlLtHighlight = table.getColor("controlLtHighlight"); Color controlShadow = table.getColor("controlShadow"); Color controlText = table.getColor("controlText"); Color menu = table.getColor("menu"); Color menuText = table.getColor("menuText"); Color textHighlight = table.getColor("textHighlight"); Color textHighlightText = table.getColor("textHighlightText"); Color textInactiveText = table.getColor("textInactiveText"); Color textText = table.getColor("textText"); Color window = table.getColor("window"); // *** Shared Insets InsetsUIResource zeroInsets = new InsetsUIResource(0,0,0,0); InsetsUIResource twoInsets = new InsetsUIResource(2,2,2,2); InsetsUIResource threeInsets = new InsetsUIResource(3,3,3,3); // *** Shared Borders Object marginBorder = new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders$MarginBorder"); Object etchedBorder = new SwingLazyValue( "javax.swing.plaf.BorderUIResource", "getEtchedBorderUIResource"); Object loweredBevelBorder = new SwingLazyValue( "javax.swing.plaf.BorderUIResource", "getLoweredBevelBorderUIResource"); Object popupMenuBorder = new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders", "getInternalFrameBorder"); Object blackLineBorder = new SwingLazyValue( "javax.swing.plaf.BorderUIResource", "getBlackLineBorderUIResource"); Object focusCellHighlightBorder = new SwingLazyValue( "javax.swing.plaf.BorderUIResource$LineBorderUIResource", null, new Object[] {yellow}); Object noFocusBorder = new BorderUIResource.EmptyBorderUIResource(1,1,1,1); Object tableHeaderBorder = new SwingLazyValue( "javax.swing.plaf.BorderUIResource$BevelBorderUIResource", null, new Object[] { new Integer(BevelBorder.RAISED), controlLtHighlight, control, controlDkShadow, controlShadow }); // *** Button value objects Object buttonBorder = new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders", "getButtonBorder"); Object buttonToggleBorder = new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders", "getToggleButtonBorder"); Object radioButtonBorder = new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders", "getRadioButtonBorder"); // *** FileChooser / FileView value objects Object newFolderIcon = SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/NewFolder.gif"); Object upFolderIcon = SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/UpFolder.gif"); Object homeFolderIcon = SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/HomeFolder.gif"); Object detailsViewIcon = SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/DetailsView.gif"); Object listViewIcon = SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/ListView.gif"); Object directoryIcon = SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/Directory.gif"); Object fileIcon = SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/File.gif"); Object computerIcon = SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/Computer.gif"); Object hardDriveIcon = SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/HardDrive.gif"); Object floppyDriveIcon = SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/FloppyDrive.gif"); // *** InternalFrame value objects Object internalFrameBorder = new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders", "getInternalFrameBorder"); // *** List value objects Object listCellRendererActiveValue = new UIDefaults.ActiveValue() { public Object createValue(UIDefaults table) { return new DefaultListCellRenderer.UIResource(); } }; // *** Menus value objects Object menuBarBorder = new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders", "getMenuBarBorder"); Object menuItemCheckIcon = new SwingLazyValue( "javax.swing.plaf.basic.BasicIconFactory", "getMenuItemCheckIcon"); Object menuItemArrowIcon = new SwingLazyValue( "javax.swing.plaf.basic.BasicIconFactory", "getMenuItemArrowIcon"); Object menuArrowIcon = new SwingLazyValue( "javax.swing.plaf.basic.BasicIconFactory", "getMenuArrowIcon"); Object checkBoxIcon = new SwingLazyValue( "javax.swing.plaf.basic.BasicIconFactory", "getCheckBoxIcon"); Object radioButtonIcon = new SwingLazyValue( "javax.swing.plaf.basic.BasicIconFactory", "getRadioButtonIcon"); Object checkBoxMenuItemIcon = new SwingLazyValue( "javax.swing.plaf.basic.BasicIconFactory", "getCheckBoxMenuItemIcon"); Object radioButtonMenuItemIcon = new SwingLazyValue( "javax.swing.plaf.basic.BasicIconFactory", "getRadioButtonMenuItemIcon"); Object menuItemAcceleratorDelimiter = new String("+"); // *** OptionPane value objects Object optionPaneMinimumSize = new DimensionUIResource(262, 90); Integer zero = new Integer(0); Object zeroBorder = new SwingLazyValue( "javax.swing.plaf.BorderUIResource$EmptyBorderUIResource", new Object[] {zero, zero, zero, zero}); Integer ten = new Integer(10); Object optionPaneBorder = new SwingLazyValue( "javax.swing.plaf.BorderUIResource$EmptyBorderUIResource", new Object[] {ten, ten, twelve, ten}); Object optionPaneButtonAreaBorder = new SwingLazyValue( "javax.swing.plaf.BorderUIResource$EmptyBorderUIResource", new Object[] {new Integer(6), zero, zero, zero}); // *** ProgessBar value objects Object progressBarBorder = new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders", "getProgressBarBorder"); // ** ScrollBar value objects Object minimumThumbSize = new DimensionUIResource(8,8); Object maximumThumbSize = new DimensionUIResource(4096,4096); // ** Slider value objects Object sliderFocusInsets = twoInsets; Object toolBarSeparatorSize = new DimensionUIResource( 10, 10 ); // *** SplitPane value objects Object splitPaneBorder = new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders", "getSplitPaneBorder"); Object splitPaneDividerBorder = new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders", "getSplitPaneDividerBorder"); // ** TabbedBane value objects Object tabbedPaneTabInsets = new InsetsUIResource(0, 4, 1, 4); Object tabbedPaneTabPadInsets = new InsetsUIResource(2, 2, 2, 1); Object tabbedPaneTabAreaInsets = new InsetsUIResource(3, 2, 0, 2); Object tabbedPaneContentBorderInsets = new InsetsUIResource(2, 2, 3, 3); // *** Text value objects Object textFieldBorder = new SwingLazyValue( "javax.swing.plaf.basic.BasicBorders", "getTextFieldBorder"); Object editorMargin = threeInsets; Object caretBlinkRate = fiveHundred; Integer four = new Integer(4); Object[] allAuditoryCues = new Object[] { "CheckBoxMenuItem.commandSound", "InternalFrame.closeSound", "InternalFrame.maximizeSound", "InternalFrame.minimizeSound", "InternalFrame.restoreDownSound", "InternalFrame.restoreUpSound", "MenuItem.commandSound", "OptionPane.errorSound", "OptionPane.informationSound", "OptionPane.questionSound", "OptionPane.warningSound", "PopupMenu.popupSound", "RadioButtonMenuItem.commandSound"}; Object[] noAuditoryCues = new Object[] {"mute"}; // *** Component Defaults Object[] defaults = { // *** Auditory Feedback "AuditoryCues.cueList", allAuditoryCues, "AuditoryCues.allAuditoryCues", allAuditoryCues, "AuditoryCues.noAuditoryCues", noAuditoryCues, // this key defines which of the various cues to render. // L&Fs that want auditory feedback NEED to override playList. "AuditoryCues.playList", null, // *** Buttons "Button.defaultButtonFollowsFocus", Boolean.TRUE, "Button.font", dialogPlain12, "Button.background", control, "Button.foreground", controlText, "Button.shadow", controlShadow, "Button.darkShadow", controlDkShadow, "Button.light", controlHighlight, "Button.highlight", controlLtHighlight, "Button.border", buttonBorder, "Button.margin", new InsetsUIResource(2, 14, 2, 14), "Button.textIconGap", four, "Button.textShiftOffset", zero, "Button.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "SPACE", "pressed", "released SPACE", "released", "ENTER", "pressed", "released ENTER", "released" }), "ToggleButton.font", dialogPlain12, "ToggleButton.background", control, "ToggleButton.foreground", controlText, "ToggleButton.shadow", controlShadow, "ToggleButton.darkShadow", controlDkShadow, "ToggleButton.light", controlHighlight, "ToggleButton.highlight", controlLtHighlight, "ToggleButton.border", buttonToggleBorder, "ToggleButton.margin", new InsetsUIResource(2, 14, 2, 14), "ToggleButton.textIconGap", four, "ToggleButton.textShiftOffset", zero, "ToggleButton.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "SPACE", "pressed", "released SPACE", "released" }), "RadioButton.font", dialogPlain12, "RadioButton.background", control, "RadioButton.foreground", controlText, "RadioButton.shadow", controlShadow, "RadioButton.darkShadow", controlDkShadow, "RadioButton.light", controlHighlight, "RadioButton.highlight", controlLtHighlight, "RadioButton.border", radioButtonBorder, "RadioButton.margin", twoInsets, "RadioButton.textIconGap", four, "RadioButton.textShiftOffset", zero, "RadioButton.icon", radioButtonIcon, "RadioButton.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "SPACE", "pressed", "released SPACE", "released", "RETURN", "pressed" }), "CheckBox.font", dialogPlain12, "CheckBox.background", control, "CheckBox.foreground", controlText, "CheckBox.border", radioButtonBorder, "CheckBox.margin", twoInsets, "CheckBox.textIconGap", four, "CheckBox.textShiftOffset", zero, "CheckBox.icon", checkBoxIcon, "CheckBox.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "SPACE", "pressed", "released SPACE", "released" }), "FileChooser.useSystemExtensionHiding", Boolean.FALSE, // *** ColorChooser "ColorChooser.font", dialogPlain12, "ColorChooser.background", control, "ColorChooser.foreground", controlText, "ColorChooser.swatchesSwatchSize", new Dimension(10, 10), "ColorChooser.swatchesRecentSwatchSize", new Dimension(10, 10), "ColorChooser.swatchesDefaultRecentColor", control, // *** ComboBox "ComboBox.font", sansSerifPlain12, "ComboBox.background", window, "ComboBox.foreground", textText, "ComboBox.buttonBackground", control, "ComboBox.buttonShadow", controlShadow, "ComboBox.buttonDarkShadow", controlDkShadow, "ComboBox.buttonHighlight", controlLtHighlight, "ComboBox.selectionBackground", textHighlight, "ComboBox.selectionForeground", textHighlightText, "ComboBox.disabledBackground", control, "ComboBox.disabledForeground", textInactiveText, "ComboBox.timeFactor", oneThousand, "ComboBox.isEnterSelectablePopup", Boolean.FALSE, "ComboBox.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ESCAPE", "hidePopup", "PAGE_UP", "pageUpPassThrough", "PAGE_DOWN", "pageDownPassThrough", "HOME", "homePassThrough", "END", "endPassThrough", "ENTER", "enterPressed" }), // *** FileChooser "FileChooser.newFolderIcon", newFolderIcon, "FileChooser.upFolderIcon", upFolderIcon, "FileChooser.homeFolderIcon", homeFolderIcon, "FileChooser.detailsViewIcon", detailsViewIcon, "FileChooser.listViewIcon", listViewIcon, "FileChooser.readOnly", Boolean.FALSE, "FileChooser.usesSingleFilePane", Boolean.FALSE, "FileChooser.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ESCAPE", "cancelSelection", "F5", "refresh", }), "FileView.directoryIcon", directoryIcon, "FileView.fileIcon", fileIcon, "FileView.computerIcon", computerIcon, "FileView.hardDriveIcon", hardDriveIcon, "FileView.floppyDriveIcon", floppyDriveIcon, // *** InternalFrame "InternalFrame.titleFont", dialogBold12, "InternalFrame.borderColor", control, "InternalFrame.borderShadow", controlShadow, "InternalFrame.borderDarkShadow", controlDkShadow, "InternalFrame.borderHighlight", controlLtHighlight, "InternalFrame.borderLight", controlHighlight, "InternalFrame.border", internalFrameBorder, "InternalFrame.icon", SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/JavaCup16.png"), /* Default frame icons are undefined for Basic. */ "InternalFrame.maximizeIcon", new SwingLazyValue( "javax.swing.plaf.basic.BasicIconFactory", "createEmptyFrameIcon"), "InternalFrame.minimizeIcon", new SwingLazyValue( "javax.swing.plaf.basic.BasicIconFactory", "createEmptyFrameIcon"), "InternalFrame.iconifyIcon", new SwingLazyValue( "javax.swing.plaf.basic.BasicIconFactory", "createEmptyFrameIcon"), "InternalFrame.closeIcon", new SwingLazyValue( "javax.swing.plaf.basic.BasicIconFactory", "createEmptyFrameIcon"), // InternalFrame Auditory Cue Mappings "InternalFrame.closeSound", null, "InternalFrame.maximizeSound", null, "InternalFrame.minimizeSound", null, "InternalFrame.restoreDownSound", null, "InternalFrame.restoreUpSound", null, "InternalFrame.activeTitleBackground", table.get("activeCaption"), "InternalFrame.activeTitleForeground", table.get("activeCaptionText"), "InternalFrame.inactiveTitleBackground", table.get("inactiveCaption"), "InternalFrame.inactiveTitleForeground", table.get("inactiveCaptionText"), "InternalFrame.windowBindings", new Object[] { "shift ESCAPE", "showSystemMenu", "ctrl SPACE", "showSystemMenu", "ESCAPE", "hideSystemMenu"}, "InternalFrameTitlePane.iconifyButtonOpacity", Boolean.TRUE, "InternalFrameTitlePane.maximizeButtonOpacity", Boolean.TRUE, "InternalFrameTitlePane.closeButtonOpacity", Boolean.TRUE, "DesktopIcon.border", internalFrameBorder, "Desktop.minOnScreenInsets", threeInsets, "Desktop.background", table.get("desktop"), "Desktop.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl F5", "restore", "ctrl F4", "close", "ctrl F7", "move", "ctrl F8", "resize", "RIGHT", "right", "KP_RIGHT", "right", "shift RIGHT", "shrinkRight", "shift KP_RIGHT", "shrinkRight", "LEFT", "left", "KP_LEFT", "left", "shift LEFT", "shrinkLeft", "shift KP_LEFT", "shrinkLeft", "UP", "up", "KP_UP", "up", "shift UP", "shrinkUp", "shift KP_UP", "shrinkUp", "DOWN", "down", "KP_DOWN", "down", "shift DOWN", "shrinkDown", "shift KP_DOWN", "shrinkDown", "ESCAPE", "escape", "ctrl F9", "minimize", "ctrl F10", "maximize", "ctrl F6", "selectNextFrame", "ctrl TAB", "selectNextFrame", "ctrl alt F6", "selectNextFrame", "shift ctrl alt F6", "selectPreviousFrame", "ctrl F12", "navigateNext", "shift ctrl F12", "navigatePrevious" }), // *** Label "Label.font", dialogPlain12, "Label.background", control, "Label.foreground", controlText, "Label.disabledForeground", white, "Label.disabledShadow", controlShadow, "Label.border", null, // *** List "List.font", dialogPlain12, "List.background", window, "List.foreground", textText, "List.selectionBackground", textHighlight, "List.selectionForeground", textHighlightText, "List.noFocusBorder", noFocusBorder, "List.focusCellHighlightBorder", focusCellHighlightBorder, "List.dropLineColor", controlShadow, "List.border", null, "List.cellRenderer", listCellRendererActiveValue, "List.timeFactor", oneThousand, "List.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl C", "copy", "ctrl V", "paste", "ctrl X", "cut", "COPY", "copy", "PASTE", "paste", "CUT", "cut", "control INSERT", "copy", "shift INSERT", "paste", "shift DELETE", "cut", "UP", "selectPreviousRow", "KP_UP", "selectPreviousRow", "shift UP", "selectPreviousRowExtendSelection", "shift KP_UP", "selectPreviousRowExtendSelection", "ctrl shift UP", "selectPreviousRowExtendSelection", "ctrl shift KP_UP", "selectPreviousRowExtendSelection", "ctrl UP", "selectPreviousRowChangeLead", "ctrl KP_UP", "selectPreviousRowChangeLead", "DOWN", "selectNextRow", "KP_DOWN", "selectNextRow", "shift DOWN", "selectNextRowExtendSelection", "shift KP_DOWN", "selectNextRowExtendSelection", "ctrl shift DOWN", "selectNextRowExtendSelection", "ctrl shift KP_DOWN", "selectNextRowExtendSelection", "ctrl DOWN", "selectNextRowChangeLead", "ctrl KP_DOWN", "selectNextRowChangeLead", "LEFT", "selectPreviousColumn", "KP_LEFT", "selectPreviousColumn", "shift LEFT", "selectPreviousColumnExtendSelection", "shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl shift LEFT", "selectPreviousColumnExtendSelection", "ctrl shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl LEFT", "selectPreviousColumnChangeLead", "ctrl KP_LEFT", "selectPreviousColumnChangeLead", "RIGHT", "selectNextColumn", "KP_RIGHT", "selectNextColumn", "shift RIGHT", "selectNextColumnExtendSelection", "shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl shift RIGHT", "selectNextColumnExtendSelection", "ctrl shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl RIGHT", "selectNextColumnChangeLead", "ctrl KP_RIGHT", "selectNextColumnChangeLead", "HOME", "selectFirstRow", "shift HOME", "selectFirstRowExtendSelection", "ctrl shift HOME", "selectFirstRowExtendSelection", "ctrl HOME", "selectFirstRowChangeLead", "END", "selectLastRow", "shift END", "selectLastRowExtendSelection", "ctrl shift END", "selectLastRowExtendSelection", "ctrl END", "selectLastRowChangeLead", "PAGE_UP", "scrollUp", "shift PAGE_UP", "scrollUpExtendSelection", "ctrl shift PAGE_UP", "scrollUpExtendSelection", "ctrl PAGE_UP", "scrollUpChangeLead", "PAGE_DOWN", "scrollDown", "shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl PAGE_DOWN", "scrollDownChangeLead", "ctrl A", "selectAll", "ctrl SLASH", "selectAll", "ctrl BACK_SLASH", "clearSelection", "SPACE", "addToSelection", "ctrl SPACE", "toggleAndAnchor", "shift SPACE", "extendTo", "ctrl shift SPACE", "moveSelectionTo" }), "List.focusInputMap.RightToLeft", new UIDefaults.LazyInputMap(new Object[] { "LEFT", "selectNextColumn", "KP_LEFT", "selectNextColumn", "shift LEFT", "selectNextColumnExtendSelection", "shift KP_LEFT", "selectNextColumnExtendSelection", "ctrl shift LEFT", "selectNextColumnExtendSelection", "ctrl shift KP_LEFT", "selectNextColumnExtendSelection", "ctrl LEFT", "selectNextColumnChangeLead", "ctrl KP_LEFT", "selectNextColumnChangeLead", "RIGHT", "selectPreviousColumn", "KP_RIGHT", "selectPreviousColumn", "shift RIGHT", "selectPreviousColumnExtendSelection", "shift KP_RIGHT", "selectPreviousColumnExtendSelection", "ctrl shift RIGHT", "selectPreviousColumnExtendSelection", "ctrl shift KP_RIGHT", "selectPreviousColumnExtendSelection", "ctrl RIGHT", "selectPreviousColumnChangeLead", "ctrl KP_RIGHT", "selectPreviousColumnChangeLead", }), // *** Menus "MenuBar.font", dialogPlain12, "MenuBar.background", menu, "MenuBar.foreground", menuText, "MenuBar.shadow", controlShadow, "MenuBar.highlight", controlLtHighlight, "MenuBar.border", menuBarBorder, "MenuBar.windowBindings", new Object[] { "F10", "takeFocus" }, "MenuItem.font", dialogPlain12, "MenuItem.acceleratorFont", dialogPlain12, "MenuItem.background", menu, "MenuItem.foreground", menuText, "MenuItem.selectionForeground", textHighlightText, "MenuItem.selectionBackground", textHighlight, "MenuItem.disabledForeground", null, "MenuItem.acceleratorForeground", menuText, "MenuItem.acceleratorSelectionForeground", textHighlightText, "MenuItem.acceleratorDelimiter", menuItemAcceleratorDelimiter, "MenuItem.border", marginBorder, "MenuItem.borderPainted", Boolean.FALSE, "MenuItem.margin", twoInsets, "MenuItem.checkIcon", menuItemCheckIcon, "MenuItem.arrowIcon", menuItemArrowIcon, "MenuItem.commandSound", null, "RadioButtonMenuItem.font", dialogPlain12, "RadioButtonMenuItem.acceleratorFont", dialogPlain12, "RadioButtonMenuItem.background", menu, "RadioButtonMenuItem.foreground", menuText, "RadioButtonMenuItem.selectionForeground", textHighlightText, "RadioButtonMenuItem.selectionBackground", textHighlight, "RadioButtonMenuItem.disabledForeground", null, "RadioButtonMenuItem.acceleratorForeground", menuText, "RadioButtonMenuItem.acceleratorSelectionForeground", textHighlightText, "RadioButtonMenuItem.border", marginBorder, "RadioButtonMenuItem.borderPainted", Boolean.FALSE, "RadioButtonMenuItem.margin", twoInsets, "RadioButtonMenuItem.checkIcon", radioButtonMenuItemIcon, "RadioButtonMenuItem.arrowIcon", menuItemArrowIcon, "RadioButtonMenuItem.commandSound", null, "CheckBoxMenuItem.font", dialogPlain12, "CheckBoxMenuItem.acceleratorFont", dialogPlain12, "CheckBoxMenuItem.background", menu, "CheckBoxMenuItem.foreground", menuText, "CheckBoxMenuItem.selectionForeground", textHighlightText, "CheckBoxMenuItem.selectionBackground", textHighlight, "CheckBoxMenuItem.disabledForeground", null, "CheckBoxMenuItem.acceleratorForeground", menuText, "CheckBoxMenuItem.acceleratorSelectionForeground", textHighlightText, "CheckBoxMenuItem.border", marginBorder, "CheckBoxMenuItem.borderPainted", Boolean.FALSE, "CheckBoxMenuItem.margin", twoInsets, "CheckBoxMenuItem.checkIcon", checkBoxMenuItemIcon, "CheckBoxMenuItem.arrowIcon", menuItemArrowIcon, "CheckBoxMenuItem.commandSound", null, "Menu.font", dialogPlain12, "Menu.acceleratorFont", dialogPlain12, "Menu.background", menu, "Menu.foreground", menuText, "Menu.selectionForeground", textHighlightText, "Menu.selectionBackground", textHighlight, "Menu.disabledForeground", null, "Menu.acceleratorForeground", menuText, "Menu.acceleratorSelectionForeground", textHighlightText, "Menu.border", marginBorder, "Menu.borderPainted", Boolean.FALSE, "Menu.margin", twoInsets, "Menu.checkIcon", menuItemCheckIcon, "Menu.arrowIcon", menuArrowIcon, "Menu.menuPopupOffsetX", new Integer(0), "Menu.menuPopupOffsetY", new Integer(0), "Menu.submenuPopupOffsetX", new Integer(0), "Menu.submenuPopupOffsetY", new Integer(0), "Menu.shortcutKeys", new int[] {KeyEvent.ALT_MASK}, "Menu.crossMenuMnemonic", Boolean.TRUE, // Menu.cancelMode affects the cancel menu action behaviour; // currently supports: // "hideLastSubmenu" (default) // hides the last open submenu, // and move selection one step back // "hideMenuTree" // resets selection and // hide the entire structure of open menu and its submenus "Menu.cancelMode", "hideLastSubmenu", // Menu.preserveTopLevelSelection affects // the cancel menu action behaviour // if set to true then top level menu selection // will be preserved when the last popup was cancelled; // the menu itself will be unselect with the next cancel action "Menu.preserveTopLevelSelection", Boolean.FALSE, // PopupMenu "PopupMenu.font", dialogPlain12, "PopupMenu.background", menu, "PopupMenu.foreground", menuText, "PopupMenu.border", popupMenuBorder, // Internal Frame Auditory Cue Mappings "PopupMenu.popupSound", null, // These window InputMap bindings are used when the Menu is // selected. "PopupMenu.selectedWindowInputMapBindings", new Object[] { "ESCAPE", "cancel", "DOWN", "selectNext", "KP_DOWN", "selectNext", "UP", "selectPrevious", "KP_UP", "selectPrevious", "LEFT", "selectParent", "KP_LEFT", "selectParent", "RIGHT", "selectChild", "KP_RIGHT", "selectChild", "ENTER", "return", "ctrl ENTER", "return", "SPACE", "return" }, "PopupMenu.selectedWindowInputMapBindings.RightToLeft", new Object[] { "LEFT", "selectChild", "KP_LEFT", "selectChild", "RIGHT", "selectParent", "KP_RIGHT", "selectParent", }, "PopupMenu.consumeEventOnClose", Boolean.FALSE, // *** OptionPane // You can additionaly define OptionPane.messageFont which will // dictate the fonts used for the message, and // OptionPane.buttonFont, which defines the font for the buttons. "OptionPane.font", dialogPlain12, "OptionPane.background", control, "OptionPane.foreground", controlText, "OptionPane.messageForeground", controlText, "OptionPane.border", optionPaneBorder, "OptionPane.messageAreaBorder", zeroBorder, "OptionPane.buttonAreaBorder", optionPaneButtonAreaBorder, "OptionPane.minimumSize", optionPaneMinimumSize, "OptionPane.errorIcon", SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/Error.gif"), "OptionPane.informationIcon", SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/Inform.gif"), "OptionPane.warningIcon", SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/Warn.gif"), "OptionPane.questionIcon", SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/Question.gif"), "OptionPane.windowBindings", new Object[] { "ESCAPE", "close" }, // OptionPane Auditory Cue Mappings "OptionPane.errorSound", null, "OptionPane.informationSound", null, // Info and Plain "OptionPane.questionSound", null, "OptionPane.warningSound", null, "OptionPane.buttonClickThreshhold", fiveHundred, // *** Panel "Panel.font", dialogPlain12, "Panel.background", control, "Panel.foreground", textText, // *** ProgressBar "ProgressBar.font", dialogPlain12, "ProgressBar.foreground", textHighlight, "ProgressBar.background", control, "ProgressBar.selectionForeground", control, "ProgressBar.selectionBackground", textHighlight, "ProgressBar.border", progressBarBorder, "ProgressBar.cellLength", new Integer(1), "ProgressBar.cellSpacing", zero, "ProgressBar.repaintInterval", new Integer(50), "ProgressBar.cycleTime", new Integer(3000), "ProgressBar.horizontalSize", new DimensionUIResource(146, 12), "ProgressBar.verticalSize", new DimensionUIResource(12, 146), // *** Separator "Separator.shadow", controlShadow, // DEPRECATED - DO NOT USE! "Separator.highlight", controlLtHighlight, // DEPRECATED - DO NOT USE! "Separator.background", controlLtHighlight, "Separator.foreground", controlShadow, // *** ScrollBar/ScrollPane/Viewport "ScrollBar.background", scrollBarTrack, "ScrollBar.foreground", control, "ScrollBar.track", table.get("scrollbar"), "ScrollBar.trackHighlight", controlDkShadow, "ScrollBar.thumb", control, "ScrollBar.thumbHighlight", controlLtHighlight, "ScrollBar.thumbDarkShadow", controlDkShadow, "ScrollBar.thumbShadow", controlShadow, "ScrollBar.border", null, "ScrollBar.minimumThumbSize", minimumThumbSize, "ScrollBar.maximumThumbSize", maximumThumbSize, "ScrollBar.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "positiveUnitIncrement", "KP_RIGHT", "positiveUnitIncrement", "DOWN", "positiveUnitIncrement", "KP_DOWN", "positiveUnitIncrement", "PAGE_DOWN", "positiveBlockIncrement", "LEFT", "negativeUnitIncrement", "KP_LEFT", "negativeUnitIncrement", "UP", "negativeUnitIncrement", "KP_UP", "negativeUnitIncrement", "PAGE_UP", "negativeBlockIncrement", "HOME", "minScroll", "END", "maxScroll" }), "ScrollBar.ancestorInputMap.RightToLeft", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "negativeUnitIncrement", "KP_RIGHT", "negativeUnitIncrement", "LEFT", "positiveUnitIncrement", "KP_LEFT", "positiveUnitIncrement", }), "ScrollBar.width", new Integer(16), "ScrollPane.font", dialogPlain12, "ScrollPane.background", control, "ScrollPane.foreground", controlText, "ScrollPane.border", textFieldBorder, "ScrollPane.viewportBorder", null, "ScrollPane.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "unitScrollRight", "KP_RIGHT", "unitScrollRight", "DOWN", "unitScrollDown", "KP_DOWN", "unitScrollDown", "LEFT", "unitScrollLeft", "KP_LEFT", "unitScrollLeft", "UP", "unitScrollUp", "KP_UP", "unitScrollUp", "PAGE_UP", "scrollUp", "PAGE_DOWN", "scrollDown", "ctrl PAGE_UP", "scrollLeft", "ctrl PAGE_DOWN", "scrollRight", "ctrl HOME", "scrollHome", "ctrl END", "scrollEnd" }), "ScrollPane.ancestorInputMap.RightToLeft", new UIDefaults.LazyInputMap(new Object[] { "ctrl PAGE_UP", "scrollRight", "ctrl PAGE_DOWN", "scrollLeft", }), "Viewport.font", dialogPlain12, "Viewport.background", control, "Viewport.foreground", textText, // *** Slider "Slider.font", dialogPlain12, "Slider.foreground", control, "Slider.background", control, "Slider.highlight", controlLtHighlight, "Slider.tickColor", Color.black, "Slider.shadow", controlShadow, "Slider.focus", controlDkShadow, "Slider.border", null, "Slider.horizontalSize", new Dimension(200, 21), "Slider.verticalSize", new Dimension(21, 200), "Slider.minimumHorizontalSize", new Dimension(36, 21), "Slider.minimumVerticalSize", new Dimension(21, 36), "Slider.focusInsets", sliderFocusInsets, "Slider.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "positiveUnitIncrement", "KP_RIGHT", "positiveUnitIncrement", "DOWN", "negativeUnitIncrement", "KP_DOWN", "negativeUnitIncrement", "PAGE_DOWN", "negativeBlockIncrement", "LEFT", "negativeUnitIncrement", "KP_LEFT", "negativeUnitIncrement", "UP", "positiveUnitIncrement", "KP_UP", "positiveUnitIncrement", "PAGE_UP", "positiveBlockIncrement", "HOME", "minScroll", "END", "maxScroll" }), "Slider.focusInputMap.RightToLeft", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "negativeUnitIncrement", "KP_RIGHT", "negativeUnitIncrement", "LEFT", "positiveUnitIncrement", "KP_LEFT", "positiveUnitIncrement", }), // *** Spinner "Spinner.font", monospacedPlain12, "Spinner.background", control, "Spinner.foreground", control, "Spinner.border", textFieldBorder, "Spinner.arrowButtonBorder", null, "Spinner.arrowButtonInsets", null, "Spinner.arrowButtonSize", new Dimension(16, 5), "Spinner.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "UP", "increment", "KP_UP", "increment", "DOWN", "decrement", "KP_DOWN", "decrement", }), "Spinner.editorBorderPainted", Boolean.FALSE, "Spinner.editorAlignment", JTextField.TRAILING, // *** SplitPane "SplitPane.background", control, "SplitPane.highlight", controlLtHighlight, "SplitPane.shadow", controlShadow, "SplitPane.darkShadow", controlDkShadow, "SplitPane.border", splitPaneBorder, "SplitPane.dividerSize", new Integer(7), "SplitPaneDivider.border", splitPaneDividerBorder, "SplitPaneDivider.draggingColor", darkGray, "SplitPane.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "UP", "negativeIncrement", "DOWN", "positiveIncrement", "LEFT", "negativeIncrement", "RIGHT", "positiveIncrement", "KP_UP", "negativeIncrement", "KP_DOWN", "positiveIncrement", "KP_LEFT", "negativeIncrement", "KP_RIGHT", "positiveIncrement", "HOME", "selectMin", "END", "selectMax", "F8", "startResize", "F6", "toggleFocus", "ctrl TAB", "focusOutForward", "ctrl shift TAB", "focusOutBackward" }), // *** TabbedPane "TabbedPane.font", dialogPlain12, "TabbedPane.background", control, "TabbedPane.foreground", controlText, "TabbedPane.highlight", controlLtHighlight, "TabbedPane.light", controlHighlight, "TabbedPane.shadow", controlShadow, "TabbedPane.darkShadow", controlDkShadow, "TabbedPane.selected", null, "TabbedPane.focus", controlText, "TabbedPane.textIconGap", four, // Causes tabs to be painted on top of the content area border. // The amount of overlap is then controlled by tabAreaInsets.bottom, // which is zero by default "TabbedPane.tabsOverlapBorder", Boolean.FALSE, "TabbedPane.selectionFollowsFocus", Boolean.TRUE, "TabbedPane.labelShift", 1, "TabbedPane.selectedLabelShift", -1, "TabbedPane.tabInsets", tabbedPaneTabInsets, "TabbedPane.selectedTabPadInsets", tabbedPaneTabPadInsets, "TabbedPane.tabAreaInsets", tabbedPaneTabAreaInsets, "TabbedPane.contentBorderInsets", tabbedPaneContentBorderInsets, "TabbedPane.tabRunOverlay", new Integer(2), "TabbedPane.tabsOpaque", Boolean.TRUE, "TabbedPane.contentOpaque", Boolean.TRUE, "TabbedPane.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "navigateRight", "KP_RIGHT", "navigateRight", "LEFT", "navigateLeft", "KP_LEFT", "navigateLeft", "UP", "navigateUp", "KP_UP", "navigateUp", "DOWN", "navigateDown", "KP_DOWN", "navigateDown", "ctrl DOWN", "requestFocusForVisibleComponent", "ctrl KP_DOWN", "requestFocusForVisibleComponent", }), "TabbedPane.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl PAGE_DOWN", "navigatePageDown", "ctrl PAGE_UP", "navigatePageUp", "ctrl UP", "requestFocus", "ctrl KP_UP", "requestFocus", }), // *** Table "Table.font", dialogPlain12, "Table.foreground", controlText, // cell text color "Table.background", window, // cell background color "Table.selectionForeground", textHighlightText, "Table.selectionBackground", textHighlight, "Table.dropLineColor", controlShadow, "Table.dropLineShortColor", black, "Table.gridColor", gray, // grid line color "Table.focusCellBackground", window, "Table.focusCellForeground", controlText, "Table.focusCellHighlightBorder", focusCellHighlightBorder, "Table.scrollPaneBorder", loweredBevelBorder, "Table.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl C", "copy", "ctrl V", "paste", "ctrl X", "cut", "COPY", "copy", "PASTE", "paste", "CUT", "cut", "control INSERT", "copy", "shift INSERT", "paste", "shift DELETE", "cut", "RIGHT", "selectNextColumn", "KP_RIGHT", "selectNextColumn", "shift RIGHT", "selectNextColumnExtendSelection", "shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl shift RIGHT", "selectNextColumnExtendSelection", "ctrl shift KP_RIGHT", "selectNextColumnExtendSelection", "ctrl RIGHT", "selectNextColumnChangeLead", "ctrl KP_RIGHT", "selectNextColumnChangeLead", "LEFT", "selectPreviousColumn", "KP_LEFT", "selectPreviousColumn", "shift LEFT", "selectPreviousColumnExtendSelection", "shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl shift LEFT", "selectPreviousColumnExtendSelection", "ctrl shift KP_LEFT", "selectPreviousColumnExtendSelection", "ctrl LEFT", "selectPreviousColumnChangeLead", "ctrl KP_LEFT", "selectPreviousColumnChangeLead", "DOWN", "selectNextRow", "KP_DOWN", "selectNextRow", "shift DOWN", "selectNextRowExtendSelection", "shift KP_DOWN", "selectNextRowExtendSelection", "ctrl shift DOWN", "selectNextRowExtendSelection", "ctrl shift KP_DOWN", "selectNextRowExtendSelection", "ctrl DOWN", "selectNextRowChangeLead", "ctrl KP_DOWN", "selectNextRowChangeLead", "UP", "selectPreviousRow", "KP_UP", "selectPreviousRow", "shift UP", "selectPreviousRowExtendSelection", "shift KP_UP", "selectPreviousRowExtendSelection", "ctrl shift UP", "selectPreviousRowExtendSelection", "ctrl shift KP_UP", "selectPreviousRowExtendSelection", "ctrl UP", "selectPreviousRowChangeLead", "ctrl KP_UP", "selectPreviousRowChangeLead", "HOME", "selectFirstColumn", "shift HOME", "selectFirstColumnExtendSelection", "ctrl shift HOME", "selectFirstRowExtendSelection", "ctrl HOME", "selectFirstRow", "END", "selectLastColumn", "shift END", "selectLastColumnExtendSelection", "ctrl shift END", "selectLastRowExtendSelection", "ctrl END", "selectLastRow", "PAGE_UP", "scrollUpChangeSelection", "shift PAGE_UP", "scrollUpExtendSelection", "ctrl shift PAGE_UP", "scrollLeftExtendSelection", "ctrl PAGE_UP", "scrollLeftChangeSelection", "PAGE_DOWN", "scrollDownChangeSelection", "shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl shift PAGE_DOWN", "scrollRightExtendSelection", "ctrl PAGE_DOWN", "scrollRightChangeSelection", "TAB", "selectNextColumnCell", "shift TAB", "selectPreviousColumnCell", "ENTER", "selectNextRowCell", "shift ENTER", "selectPreviousRowCell", "ctrl A", "selectAll", "ctrl SLASH", "selectAll", "ctrl BACK_SLASH", "clearSelection", "ESCAPE", "cancel", "F2", "startEditing", "SPACE", "addToSelection", "ctrl SPACE", "toggleAndAnchor", "shift SPACE", "extendTo", "ctrl shift SPACE", "moveSelectionTo", "F8", "focusHeader" }), "Table.ancestorInputMap.RightToLeft", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "selectPreviousColumn", "KP_RIGHT", "selectPreviousColumn", "shift RIGHT", "selectPreviousColumnExtendSelection", "shift KP_RIGHT", "selectPreviousColumnExtendSelection", "ctrl shift RIGHT", "selectPreviousColumnExtendSelection", "ctrl shift KP_RIGHT", "selectPreviousColumnExtendSelection", "ctrl RIGHT", "selectPreviousColumnChangeLead", "ctrl KP_RIGHT", "selectPreviousColumnChangeLead", "LEFT", "selectNextColumn", "KP_LEFT", "selectNextColumn", "shift LEFT", "selectNextColumnExtendSelection", "shift KP_LEFT", "selectNextColumnExtendSelection", "ctrl shift LEFT", "selectNextColumnExtendSelection", "ctrl shift KP_LEFT", "selectNextColumnExtendSelection", "ctrl LEFT", "selectNextColumnChangeLead", "ctrl KP_LEFT", "selectNextColumnChangeLead", "ctrl PAGE_UP", "scrollRightChangeSelection", "ctrl PAGE_DOWN", "scrollLeftChangeSelection", "ctrl shift PAGE_UP", "scrollRightExtendSelection", "ctrl shift PAGE_DOWN", "scrollLeftExtendSelection", }), "Table.ascendingSortIcon", new SwingLazyValue( "sun.swing.icon.SortArrowIcon", null, new Object[] { Boolean.TRUE, "Table.sortIconColor" }), "Table.descendingSortIcon", new SwingLazyValue( "sun.swing.icon.SortArrowIcon", null, new Object[] { Boolean.FALSE, "Table.sortIconColor" }), "Table.sortIconColor", controlShadow, "TableHeader.font", dialogPlain12, "TableHeader.foreground", controlText, // header text color "TableHeader.background", control, // header background "TableHeader.cellBorder", tableHeaderBorder, // Support for changing the background/border of the currently // selected header column when the header has the keyboard focus. "TableHeader.focusCellBackground", table.getColor("text"), // like text component bg "TableHeader.focusCellForeground", null, "TableHeader.focusCellBorder", null, "TableHeader.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "SPACE", "toggleSortOrder", "LEFT", "selectColumnToLeft", "KP_LEFT", "selectColumnToLeft", "RIGHT", "selectColumnToRight", "KP_RIGHT", "selectColumnToRight", "alt LEFT", "moveColumnLeft", "alt KP_LEFT", "moveColumnLeft", "alt RIGHT", "moveColumnRight", "alt KP_RIGHT", "moveColumnRight", "alt shift LEFT", "resizeLeft", "alt shift KP_LEFT", "resizeLeft", "alt shift RIGHT", "resizeRight", "alt shift KP_RIGHT", "resizeRight", "ESCAPE", "focusTable", }), // *** Text "TextField.font", sansSerifPlain12, "TextField.background", window, "TextField.foreground", textText, "TextField.shadow", controlShadow, "TextField.darkShadow", controlDkShadow, "TextField.light", controlHighlight, "TextField.highlight", controlLtHighlight, "TextField.inactiveForeground", textInactiveText, "TextField.inactiveBackground", control, "TextField.selectionBackground", textHighlight, "TextField.selectionForeground", textHighlightText, "TextField.caretForeground", textText, "TextField.caretBlinkRate", caretBlinkRate, "TextField.border", textFieldBorder, "TextField.margin", zeroInsets, "FormattedTextField.font", sansSerifPlain12, "FormattedTextField.background", window, "FormattedTextField.foreground", textText, "FormattedTextField.inactiveForeground", textInactiveText, "FormattedTextField.inactiveBackground", control, "FormattedTextField.selectionBackground", textHighlight, "FormattedTextField.selectionForeground", textHighlightText, "FormattedTextField.caretForeground", textText, "FormattedTextField.caretBlinkRate", caretBlinkRate, "FormattedTextField.border", textFieldBorder, "FormattedTextField.margin", zeroInsets, "FormattedTextField.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl C", DefaultEditorKit.copyAction, "ctrl V", DefaultEditorKit.pasteAction, "ctrl X", DefaultEditorKit.cutAction, "COPY", DefaultEditorKit.copyAction, "PASTE", DefaultEditorKit.pasteAction, "CUT", DefaultEditorKit.cutAction, "control INSERT", DefaultEditorKit.copyAction, "shift INSERT", DefaultEditorKit.pasteAction, "shift DELETE", DefaultEditorKit.cutAction, "shift LEFT", DefaultEditorKit.selectionBackwardAction, "shift KP_LEFT", DefaultEditorKit.selectionBackwardAction, "shift RIGHT", DefaultEditorKit.selectionForwardAction, "shift KP_RIGHT", DefaultEditorKit.selectionForwardAction, "ctrl LEFT", DefaultEditorKit.previousWordAction, "ctrl KP_LEFT", DefaultEditorKit.previousWordAction, "ctrl RIGHT", DefaultEditorKit.nextWordAction, "ctrl KP_RIGHT", DefaultEditorKit.nextWordAction, "ctrl shift LEFT", DefaultEditorKit.selectionPreviousWordAction, "ctrl shift KP_LEFT", DefaultEditorKit.selectionPreviousWordAction, "ctrl shift RIGHT", DefaultEditorKit.selectionNextWordAction, "ctrl shift KP_RIGHT", DefaultEditorKit.selectionNextWordAction, "ctrl A", DefaultEditorKit.selectAllAction, "HOME", DefaultEditorKit.beginLineAction, "END", DefaultEditorKit.endLineAction, "shift HOME", DefaultEditorKit.selectionBeginLineAction, "shift END", DefaultEditorKit.selectionEndLineAction, "BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "shift BACK_SPACE", DefaultEditorKit.deletePrevCharAction, "ctrl H", DefaultEditorKit.deletePrevCharAction, "DELETE", DefaultEditorKit.deleteNextCharAction, "ctrl DELETE", DefaultEditorKit.deleteNextWordAction, "ctrl BACK_SPACE", DefaultEditorKit.deletePrevWordAction, "RIGHT", DefaultEditorKit.forwardAction, "LEFT", DefaultEditorKit.backwardAction, "KP_RIGHT", DefaultEditorKit.forwardAction, "KP_LEFT", DefaultEditorKit.backwardAction, "ENTER", JTextField.notifyAction, "ctrl BACK_SLASH", "unselect", "control shift O", "toggle-componentOrientation", "ESCAPE", "reset-field-edit", "UP", "increment", "KP_UP", "increment", "DOWN", "decrement", "KP_DOWN", "decrement", }), "PasswordField.font", monospacedPlain12, "PasswordField.background", window, "PasswordField.foreground", textText, "PasswordField.inactiveForeground", textInactiveText, "PasswordField.inactiveBackground", control, "PasswordField.selectionBackground", textHighlight, "PasswordField.selectionForeground", textHighlightText, "PasswordField.caretForeground", textText, "PasswordField.caretBlinkRate", caretBlinkRate, "PasswordField.border", textFieldBorder, "PasswordField.margin", zeroInsets, "PasswordField.echoChar", '*', "TextArea.font", monospacedPlain12, "TextArea.background", window, "TextArea.foreground", textText, "TextArea.inactiveForeground", textInactiveText, "TextArea.selectionBackground", textHighlight, "TextArea.selectionForeground", textHighlightText, "TextArea.caretForeground", textText, "TextArea.caretBlinkRate", caretBlinkRate, "TextArea.border", marginBorder, "TextArea.margin", zeroInsets, "TextPane.font", serifPlain12, "TextPane.background", white, "TextPane.foreground", textText, "TextPane.selectionBackground", textHighlight, "TextPane.selectionForeground", textHighlightText, "TextPane.caretForeground", textText, "TextPane.caretBlinkRate", caretBlinkRate, "TextPane.inactiveForeground", textInactiveText, "TextPane.border", marginBorder, "TextPane.margin", editorMargin, "EditorPane.font", serifPlain12, "EditorPane.background", white, "EditorPane.foreground", textText, "EditorPane.selectionBackground", textHighlight, "EditorPane.selectionForeground", textHighlightText, "EditorPane.caretForeground", textText, "EditorPane.caretBlinkRate", caretBlinkRate, "EditorPane.inactiveForeground", textInactiveText, "EditorPane.border", marginBorder, "EditorPane.margin", editorMargin, "html.pendingImage", SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/image-delayed.png"), "html.missingImage", SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/image-failed.png"), // *** TitledBorder "TitledBorder.font", dialogPlain12, "TitledBorder.titleColor", controlText, "TitledBorder.border", etchedBorder, // *** ToolBar "ToolBar.font", dialogPlain12, "ToolBar.background", control, "ToolBar.foreground", controlText, "ToolBar.shadow", controlShadow, "ToolBar.darkShadow", controlDkShadow, "ToolBar.light", controlHighlight, "ToolBar.highlight", controlLtHighlight, "ToolBar.dockingBackground", control, "ToolBar.dockingForeground", red, "ToolBar.floatingBackground", control, "ToolBar.floatingForeground", darkGray, "ToolBar.border", etchedBorder, "ToolBar.separatorSize", toolBarSeparatorSize, "ToolBar.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "UP", "navigateUp", "KP_UP", "navigateUp", "DOWN", "navigateDown", "KP_DOWN", "navigateDown", "LEFT", "navigateLeft", "KP_LEFT", "navigateLeft", "RIGHT", "navigateRight", "KP_RIGHT", "navigateRight" }), // *** ToolTips "ToolTip.font", sansSerifPlain12, "ToolTip.background", table.get("info"), "ToolTip.foreground", table.get("infoText"), "ToolTip.border", blackLineBorder, // ToolTips also support backgroundInactive, borderInactive, // and foregroundInactive // *** ToolTipManager // ToolTipManager.enableToolTipMode currently supports: // "allWindows" (default): // enables tool tips for all windows of all java applications, // whether the windows are active or inactive // "activeApplication" // enables tool tips for windows of an application only when // the application has an active window "ToolTipManager.enableToolTipMode", "allWindows", // *** Tree "Tree.paintLines", Boolean.TRUE, "Tree.lineTypeDashed", Boolean.FALSE, "Tree.font", dialogPlain12, "Tree.background", window, "Tree.foreground", textText, "Tree.hash", gray, "Tree.textForeground", textText, "Tree.textBackground", table.get("text"), "Tree.selectionForeground", textHighlightText, "Tree.selectionBackground", textHighlight, "Tree.selectionBorderColor", black, "Tree.dropLineColor", controlShadow, "Tree.editorBorder", blackLineBorder, "Tree.leftChildIndent", new Integer(7), "Tree.rightChildIndent", new Integer(13), "Tree.rowHeight", new Integer(16), "Tree.scrollsOnExpand", Boolean.TRUE, "Tree.openIcon", SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/TreeOpen.gif"), "Tree.closedIcon", SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/TreeClosed.gif"), "Tree.leafIcon", SwingUtilities2.makeIcon(getClass(), BasicLookAndFeel.class, "icons/TreeLeaf.gif"), "Tree.expandedIcon", null, "Tree.collapsedIcon", null, "Tree.changeSelectionWithFocus", Boolean.TRUE, "Tree.drawsFocusBorderAroundIcon", Boolean.FALSE, "Tree.timeFactor", oneThousand, "Tree.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl C", "copy", "ctrl V", "paste", "ctrl X", "cut", "COPY", "copy", "PASTE", "paste", "CUT", "cut", "control INSERT", "copy", "shift INSERT", "paste", "shift DELETE", "cut", "UP", "selectPrevious", "KP_UP", "selectPrevious", "shift UP", "selectPreviousExtendSelection", "shift KP_UP", "selectPreviousExtendSelection", "ctrl shift UP", "selectPreviousExtendSelection", "ctrl shift KP_UP", "selectPreviousExtendSelection", "ctrl UP", "selectPreviousChangeLead", "ctrl KP_UP", "selectPreviousChangeLead", "DOWN", "selectNext", "KP_DOWN", "selectNext", "shift DOWN", "selectNextExtendSelection", "shift KP_DOWN", "selectNextExtendSelection", "ctrl shift DOWN", "selectNextExtendSelection", "ctrl shift KP_DOWN", "selectNextExtendSelection", "ctrl DOWN", "selectNextChangeLead", "ctrl KP_DOWN", "selectNextChangeLead", "RIGHT", "selectChild", "KP_RIGHT", "selectChild", "LEFT", "selectParent", "KP_LEFT", "selectParent", "PAGE_UP", "scrollUpChangeSelection", "shift PAGE_UP", "scrollUpExtendSelection", "ctrl shift PAGE_UP", "scrollUpExtendSelection", "ctrl PAGE_UP", "scrollUpChangeLead", "PAGE_DOWN", "scrollDownChangeSelection", "shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl shift PAGE_DOWN", "scrollDownExtendSelection", "ctrl PAGE_DOWN", "scrollDownChangeLead", "HOME", "selectFirst", "shift HOME", "selectFirstExtendSelection", "ctrl shift HOME", "selectFirstExtendSelection", "ctrl HOME", "selectFirstChangeLead", "END", "selectLast", "shift END", "selectLastExtendSelection", "ctrl shift END", "selectLastExtendSelection", "ctrl END", "selectLastChangeLead", "F2", "startEditing", "ctrl A", "selectAll", "ctrl SLASH", "selectAll", "ctrl BACK_SLASH", "clearSelection", "ctrl LEFT", "scrollLeft", "ctrl KP_LEFT", "scrollLeft", "ctrl RIGHT", "scrollRight", "ctrl KP_RIGHT", "scrollRight", "SPACE", "addToSelection", "ctrl SPACE", "toggleAndAnchor", "shift SPACE", "extendTo", "ctrl shift SPACE", "moveSelectionTo" }), "Tree.focusInputMap.RightToLeft", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "selectParent", "KP_RIGHT", "selectParent", "LEFT", "selectChild", "KP_LEFT", "selectChild", }), "Tree.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ESCAPE", "cancel" }), // Bind specific keys that can invoke popup on currently // focused JComponent "RootPane.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "shift F10", "postPopup", "CONTEXT_MENU", "postPopup" }), // These bindings are only enabled when there is a default // button set on the rootpane. "RootPane.defaultButtonWindowKeyBindings", new Object[] { "ENTER", "press", "released ENTER", "release", "ctrl ENTER", "press", "ctrl released ENTER", "release" }, }; table.putDefaults(defaults); } /** {@collect.stats} * Returns the ui that is of type <code>klass</code>, or null if * one can not be found. */ static Object getUIOfType(ComponentUI ui, Class klass) { if (klass.isInstance(ui)) { return ui; } return null; } // ********* Auditory Cue support methods and objects ********* // also see the "AuditoryCues" section of the defaults table /** {@collect.stats} * Returns an <code>ActionMap</code> containing the audio actions * for this look and feel. * <P> * The returned <code>ActionMap</code> contains <code>Actions</code> that * embody the ability to render an auditory cue. These auditory * cues map onto user and system activities that may be useful * for an end user to know about (such as a dialog box appearing). * <P> * At the appropriate time, * the {@code ComponentUI} is responsible for obtaining an * <code>Action</code> out of the <code>ActionMap</code> and passing * it to <code>playSound</code>. * <P> * This method first looks up the {@code ActionMap} from the * defaults using the key {@code "AuditoryCues.actionMap"}. * <p> * If the value is {@code non-null}, it is returned. If the value * of the default {@code "AuditoryCues.actionMap"} is {@code null} * and the value of the default {@code "AuditoryCues.cueList"} is * {@code non-null}, an {@code ActionMapUIResource} is created and * populated. Population is done by iterating over each of the * elements of the {@code "AuditoryCues.cueList"} array, and * invoking {@code createAudioAction()} to create an {@code * Action} for each element. The resulting {@code Action} is * placed in the {@code ActionMapUIResource}, using the array * element as the key. For example, if the {@code * "AuditoryCues.cueList"} array contains a single-element, {@code * "audioKey"}, the {@code ActionMapUIResource} is created, then * populated by way of {@code actionMap.put(cueList[0], * createAudioAction(cueList[0]))}. * <p> * If the value of the default {@code "AuditoryCues.actionMap"} is * {@code null} and the value of the default * {@code "AuditoryCues.cueList"} is {@code null}, an empty * {@code ActionMapUIResource} is created. * * * @return an ActionMap containing {@code Actions} * responsible for playing auditory cues * @throws ClassCastException if the value of the * default {@code "AuditoryCues.actionMap"} is not an * {@code ActionMap}, or the value of the default * {@code "AuditoryCues.cueList"} is not an {@code Object[]} * @see #createAudioAction * @see #playSound(Action) * @since 1.4 */ protected ActionMap getAudioActionMap() { ActionMap audioActionMap = (ActionMap)UIManager.get( "AuditoryCues.actionMap"); if (audioActionMap == null) { Object[] acList = (Object[])UIManager.get("AuditoryCues.cueList"); if (acList != null) { audioActionMap = new ActionMapUIResource(); for(int counter = acList.length-1; counter >= 0; counter--) { audioActionMap.put(acList[counter], createAudioAction(acList[counter])); } } UIManager.getLookAndFeelDefaults().put("AuditoryCues.actionMap", audioActionMap); } return audioActionMap; } /** {@collect.stats} * Creates and returns an {@code Action} used to play a sound. * <p> * If {@code key} is {@code non-null}, an {@code Action} is created * using the value from the defaults with key {@code key}. The value * identifies the sound resource to load when * {@code actionPerformed} is invoked on the {@code Action}. The * sound resource is loaded into a {@code byte[]} by way of * {@code getClass().getResourceAsStream()}. * * @param key the key identifying the audio action * @return an {@code Action} used to play the source, or {@code null} * if {@code key} is {@code null} * @see #playSound(Action) * @since 1.4 */ protected Action createAudioAction(Object key) { if (key != null) { String audioKey = (String)key; String audioValue = (String)UIManager.get(key); return new AudioAction(audioKey, audioValue); } else { return null; } } /** {@collect.stats} * Pass the name String to the super constructor. This is used * later to identify the Action and decide whether to play it or * not. Store the resource String. I is used to get the audio * resource. In this case, the resource is an audio file. * * @since 1.4 */ private class AudioAction extends AbstractAction implements LineListener { // We strive to only play one sound at a time (other platforms // appear to do this). This is done by maintaining the field // clipPlaying. Every time a sound is to be played, // cancelCurrentSound is invoked to cancel any sound that may be // playing. private String audioResource; private byte[] audioBuffer; /** {@collect.stats} * The String is the name of the Action and * points to the audio resource. * The byte[] is a buffer of the audio bits. */ public AudioAction(String name, String resource) { super(name); audioResource = resource; } public void actionPerformed(ActionEvent e) { if (audioBuffer == null) { audioBuffer = loadAudioData(audioResource); } if (audioBuffer != null) { cancelCurrentSound(null); try { AudioInputStream soundStream = AudioSystem.getAudioInputStream( new ByteArrayInputStream(audioBuffer)); DataLine.Info info = new DataLine.Info(Clip.class, soundStream.getFormat()); Clip clip = (Clip) AudioSystem.getLine(info); clip.open(soundStream); clip.addLineListener(this); synchronized(audioLock) { clipPlaying = clip; } clip.start(); } catch (Exception ex) {} } } public void update(LineEvent event) { if (event.getType() == LineEvent.Type.STOP) { cancelCurrentSound((Clip)event.getLine()); } } /** {@collect.stats} * If the parameter is null, or equal to the currently * playing sound, then cancel the currently playing sound. */ private void cancelCurrentSound(Clip clip) { Clip lastClip = null; synchronized(audioLock) { if (clip == null || clip == clipPlaying) { lastClip = clipPlaying; clipPlaying = null; } } if (lastClip != null) { lastClip.removeLineListener(this); lastClip.close(); } } } /** {@collect.stats} * Utility method that loads audio bits for the specified * <code>soundFile</code> filename. If this method is unable to * build a viable path name from the <code>baseClass</code> and * <code>soundFile</code> passed into this method, it will * return <code>null</code>. * * @param baseClass used as the root class/location to get the * soundFile from * @param soundFile the name of the audio file to be retrieved * from disk * @return A byte[] with audio data or null * @since 1.4 */ private byte[] loadAudioData(final String soundFile){ if (soundFile == null) { return null; } /* Copy resource into a byte array. This is * necessary because several browsers consider * Class.getResource a security risk since it * can be used to load additional classes. * Class.getResourceAsStream just returns raw * bytes, which we can convert to a sound. */ byte[] buffer = (byte[])AccessController.doPrivileged( new PrivilegedAction() { public Object run() { try { InputStream resource = BasicLookAndFeel.this. getClass().getResourceAsStream(soundFile); 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(); buffer = out.toByteArray(); return buffer; } catch (IOException ioe) { System.err.println(ioe.toString()); return null; } } }); if (buffer == null) { System.err.println(getClass().getName() + "/" + soundFile + " not found."); return null; } if (buffer.length == 0) { System.err.println("warning: " + soundFile + " is zero-length"); return null; } return buffer; } /** {@collect.stats} * If necessary, invokes {@code actionPerformed} on * {@code audioAction} to play a sound. * The {@code actionPerformed} method is invoked if the value of * the {@code "AuditoryCues.playList"} default is a {@code * non-null} {@code Object[]} containing a {@code String} entry * equal to the name of the {@code audioAction}. * * @param audioAction an Action that knows how to render the audio * associated with the system or user activity * that is occurring; a value of {@code null}, is * ignored * @throws ClassCastException if {@code audioAction} is {@code non-null} * and the value of the default {@code "AuditoryCues.playList"} * is not an {@code Object[]} * @since 1.4 */ protected void playSound(Action audioAction) { if (audioAction != null) { Object[] audioStrings = (Object[]) UIManager.get("AuditoryCues.playList"); if (audioStrings != null) { // create a HashSet to help us decide to play or not HashSet audioCues = new HashSet(); for (int i = 0; i < audioStrings.length; i++) { audioCues.add(audioStrings[i]); } // get the name of the Action String actionName = (String)audioAction.getValue(Action.NAME); // if the actionName is in the audioCues HashSet, play it. if (audioCues.contains(actionName)) { audioAction.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, actionName)); } } } } /** {@collect.stats} * Sets the parent of the passed in ActionMap to be the audio action * map. */ static void installAudioActionMap(ActionMap map) { LookAndFeel laf = UIManager.getLookAndFeel(); if (laf instanceof BasicLookAndFeel) { map.setParent(((BasicLookAndFeel)laf).getAudioActionMap()); } } /** {@collect.stats} * Helper method to play a named sound. * * @param c JComponent to play the sound for. * @param actionKey Key for the sound. */ static void playSound(JComponent c, Object actionKey) { LookAndFeel laf = UIManager.getLookAndFeel(); if (laf instanceof BasicLookAndFeel) { ActionMap map = c.getActionMap(); if (map != null) { Action audioAction = map.get(actionKey); if (audioAction != null) { // pass off firing the Action to a utility method ((BasicLookAndFeel)laf).playSound(audioAction); } } } } /** {@collect.stats} * This class contains listener that watches for all the mouse * events that can possibly invoke popup on the component */ class AWTEventHelper implements AWTEventListener,PrivilegedAction { AWTEventHelper() { super(); AccessController.doPrivileged(this); } public Object run() { Toolkit tk = Toolkit.getDefaultToolkit(); if(invocator == null) { tk.addAWTEventListener(this, AWTEvent.MOUSE_EVENT_MASK); } else { tk.removeAWTEventListener(invocator); } // Return value not used. return null; } public void eventDispatched(AWTEvent ev) { int eventID = ev.getID(); if((eventID & AWTEvent.MOUSE_EVENT_MASK) != 0) { MouseEvent me = (MouseEvent) ev; if(me.isPopupTrigger()) { MenuElement[] elems = MenuSelectionManager .defaultManager() .getSelectedPath(); if(elems != null && elems.length != 0) { return; // We shall not interfere with already opened menu } Object c = me.getSource(); JComponent src = null; if(c instanceof JComponent) { src = (JComponent) c; } else if(c instanceof BasicSplitPaneDivider) { // Special case - if user clicks on divider we must // invoke popup from the SplitPane src = (JComponent) ((BasicSplitPaneDivider)c).getParent(); } if(src != null) { if(src.getComponentPopupMenu() != null) { Point pt = src.getPopupLocation(me); if(pt == null) { pt = me.getPoint(); pt = SwingUtilities.convertPoint((Component)c, pt, src); } src.getComponentPopupMenu().show(src, pt.x, pt.y); me.consume(); } } } } /* Activate a JInternalFrame if necessary. */ if (eventID == MouseEvent.MOUSE_PRESSED) { Object object = ev.getSource(); if (!(object instanceof Component)) { return; } Component component = (Component)object; if (component != null) { Component parent = component; while (parent != null && !(parent instanceof Window)) { if (parent instanceof JInternalFrame) { // Activate the frame. try { ((JInternalFrame)parent).setSelected(true); } catch (PropertyVetoException e1) { } } parent = parent.getParent(); } } } } } }
Java
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.plaf.*; import javax.swing.border.*; /** {@collect.stats} * BasicRadioButtonMenuItem implementation * * @author Georges Saab * @author David Karlton */ public class BasicRadioButtonMenuItemUI extends BasicMenuItemUI { public static ComponentUI createUI(JComponent b) { return new BasicRadioButtonMenuItemUI(); } protected String getPropertyPrefix() { return "RadioButtonMenuItem"; } public void processMouseEvent(JMenuItem item,MouseEvent e,MenuElement path[],MenuSelectionManager manager) { Point p = e.getPoint(); if(p.x >= 0 && p.x < item.getWidth() && p.y >= 0 && p.y < item.getHeight()) { if(e.getID() == MouseEvent.MOUSE_RELEASED) { manager.clearSelectedPath(); item.doClick(0); item.setArmed(false); } else manager.setSelectedPath(path); } else if(item.getModel().isArmed()) { MenuElement newPath[] = new MenuElement[path.length-1]; int i,c; for(i=0,c=path.length-1;i<c;i++) newPath[i] = path[i]; manager.setSelectedPath(newPath); } } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import sun.swing.SwingUtilities2; import sun.swing.DefaultLookup; import sun.swing.UIAction; import sun.awt.AppContext; import javax.swing.*; import javax.swing.plaf.*; import javax.swing.text.View; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Insets; import java.awt.Color; import java.awt.Graphics; import java.awt.Font; import java.awt.FontMetrics; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** {@collect.stats} * A Windows L&F implementation of LabelUI. This implementation * is completely static, i.e. there's only one UIView implementation * that's shared by all JLabel objects. * * @author Hans Muller */ public class BasicLabelUI extends LabelUI implements PropertyChangeListener { /** {@collect.stats} * The default <code>BasicLabelUI</code> instance. This field might * not be used. To change the default instance use a subclass which * overrides the <code>createUI</code> method, and place that class * name in defaults table under the key "LabelUI". */ protected static BasicLabelUI labelUI = new BasicLabelUI(); private static final Object BASIC_LABEL_UI_KEY = new Object(); private Rectangle paintIconR = new Rectangle(); private Rectangle paintTextR = new Rectangle(); static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.PRESS)); map.put(new Actions(Actions.RELEASE)); } /** {@collect.stats} * Forwards the call to SwingUtilities.layoutCompoundLabel(). * This method is here so that a subclass could do Label specific * layout and to shorten the method name a little. * * @see SwingUtilities#layoutCompoundLabel */ protected String layoutCL( JLabel label, FontMetrics fontMetrics, String text, Icon icon, Rectangle viewR, Rectangle iconR, Rectangle textR) { return SwingUtilities.layoutCompoundLabel( (JComponent) label, fontMetrics, text, icon, label.getVerticalAlignment(), label.getHorizontalAlignment(), label.getVerticalTextPosition(), label.getHorizontalTextPosition(), viewR, iconR, textR, label.getIconTextGap()); } /** {@collect.stats} * Paint clippedText at textX, textY with the labels foreground color. * * @see #paint * @see #paintDisabledText */ protected void paintEnabledText(JLabel l, Graphics g, String s, int textX, int textY) { int mnemIndex = l.getDisplayedMnemonicIndex(); g.setColor(l.getForeground()); SwingUtilities2.drawStringUnderlineCharAt(l, g, s, mnemIndex, textX, textY); } /** {@collect.stats} * Paint clippedText at textX, textY with background.lighter() and then * shifted down and to the right by one pixel with background.darker(). * * @see #paint * @see #paintEnabledText */ protected void paintDisabledText(JLabel l, Graphics g, String s, int textX, int textY) { int accChar = l.getDisplayedMnemonicIndex(); Color background = l.getBackground(); g.setColor(background.brighter()); SwingUtilities2.drawStringUnderlineCharAt(l, g, s, accChar, textX + 1, textY + 1); g.setColor(background.darker()); SwingUtilities2.drawStringUnderlineCharAt(l, g, s, accChar, textX, textY); } /** {@collect.stats} * Paint the label text in the foreground color, if the label * is opaque then paint the entire background with the background * color. The Label text is drawn by paintEnabledText() or * paintDisabledText(). The locations of the label parts are computed * by layoutCL. * * @see #paintEnabledText * @see #paintDisabledText * @see #layoutCL */ 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 = SwingUtilities2.getFontMetrics(label, g); String clippedText = layout(label, fm, c.getWidth(), c.getHeight()); if (icon != null) { icon.paintIcon(c, g, paintIconR.x, paintIconR.y); } if (text != null) { View v = (View) c.getClientProperty(BasicHTML.propertyKey); if (v != null) { v.paint(g, paintTextR); } else { 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); } } } } private String layout(JLabel label, FontMetrics fm, int width, int height) { Insets insets = label.getInsets(null); String text = label.getText(); Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon(); Rectangle paintViewR = new Rectangle(); paintViewR.x = insets.left; paintViewR.y = insets.top; paintViewR.width = width - (insets.left + insets.right); paintViewR.height = height - (insets.top + insets.bottom); paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0; paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0; return layoutCL(label, fm, text, icon, paintViewR, paintIconR, paintTextR); } public Dimension getPreferredSize(JComponent c) { JLabel label = (JLabel)c; String text = label.getText(); Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon(); Insets insets = label.getInsets(null); Font font = label.getFont(); int dx = insets.left + insets.right; int dy = insets.top + insets.bottom; if ((icon == null) && ((text == null) || ((text != null) && (font == null)))) { return new Dimension(dx, dy); } else if ((text == null) || ((icon != null) && (font == null))) { return new Dimension(icon.getIconWidth() + dx, icon.getIconHeight() + dy); } else { FontMetrics fm = label.getFontMetrics(font); Rectangle iconR = new Rectangle(); Rectangle textR = new Rectangle(); Rectangle viewR = new Rectangle(); iconR.x = iconR.y = iconR.width = iconR.height = 0; textR.x = textR.y = textR.width = textR.height = 0; viewR.x = dx; viewR.y = dy; viewR.width = viewR.height = Short.MAX_VALUE; layoutCL(label, fm, text, icon, viewR, iconR, textR); int x1 = Math.min(iconR.x, textR.x); int x2 = Math.max(iconR.x + iconR.width, textR.x + textR.width); int y1 = Math.min(iconR.y, textR.y); int y2 = Math.max(iconR.y + iconR.height, textR.y + textR.height); Dimension rv = new Dimension(x2 - x1, y2 - y1); rv.width += dx; rv.height += dy; return rv; } } /** {@collect.stats} * @return getPreferredSize(c) */ public Dimension getMinimumSize(JComponent c) { Dimension d = getPreferredSize(c); View v = (View) c.getClientProperty(BasicHTML.propertyKey); if (v != null) { d.width -= v.getPreferredSpan(View.X_AXIS) - v.getMinimumSpan(View.X_AXIS); } return d; } /** {@collect.stats} * @return getPreferredSize(c) */ public Dimension getMaximumSize(JComponent c) { Dimension d = getPreferredSize(c); View v = (View) c.getClientProperty(BasicHTML.propertyKey); if (v != null) { d.width += v.getMaximumSpan(View.X_AXIS) - v.getPreferredSpan(View.X_AXIS); } return d; } /** {@collect.stats} * Returns the baseline. * * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public int getBaseline(JComponent c, int width, int height) { super.getBaseline(c, width, height); JLabel label = (JLabel)c; String text = label.getText(); if (text == null || "".equals(text) || label.getFont() == null) { return -1; } FontMetrics fm = label.getFontMetrics(label.getFont()); layout(label, fm, width, height); return BasicHTML.getBaseline(label, paintTextR.y, fm.getAscent(), paintTextR.width, paintTextR.height); } /** {@collect.stats} * Returns an enum indicating how the baseline of the component * changes as the size changes. * * @throws NullPointerException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public Component.BaselineResizeBehavior getBaselineResizeBehavior( JComponent c) { super.getBaselineResizeBehavior(c); if (c.getClientProperty(BasicHTML.propertyKey) != null) { return Component.BaselineResizeBehavior.OTHER; } switch(((JLabel)c).getVerticalAlignment()) { case JLabel.TOP: return Component.BaselineResizeBehavior.CONSTANT_ASCENT; case JLabel.BOTTOM: return Component.BaselineResizeBehavior.CONSTANT_DESCENT; case JLabel.CENTER: return Component.BaselineResizeBehavior.CENTER_OFFSET; } return Component.BaselineResizeBehavior.OTHER; } public void installUI(JComponent c) { installDefaults((JLabel)c); installComponents((JLabel)c); installListeners((JLabel)c); installKeyboardActions((JLabel)c); } public void uninstallUI(JComponent c) { uninstallDefaults((JLabel)c); uninstallComponents((JLabel)c); uninstallListeners((JLabel)c); uninstallKeyboardActions((JLabel)c); } protected void installDefaults(JLabel c){ LookAndFeel.installColorsAndFont(c, "Label.background", "Label.foreground", "Label.font"); LookAndFeel.installProperty(c, "opaque", Boolean.FALSE); } protected void installListeners(JLabel c){ c.addPropertyChangeListener(this); } protected void installComponents(JLabel c){ BasicHTML.updateRenderer(c, c.getText()); c.setInheritsPopupMenu(true); } protected void installKeyboardActions(JLabel l) { int dka = l.getDisplayedMnemonic(); Component lf = l.getLabelFor(); if ((dka != 0) && (lf != null)) { LazyActionMap.installLazyActionMap(l, BasicLabelUI.class, "Label.actionMap"); InputMap inputMap = SwingUtilities.getUIInputMap (l, JComponent.WHEN_IN_FOCUSED_WINDOW); if (inputMap == null) { inputMap = new ComponentInputMapUIResource(l); SwingUtilities.replaceUIInputMap(l, JComponent.WHEN_IN_FOCUSED_WINDOW, inputMap); } inputMap.clear(); inputMap.put(KeyStroke.getKeyStroke(dka, ActionEvent.ALT_MASK, false), "press"); } else { InputMap inputMap = SwingUtilities.getUIInputMap (l, JComponent.WHEN_IN_FOCUSED_WINDOW); if (inputMap != null) { inputMap.clear(); } } } protected void uninstallDefaults(JLabel c){ } protected void uninstallListeners(JLabel c){ c.removePropertyChangeListener(this); } protected void uninstallComponents(JLabel c){ BasicHTML.updateRenderer(c, ""); } protected void uninstallKeyboardActions(JLabel c) { SwingUtilities.replaceUIInputMap(c, JComponent.WHEN_FOCUSED, null); SwingUtilities.replaceUIInputMap(c, JComponent.WHEN_IN_FOCUSED_WINDOW, null); SwingUtilities.replaceUIActionMap(c, null); } public static ComponentUI createUI(JComponent c) { if (System.getSecurityManager() != null) { AppContext appContext = AppContext.getAppContext(); BasicLabelUI safeBasicLabelUI = (BasicLabelUI) appContext.get(BASIC_LABEL_UI_KEY); if (safeBasicLabelUI == null) { safeBasicLabelUI = new BasicLabelUI(); appContext.put(BASIC_LABEL_UI_KEY, safeBasicLabelUI); } return safeBasicLabelUI; } return labelUI; } public void propertyChange(PropertyChangeEvent e) { String name = e.getPropertyName(); if (name == "text" || "font" == name || "foreground" == name) { // remove the old html view client property if one // existed, and install a new one if the text installed // into the JLabel is html source. JLabel lbl = ((JLabel) e.getSource()); String text = lbl.getText(); BasicHTML.updateRenderer(lbl, text); } else if (name == "labelFor" || name == "displayedMnemonic") { installKeyboardActions((JLabel) e.getSource()); } } // When the accelerator is pressed, temporarily make the JLabel // focusTraversable by registering a WHEN_FOCUSED action for the // release of the accelerator. Then give it focus so it can // prevent unwanted keyTyped events from getting to other components. private static class Actions extends UIAction { private static final String PRESS = "press"; private static final String RELEASE = "release"; Actions(String key) { super(key); } public void actionPerformed(ActionEvent e) { JLabel label = (JLabel)e.getSource(); String key = getName(); if (key == PRESS) { doPress(label); } else if (key == RELEASE) { doRelease(label); } } private void doPress(JLabel label) { Component labelFor = label.getLabelFor(); if (labelFor != null && labelFor.isEnabled()) { InputMap inputMap = SwingUtilities.getUIInputMap(label, JComponent.WHEN_FOCUSED); if (inputMap == null) { inputMap = new InputMapUIResource(); SwingUtilities.replaceUIInputMap(label, JComponent.WHEN_FOCUSED, inputMap); } int dka = label.getDisplayedMnemonic(); inputMap.put(KeyStroke.getKeyStroke(dka, ActionEvent.ALT_MASK, true), RELEASE); // Need this if ALT is released before the accelerator inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ALT, 0, true), RELEASE); label.requestFocus(); } } private void doRelease(JLabel label) { Component labelFor = label.getLabelFor(); if (labelFor != null && labelFor.isEnabled()) { InputMap inputMap = SwingUtilities.getUIInputMap(label, JComponent.WHEN_FOCUSED); if (inputMap != null) { // inputMap should never be null. inputMap.remove(KeyStroke.getKeyStroke(label.getDisplayedMnemonic(), ActionEvent.ALT_MASK, true)); inputMap.remove(KeyStroke.getKeyStroke(KeyEvent.VK_ALT, 0, true)); } if (labelFor instanceof Container && ((Container) labelFor).isFocusCycleRoot()) { labelFor.requestFocus(); } else { SwingUtilities2.compositeRequestFocus(labelFor); } } } } }
Java
/* * Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import sun.swing.DefaultLookup; import sun.swing.UIAction; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.*; import java.awt.peer.ComponentPeer; import java.awt.peer.LightweightPeer; import java.beans.*; import java.util.*; import javax.swing.plaf.SplitPaneUI; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.UIResource; import sun.swing.SwingUtilities2; /** {@collect.stats} * A Basic L&F implementation of the SplitPaneUI. * * @author Scott Violet * @author Steve Wilson * @author Ralph Kar */ public class BasicSplitPaneUI extends SplitPaneUI { /** {@collect.stats} * The divider used for non-continuous layout is added to the split pane * with this object. */ protected static final String NON_CONTINUOUS_DIVIDER = "nonContinuousDivider"; /** {@collect.stats} * How far (relative) the divider does move when it is moved around by * the cursor keys on the keyboard. */ protected static int KEYBOARD_DIVIDER_MOVE_OFFSET = 3; /** {@collect.stats} * JSplitPane instance this instance is providing * the look and feel for. */ protected JSplitPane splitPane; /** {@collect.stats} * LayoutManager that is created and placed into the split pane. */ protected BasicHorizontalLayoutManager layoutManager; /** {@collect.stats} * Instance of the divider for this JSplitPane. */ protected BasicSplitPaneDivider divider; /** {@collect.stats} * Instance of the PropertyChangeListener for this JSplitPane. */ protected PropertyChangeListener propertyChangeListener; /** {@collect.stats} * Instance of the FocusListener for this JSplitPane. */ protected FocusListener focusListener; private Handler handler; /** {@collect.stats} * Keys to use for forward focus traversal when the JComponent is * managing focus. */ private Set managingFocusForwardTraversalKeys; /** {@collect.stats} * Keys to use for backward focus traversal when the JComponent is * managing focus. */ private Set managingFocusBackwardTraversalKeys; /** {@collect.stats} * The size of the divider while the dragging session is valid. */ protected int dividerSize; /** {@collect.stats} * Instance for the shadow of the divider when non continuous layout * is being used. */ protected Component nonContinuousLayoutDivider; /** {@collect.stats} * Set to true in startDragging if any of the children * (not including the nonContinuousLayoutDivider) are heavy weights. */ protected boolean draggingHW; /** {@collect.stats} * Location of the divider when the dragging session began. */ protected int beginDragDividerLocation; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected KeyStroke upKey; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected KeyStroke downKey; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected KeyStroke leftKey; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected KeyStroke rightKey; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected KeyStroke homeKey; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected KeyStroke endKey; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected KeyStroke dividerResizeToggleKey; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected ActionListener keyboardUpLeftListener; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected ActionListener keyboardDownRightListener; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected ActionListener keyboardHomeListener; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected ActionListener keyboardEndListener; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected ActionListener keyboardResizeToggleListener; // Private data of the instance private int orientation; private int lastDragLocation; private boolean continuousLayout; private boolean dividerKeyboardResize; private boolean dividerLocationIsSet; // needed for tracking // the first occurrence of // setDividerLocation() private Color dividerDraggingColor; private boolean rememberPaneSizes; // Indicates wether the one of splitpane sides is expanded private boolean keepHidden = false; /** {@collect.stats} Indicates that we have painted once. */ // This is used by the LayoutManager to determine when it should use // the divider location provided by the JSplitPane. This is used as there // is no way to determine when the layout process has completed. boolean painted; /** {@collect.stats} If true, setDividerLocation does nothing. */ boolean ignoreDividerLocationChange; /** {@collect.stats} * Creates a new BasicSplitPaneUI instance */ public static ComponentUI createUI(JComponent x) { return new BasicSplitPaneUI(); } static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.NEGATIVE_INCREMENT)); map.put(new Actions(Actions.POSITIVE_INCREMENT)); map.put(new Actions(Actions.SELECT_MIN)); map.put(new Actions(Actions.SELECT_MAX)); map.put(new Actions(Actions.START_RESIZE)); map.put(new Actions(Actions.TOGGLE_FOCUS)); map.put(new Actions(Actions.FOCUS_OUT_FORWARD)); map.put(new Actions(Actions.FOCUS_OUT_BACKWARD)); } /** {@collect.stats} * Installs the UI. */ public void installUI(JComponent c) { splitPane = (JSplitPane) c; dividerLocationIsSet = false; dividerKeyboardResize = false; keepHidden = false; installDefaults(); installListeners(); installKeyboardActions(); setLastDragLocation(-1); } /** {@collect.stats} * Installs the UI defaults. */ protected void installDefaults(){ LookAndFeel.installBorder(splitPane, "SplitPane.border"); LookAndFeel.installColors(splitPane, "SplitPane.background", "SplitPane.foreground"); LookAndFeel.installProperty(splitPane, "opaque", Boolean.TRUE); if (divider == null) divider = createDefaultDivider(); divider.setBasicSplitPaneUI(this); Border b = divider.getBorder(); if (b == null || !(b instanceof UIResource)) { divider.setBorder(UIManager.getBorder("SplitPaneDivider.border")); } dividerDraggingColor = UIManager.getColor("SplitPaneDivider.draggingColor"); setOrientation(splitPane.getOrientation()); // This plus 2 here is to provide backwards consistancy. Previously, // the old size did not include the 2 pixel border around the divider, // it now does. Integer dividerSize = (Integer)UIManager.get("SplitPane.dividerSize"); if (divider == null) dividerSize = 10; LookAndFeel.installProperty(splitPane, "dividerSize", dividerSize); divider.setDividerSize(splitPane.getDividerSize()); dividerSize = divider.getDividerSize(); splitPane.add(divider, JSplitPane.DIVIDER); setContinuousLayout(splitPane.isContinuousLayout()); resetLayoutManager(); /* Install the nonContinuousLayoutDivider here to avoid having to add/remove everything later. */ if(nonContinuousLayoutDivider == null) { setNonContinuousLayoutDivider( createDefaultNonContinuousLayoutDivider(), true); } else { setNonContinuousLayoutDivider(nonContinuousLayoutDivider, true); } // focus forward traversal key if (managingFocusForwardTraversalKeys==null) { managingFocusForwardTraversalKeys = new HashSet(); managingFocusForwardTraversalKeys.add( KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)); } splitPane.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, managingFocusForwardTraversalKeys); // focus backward traversal key if (managingFocusBackwardTraversalKeys==null) { managingFocusBackwardTraversalKeys = new HashSet(); managingFocusBackwardTraversalKeys.add( KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK)); } splitPane.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, managingFocusBackwardTraversalKeys); } /** {@collect.stats} * Installs the event listeners for the UI. */ protected void installListeners() { if ((propertyChangeListener = createPropertyChangeListener()) != null) { splitPane.addPropertyChangeListener(propertyChangeListener); } if ((focusListener = createFocusListener()) != null) { splitPane.addFocusListener(focusListener); } } /** {@collect.stats} * Installs the keyboard actions for the UI. */ protected void installKeyboardActions() { InputMap km = getInputMap(JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); SwingUtilities.replaceUIInputMap(splitPane, JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, km); LazyActionMap.installLazyActionMap(splitPane, BasicSplitPaneUI.class, "SplitPane.actionMap"); } InputMap getInputMap(int condition) { if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) { return (InputMap)DefaultLookup.get(splitPane, this, "SplitPane.ancestorInputMap"); } return null; } /** {@collect.stats} * Uninstalls the UI. */ public void uninstallUI(JComponent c) { uninstallKeyboardActions(); uninstallListeners(); uninstallDefaults(); dividerLocationIsSet = false; dividerKeyboardResize = false; splitPane = null; } /** {@collect.stats} * Uninstalls the UI defaults. */ protected void uninstallDefaults() { if(splitPane.getLayout() == layoutManager) { splitPane.setLayout(null); } if(nonContinuousLayoutDivider != null) { splitPane.remove(nonContinuousLayoutDivider); } LookAndFeel.uninstallBorder(splitPane); Border b = divider.getBorder(); if (b instanceof UIResource) { divider.setBorder(null); } splitPane.remove(divider); divider.setBasicSplitPaneUI(null); layoutManager = null; divider = null; nonContinuousLayoutDivider = null; setNonContinuousLayoutDivider(null); // sets the focus forward and backward traversal keys to null // to restore the defaults splitPane.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null); splitPane.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null); } /** {@collect.stats} * Uninstalls the event listeners for the UI. */ protected void uninstallListeners() { if (propertyChangeListener != null) { splitPane.removePropertyChangeListener(propertyChangeListener); propertyChangeListener = null; } if (focusListener != null) { splitPane.removeFocusListener(focusListener); focusListener = null; } keyboardUpLeftListener = null; keyboardDownRightListener = null; keyboardHomeListener = null; keyboardEndListener = null; keyboardResizeToggleListener = null; handler = null; } /** {@collect.stats} * Uninstalls the keyboard actions for the UI. */ protected void uninstallKeyboardActions() { SwingUtilities.replaceUIActionMap(splitPane, null); SwingUtilities.replaceUIInputMap(splitPane, JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null); } /** {@collect.stats} * Creates a PropertyChangeListener for the JSplitPane UI. */ protected PropertyChangeListener createPropertyChangeListener() { return getHandler(); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } /** {@collect.stats} * Creates a FocusListener for the JSplitPane UI. */ protected FocusListener createFocusListener() { return getHandler(); } /** {@collect.stats} * As of Java 2 platform v1.3 this method is no * longer used. Subclassers previously using this method should * instead create an Action wrapping the ActionListener, and register * that Action by overriding <code>installKeyboardActions</code> and * placing the Action in the SplitPane's ActionMap. Please refer to * the key bindings specification for further details. * <p> * Creates a ActionListener for the JSplitPane UI that listens for * specific key presses. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected ActionListener createKeyboardUpLeftListener() { return new KeyboardUpLeftHandler(); } /** {@collect.stats} * As of Java 2 platform v1.3 this method is no * longer used. Subclassers previously using this method should * instead create an Action wrapping the ActionListener, and register * that Action by overriding <code>installKeyboardActions</code> and * placing the Action in the SplitPane's ActionMap. Please refer to * the key bindings specification for further details. * <p> * Creates a ActionListener for the JSplitPane UI that listens for * specific key presses. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected ActionListener createKeyboardDownRightListener() { return new KeyboardDownRightHandler(); } /** {@collect.stats} * As of Java 2 platform v1.3 this method is no * longer used. Subclassers previously using this method should * instead create an Action wrapping the ActionListener, and register * that Action by overriding <code>installKeyboardActions</code> and * placing the Action in the SplitPane's ActionMap. Please refer to * the key bindings specification for further details. * <p> * Creates a ActionListener for the JSplitPane UI that listens for * specific key presses. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected ActionListener createKeyboardHomeListener() { return new KeyboardHomeHandler(); } /** {@collect.stats} * As of Java 2 platform v1.3 this method is no * longer used. Subclassers previously using this method should * instead create an Action wrapping the ActionListener, and register * that Action by overriding <code>installKeyboardActions</code> and * placing the Action in the SplitPane's ActionMap. Please refer to * the key bindings specification for further details. * <p> * Creates a ActionListener for the JSplitPane UI that listens for * specific key presses. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected ActionListener createKeyboardEndListener() { return new KeyboardEndHandler(); } /** {@collect.stats} * As of Java 2 platform v1.3 this method is no * longer used. Subclassers previously using this method should * instead create an Action wrapping the ActionListener, and register * that Action by overriding <code>installKeyboardActions</code> and * placing the Action in the SplitPane's ActionMap. Please refer to * the key bindings specification for further details. * <p> * Creates a ActionListener for the JSplitPane UI that listens for * specific key presses. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected ActionListener createKeyboardResizeToggleListener() { return new KeyboardResizeToggleHandler(); } /** {@collect.stats} * Returns the orientation for the JSplitPane. */ public int getOrientation() { return orientation; } /** {@collect.stats} * Set the orientation for the JSplitPane. */ public void setOrientation(int orientation) { this.orientation = orientation; } /** {@collect.stats} * Determines wether the JSplitPane is set to use a continuous layout. */ public boolean isContinuousLayout() { return continuousLayout; } /** {@collect.stats} * Turn continuous layout on/off. */ public void setContinuousLayout(boolean b) { continuousLayout = b; } /** {@collect.stats} * Returns the last drag location of the JSplitPane. */ public int getLastDragLocation() { return lastDragLocation; } /** {@collect.stats} * Set the last drag location of the JSplitPane. */ public void setLastDragLocation(int l) { lastDragLocation = l; } /** {@collect.stats} * @return increment via keyboard methods. */ int getKeyboardMoveIncrement() { return 3; } /** {@collect.stats} * Implementation of the PropertyChangeListener * that the JSplitPane UI uses. * <p> * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicSplitPaneUI. */ public class PropertyHandler implements PropertyChangeListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. /** {@collect.stats} * Messaged from the <code>JSplitPane</code> the receiver is * contained in. May potentially reset the layout manager and cause a * <code>validate</code> to be sent. */ public void propertyChange(PropertyChangeEvent e) { getHandler().propertyChange(e); } } /** {@collect.stats} * Implementation of the FocusListener that the JSplitPane UI uses. * <p> * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicSplitPaneUI. */ public class FocusHandler extends FocusAdapter { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void focusGained(FocusEvent ev) { getHandler().focusGained(ev); } public void focusLost(FocusEvent ev) { getHandler().focusLost(ev); } } /** {@collect.stats} * Implementation of an ActionListener that the JSplitPane UI uses for * handling specific key presses. * <p> * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicSplitPaneUI. */ public class KeyboardUpLeftHandler implements ActionListener { public void actionPerformed(ActionEvent ev) { if (dividerKeyboardResize) { splitPane.setDividerLocation(Math.max(0,getDividerLocation (splitPane) - getKeyboardMoveIncrement())); } } } /** {@collect.stats} * Implementation of an ActionListener that the JSplitPane UI uses for * handling specific key presses. * <p> * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicSplitPaneUI. */ public class KeyboardDownRightHandler implements ActionListener { public void actionPerformed(ActionEvent ev) { if (dividerKeyboardResize) { splitPane.setDividerLocation(getDividerLocation(splitPane) + getKeyboardMoveIncrement()); } } } /** {@collect.stats} * Implementation of an ActionListener that the JSplitPane UI uses for * handling specific key presses. * <p> * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicSplitPaneUI. */ public class KeyboardHomeHandler implements ActionListener { public void actionPerformed(ActionEvent ev) { if (dividerKeyboardResize) { splitPane.setDividerLocation(0); } } } /** {@collect.stats} * Implementation of an ActionListener that the JSplitPane UI uses for * handling specific key presses. * <p> * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicSplitPaneUI. */ public class KeyboardEndHandler implements ActionListener { public void actionPerformed(ActionEvent ev) { if (dividerKeyboardResize) { Insets insets = splitPane.getInsets(); int bottomI = (insets != null) ? insets.bottom : 0; int rightI = (insets != null) ? insets.right : 0; if (orientation == JSplitPane.VERTICAL_SPLIT) { splitPane.setDividerLocation(splitPane.getHeight() - bottomI); } else { splitPane.setDividerLocation(splitPane.getWidth() - rightI); } } } } /** {@collect.stats} * Implementation of an ActionListener that the JSplitPane UI uses for * handling specific key presses. * <p> * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicSplitPaneUI. */ public class KeyboardResizeToggleHandler implements ActionListener { public void actionPerformed(ActionEvent ev) { if (!dividerKeyboardResize) { splitPane.requestFocus(); } } } /** {@collect.stats} * Returns the divider between the top Components. */ public BasicSplitPaneDivider getDivider() { return divider; } /** {@collect.stats} * Returns the default non continuous layout divider, which is an * instanceof Canvas that fills the background in dark gray. */ protected Component createDefaultNonContinuousLayoutDivider() { return new Canvas() { public void paint(Graphics g) { if(!isContinuousLayout() && getLastDragLocation() != -1) { Dimension size = splitPane.getSize(); g.setColor(dividerDraggingColor); if(orientation == JSplitPane.HORIZONTAL_SPLIT) { g.fillRect(0, 0, dividerSize - 1, size.height - 1); } else { g.fillRect(0, 0, size.width - 1, dividerSize - 1); } } } }; } /** {@collect.stats} * Sets the divider to use when the splitPane is configured to * not continuously layout. This divider will only be used during a * dragging session. It is recommended that the passed in component * be a heavy weight. */ protected void setNonContinuousLayoutDivider(Component newDivider) { setNonContinuousLayoutDivider(newDivider, true); } /** {@collect.stats} * Sets the divider to use. */ protected void setNonContinuousLayoutDivider(Component newDivider, boolean rememberSizes) { rememberPaneSizes = rememberSizes; if(nonContinuousLayoutDivider != null && splitPane != null) { splitPane.remove(nonContinuousLayoutDivider); } nonContinuousLayoutDivider = newDivider; } private void addHeavyweightDivider() { if(nonContinuousLayoutDivider != null && splitPane != null) { /* Needs to remove all the components and re-add them! YECK! */ // This is all done so that the nonContinuousLayoutDivider will // be drawn on top of the other components, without this, one // of the heavyweights will draw over the divider! Component leftC = splitPane.getLeftComponent(); Component rightC = splitPane.getRightComponent(); int lastLocation = splitPane. getDividerLocation(); if(leftC != null) splitPane.setLeftComponent(null); if(rightC != null) splitPane.setRightComponent(null); splitPane.remove(divider); splitPane.add(nonContinuousLayoutDivider, BasicSplitPaneUI. NON_CONTINUOUS_DIVIDER, splitPane.getComponentCount()); splitPane.setLeftComponent(leftC); splitPane.setRightComponent(rightC); splitPane.add(divider, JSplitPane.DIVIDER); if(rememberPaneSizes) { splitPane.setDividerLocation(lastLocation); } } } /** {@collect.stats} * Returns the divider to use when the splitPane is configured to * not continuously layout. This divider will only be used during a * dragging session. */ public Component getNonContinuousLayoutDivider() { return nonContinuousLayoutDivider; } /** {@collect.stats} * Returns the splitpane this instance is currently contained * in. */ public JSplitPane getSplitPane() { return splitPane; } /** {@collect.stats} * Creates the default divider. */ public BasicSplitPaneDivider createDefaultDivider() { return new BasicSplitPaneDivider(this); } /** {@collect.stats} * Messaged to reset the preferred sizes. */ public void resetToPreferredSizes(JSplitPane jc) { if(splitPane != null) { layoutManager.resetToPreferredSizes(); splitPane.revalidate(); splitPane.repaint(); } } /** {@collect.stats} * Sets the location of the divider to location. */ public void setDividerLocation(JSplitPane jc, int location) { if (!ignoreDividerLocationChange) { dividerLocationIsSet = true; splitPane.revalidate(); splitPane.repaint(); if (keepHidden) { Insets insets = splitPane.getInsets(); int orientation = splitPane.getOrientation(); if ((orientation == JSplitPane.VERTICAL_SPLIT && location != insets.top && location != splitPane.getHeight()-divider.getHeight()-insets.top) || (orientation == JSplitPane.HORIZONTAL_SPLIT && location != insets.left && location != splitPane.getWidth()-divider.getWidth()-insets.left)) { setKeepHidden(false); } } } else { ignoreDividerLocationChange = false; } } /** {@collect.stats} * Returns the location of the divider, which may differ from what * the splitpane thinks the location of the divider is. */ public int getDividerLocation(JSplitPane jc) { if(orientation == JSplitPane.HORIZONTAL_SPLIT) return divider.getLocation().x; return divider.getLocation().y; } /** {@collect.stats} * Gets the minimum location of the divider. */ public int getMinimumDividerLocation(JSplitPane jc) { int minLoc = 0; Component leftC = splitPane.getLeftComponent(); if ((leftC != null) && (leftC.isVisible())) { Insets insets = splitPane.getInsets(); Dimension minSize = leftC.getMinimumSize(); if(orientation == JSplitPane.HORIZONTAL_SPLIT) { minLoc = minSize.width; } else { minLoc = minSize.height; } if(insets != null) { if(orientation == JSplitPane.HORIZONTAL_SPLIT) { minLoc += insets.left; } else { minLoc += insets.top; } } } return minLoc; } /** {@collect.stats} * Gets the maximum location of the divider. */ public int getMaximumDividerLocation(JSplitPane jc) { Dimension splitPaneSize = splitPane.getSize(); int maxLoc = 0; Component rightC = splitPane.getRightComponent(); if (rightC != null) { Insets insets = splitPane.getInsets(); Dimension minSize = new Dimension(0, 0); if (rightC.isVisible()) { minSize = rightC.getMinimumSize(); } if(orientation == JSplitPane.HORIZONTAL_SPLIT) { maxLoc = splitPaneSize.width - minSize.width; } else { maxLoc = splitPaneSize.height - minSize.height; } maxLoc -= dividerSize; if(insets != null) { if(orientation == JSplitPane.HORIZONTAL_SPLIT) { maxLoc -= insets.right; } else { maxLoc -= insets.top; } } } return Math.max(getMinimumDividerLocation(splitPane), maxLoc); } /** {@collect.stats} * Messaged after the JSplitPane the receiver is providing the look * and feel for paints its children. */ public void finishedPaintingChildren(JSplitPane jc, Graphics g) { if(jc == splitPane && getLastDragLocation() != -1 && !isContinuousLayout() && !draggingHW) { Dimension size = splitPane.getSize(); g.setColor(dividerDraggingColor); if(orientation == JSplitPane.HORIZONTAL_SPLIT) { g.fillRect(getLastDragLocation(), 0, dividerSize - 1, size.height - 1); } else { g.fillRect(0, lastDragLocation, size.width - 1, dividerSize - 1); } } } /** {@collect.stats} * Messaged to paint the look and feel. */ public void paint(Graphics g, JComponent jc) { if (!painted && splitPane.getDividerLocation()<0) { ignoreDividerLocationChange = true; splitPane.setDividerLocation(getDividerLocation(splitPane)); } painted = true; } /** {@collect.stats} * Returns the preferred size for the passed in component, * This is passed off to the current layoutmanager. */ public Dimension getPreferredSize(JComponent jc) { if(splitPane != null) return layoutManager.preferredLayoutSize(splitPane); return new Dimension(0, 0); } /** {@collect.stats} * Returns the minimum size for the passed in component, * This is passed off to the current layoutmanager. */ public Dimension getMinimumSize(JComponent jc) { if(splitPane != null) return layoutManager.minimumLayoutSize(splitPane); return new Dimension(0, 0); } /** {@collect.stats} * Returns the maximum size for the passed in component, * This is passed off to the current layoutmanager. */ public Dimension getMaximumSize(JComponent jc) { if(splitPane != null) return layoutManager.maximumLayoutSize(splitPane); return new Dimension(0, 0); } /** {@collect.stats} * Returns the insets. The insets are returned from the border insets * of the current border. */ public Insets getInsets(JComponent jc) { return null; } /** {@collect.stats} * Resets the layout manager based on orientation and messages it * with invalidateLayout to pull in appropriate Components. */ protected void resetLayoutManager() { if(orientation == JSplitPane.HORIZONTAL_SPLIT) { layoutManager = new BasicHorizontalLayoutManager(0); } else { layoutManager = new BasicHorizontalLayoutManager(1); } splitPane.setLayout(layoutManager); layoutManager.updateComponents(); splitPane.revalidate(); splitPane.repaint(); } /** {@collect.stats} * Set the value to indicate if one of the splitpane sides is expanded. */ void setKeepHidden(boolean keepHidden) { this.keepHidden = keepHidden; } /** {@collect.stats} * The value returned indicates if one of the splitpane sides is expanded. * @return true if one of the splitpane sides is expanded, false otherwise. */ private boolean getKeepHidden() { return keepHidden; } /** {@collect.stats} * Should be messaged before the dragging session starts, resets * lastDragLocation and dividerSize. */ protected void startDragging() { Component leftC = splitPane.getLeftComponent(); Component rightC = splitPane.getRightComponent(); ComponentPeer cPeer; beginDragDividerLocation = getDividerLocation(splitPane); draggingHW = false; if(leftC != null && (cPeer = leftC.getPeer()) != null && !(cPeer instanceof LightweightPeer)) { draggingHW = true; } else if(rightC != null && (cPeer = rightC.getPeer()) != null && !(cPeer instanceof LightweightPeer)) { draggingHW = true; } if(orientation == JSplitPane.HORIZONTAL_SPLIT) { setLastDragLocation(divider.getBounds().x); dividerSize = divider.getSize().width; if(!isContinuousLayout() && draggingHW) { nonContinuousLayoutDivider.setBounds (getLastDragLocation(), 0, dividerSize, splitPane.getHeight()); addHeavyweightDivider(); } } else { setLastDragLocation(divider.getBounds().y); dividerSize = divider.getSize().height; if(!isContinuousLayout() && draggingHW) { nonContinuousLayoutDivider.setBounds (0, getLastDragLocation(), splitPane.getWidth(), dividerSize); addHeavyweightDivider(); } } } /** {@collect.stats} * Messaged during a dragging session to move the divider to the * passed in location. If continuousLayout is true the location is * reset and the splitPane validated. */ protected void dragDividerTo(int location) { if(getLastDragLocation() != location) { if(isContinuousLayout()) { splitPane.setDividerLocation(location); setLastDragLocation(location); } else { int lastLoc = getLastDragLocation(); setLastDragLocation(location); if(orientation == JSplitPane.HORIZONTAL_SPLIT) { if(draggingHW) { nonContinuousLayoutDivider.setLocation( getLastDragLocation(), 0); } else { int splitHeight = splitPane.getHeight(); splitPane.repaint(lastLoc, 0, dividerSize, splitHeight); splitPane.repaint(location, 0, dividerSize, splitHeight); } } else { if(draggingHW) { nonContinuousLayoutDivider.setLocation(0, getLastDragLocation()); } else { int splitWidth = splitPane.getWidth(); splitPane.repaint(0, lastLoc, splitWidth, dividerSize); splitPane.repaint(0, location, splitWidth, dividerSize); } } } } } /** {@collect.stats} * Messaged to finish the dragging session. If not continuous display * the dividers location will be reset. */ protected void finishDraggingTo(int location) { dragDividerTo(location); setLastDragLocation(-1); if(!isContinuousLayout()) { Component leftC = splitPane.getLeftComponent(); Rectangle leftBounds = leftC.getBounds(); if (draggingHW) { if(orientation == JSplitPane.HORIZONTAL_SPLIT) { nonContinuousLayoutDivider.setLocation(-dividerSize, 0); } else { nonContinuousLayoutDivider.setLocation(0, -dividerSize); } splitPane.remove(nonContinuousLayoutDivider); } splitPane.setDividerLocation(location); } } /** {@collect.stats} * As of Java 2 platform v1.3 this method is no longer used. Instead * you should set the border on the divider. * <p> * Returns the width of one side of the divider border. * * @deprecated As of Java 2 platform v1.3, instead set the border on the * divider. */ @Deprecated protected int getDividerBorderSize() { return 1; } /** {@collect.stats} * LayoutManager for JSplitPanes that have an orientation of * HORIZONTAL_SPLIT. */ public class BasicHorizontalLayoutManager implements LayoutManager2 { /* left, right, divider. (in this exact order) */ protected int[] sizes; protected Component[] components; /** {@collect.stats} Size of the splitpane the last time laid out. */ private int lastSplitPaneSize; /** {@collect.stats} True if resetToPreferredSizes has been invoked. */ private boolean doReset; /** {@collect.stats} Axis, 0 for horizontal, or 1 for veritcal. */ private int axis; BasicHorizontalLayoutManager() { this(0); } BasicHorizontalLayoutManager(int axis) { this.axis = axis; components = new Component[3]; components[0] = components[1] = components[2] = null; sizes = new int[3]; } // // LayoutManager // /** {@collect.stats} * Does the actual layout. */ public void layoutContainer(Container container) { Dimension containerSize = container.getSize(); // If the splitpane has a zero size then no op out of here. // If we execute this function now, we're going to cause ourselves // much grief. if (containerSize.height <= 0 || containerSize.width <= 0 ) { lastSplitPaneSize = 0; return; } int spDividerLocation = splitPane.getDividerLocation(); Insets insets = splitPane.getInsets(); int availableSize = getAvailableSize(containerSize, insets); int newSize = getSizeForPrimaryAxis(containerSize); int beginLocation = getDividerLocation(splitPane); int dOffset = getSizeForPrimaryAxis(insets, true); Dimension dSize = (components[2] == null) ? null : components[2].getPreferredSize(); if ((doReset && !dividerLocationIsSet) || spDividerLocation < 0) { resetToPreferredSizes(availableSize); } else if (lastSplitPaneSize <= 0 || availableSize == lastSplitPaneSize || !painted || (dSize != null && getSizeForPrimaryAxis(dSize) != sizes[2])) { if (dSize != null) { sizes[2] = getSizeForPrimaryAxis(dSize); } else { sizes[2] = 0; } setDividerLocation(spDividerLocation - dOffset, availableSize); dividerLocationIsSet = false; } else if (availableSize != lastSplitPaneSize) { distributeSpace(availableSize - lastSplitPaneSize, getKeepHidden()); } doReset = false; dividerLocationIsSet = false; lastSplitPaneSize = availableSize; // Reset the bounds of each component int nextLocation = getInitialLocation(insets); int counter = 0; while (counter < 3) { if (components[counter] != null && components[counter].isVisible()) { setComponentToSize(components[counter], sizes[counter], nextLocation, insets, containerSize); nextLocation += sizes[counter]; } switch (counter) { case 0: counter = 2; break; case 2: counter = 1; break; case 1: counter = 3; break; } } if (painted) { // This is tricky, there is never a good time for us // to push the value to the splitpane, painted appears to // the best time to do it. What is really needed is // notification that layout has completed. int newLocation = getDividerLocation(splitPane); if (newLocation != (spDividerLocation - dOffset)) { int lastLocation = splitPane.getLastDividerLocation(); ignoreDividerLocationChange = true; try { splitPane.setDividerLocation(newLocation); // This is not always needed, but is rather tricky // to determine when... The case this is needed for // is if the user sets the divider location to some // bogus value, say 0, and the actual value is 1, the // call to setDividerLocation(1) will preserve the // old value of 0, when we really want the divider // location value before the call. This is needed for // the one touch buttons. splitPane.setLastDividerLocation(lastLocation); } finally { ignoreDividerLocationChange = false; } } } } /** {@collect.stats} * Adds the component at place. Place must be one of * JSplitPane.LEFT, RIGHT, TOP, BOTTOM, or null (for the * divider). */ public void addLayoutComponent(String place, Component component) { boolean isValid = true; if(place != null) { if(place.equals(JSplitPane.DIVIDER)) { /* Divider. */ components[2] = component; sizes[2] = getSizeForPrimaryAxis(component. getPreferredSize()); } else if(place.equals(JSplitPane.LEFT) || place.equals(JSplitPane.TOP)) { components[0] = component; sizes[0] = 0; } else if(place.equals(JSplitPane.RIGHT) || place.equals(JSplitPane.BOTTOM)) { components[1] = component; sizes[1] = 0; } else if(!place.equals( BasicSplitPaneUI.NON_CONTINUOUS_DIVIDER)) isValid = false; } else { isValid = false; } if(!isValid) throw new IllegalArgumentException("cannot add to layout: " + "unknown constraint: " + place); doReset = true; } /** {@collect.stats} * Returns the minimum size needed to contain the children. * The width is the sum of all the childrens min widths and * the height is the largest of the childrens minimum heights. */ public Dimension minimumLayoutSize(Container container) { int minPrimary = 0; int minSecondary = 0; Insets insets = splitPane.getInsets(); for (int counter=0; counter<3; counter++) { if(components[counter] != null) { Dimension minSize = components[counter].getMinimumSize(); int secSize = getSizeForSecondaryAxis(minSize); minPrimary += getSizeForPrimaryAxis(minSize); if(secSize > minSecondary) minSecondary = secSize; } } if(insets != null) { minPrimary += getSizeForPrimaryAxis(insets, true) + getSizeForPrimaryAxis(insets, false); minSecondary += getSizeForSecondaryAxis(insets, true) + getSizeForSecondaryAxis(insets, false); } if (axis == 0) { return new Dimension(minPrimary, minSecondary); } return new Dimension(minSecondary, minPrimary); } /** {@collect.stats} * Returns the preferred size needed to contain the children. * The width is the sum of all the childrens preferred widths and * the height is the largest of the childrens preferred heights. */ public Dimension preferredLayoutSize(Container container) { int prePrimary = 0; int preSecondary = 0; Insets insets = splitPane.getInsets(); for(int counter = 0; counter < 3; counter++) { if(components[counter] != null) { Dimension preSize = components[counter]. getPreferredSize(); int secSize = getSizeForSecondaryAxis(preSize); prePrimary += getSizeForPrimaryAxis(preSize); if(secSize > preSecondary) preSecondary = secSize; } } if(insets != null) { prePrimary += getSizeForPrimaryAxis(insets, true) + getSizeForPrimaryAxis(insets, false); preSecondary += getSizeForSecondaryAxis(insets, true) + getSizeForSecondaryAxis(insets, false); } if (axis == 0) { return new Dimension(prePrimary, preSecondary); } return new Dimension(preSecondary, prePrimary); } /** {@collect.stats} * Removes the specified component from our knowledge. */ public void removeLayoutComponent(Component component) { for(int counter = 0; counter < 3; counter++) { if(components[counter] == component) { components[counter] = null; sizes[counter] = 0; doReset = true; } } } // // LayoutManager2 // /** {@collect.stats} * Adds the specified component to the layout, using the specified * constraint object. * @param comp the component to be added * @param constraints where/how the component is added to the layout. */ public void addLayoutComponent(Component comp, Object constraints) { if ((constraints == null) || (constraints instanceof String)) { addLayoutComponent((String)constraints, comp); } else { throw new IllegalArgumentException("cannot add to layout: " + "constraint must be a " + "string (or null)"); } } /** {@collect.stats} * Returns the alignment along the x axis. This specifies how * the component would like to be aligned relative to other * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. */ public float getLayoutAlignmentX(Container target) { return 0.0f; } /** {@collect.stats} * Returns the alignment along the y axis. This specifies how * the component would like to be aligned relative to other * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. */ public float getLayoutAlignmentY(Container target) { return 0.0f; } /** {@collect.stats} * Does nothing. If the developer really wants to change the * size of one of the views JSplitPane.resetToPreferredSizes should * be messaged. */ public void invalidateLayout(Container c) { } /** {@collect.stats} * Returns the maximum layout size, which is Integer.MAX_VALUE * in both directions. */ public Dimension maximumLayoutSize(Container target) { return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } // // New methods. // /** {@collect.stats} * Marks the receiver so that the next time this instance is * laid out it'll ask for the preferred sizes. */ public void resetToPreferredSizes() { doReset = true; } /** {@collect.stats} * Resets the size of the Component at the passed in location. */ protected void resetSizeAt(int index) { sizes[index] = 0; doReset = true; } /** {@collect.stats} * Sets the sizes to <code>newSizes</code>. */ protected void setSizes(int[] newSizes) { System.arraycopy(newSizes, 0, sizes, 0, 3); } /** {@collect.stats} * Returns the sizes of the components. */ protected int[] getSizes() { int[] retSizes = new int[3]; System.arraycopy(sizes, 0, retSizes, 0, 3); return retSizes; } /** {@collect.stats} * Returns the width of the passed in Components preferred size. */ protected int getPreferredSizeOfComponent(Component c) { return getSizeForPrimaryAxis(c.getPreferredSize()); } /** {@collect.stats} * Returns the width of the passed in Components minimum size. */ int getMinimumSizeOfComponent(Component c) { return getSizeForPrimaryAxis(c.getMinimumSize()); } /** {@collect.stats} * Returns the width of the passed in component. */ protected int getSizeOfComponent(Component c) { return getSizeForPrimaryAxis(c.getSize()); } /** {@collect.stats} * Returns the available width based on the container size and * Insets. */ protected int getAvailableSize(Dimension containerSize, Insets insets) { if(insets == null) return getSizeForPrimaryAxis(containerSize); return (getSizeForPrimaryAxis(containerSize) - (getSizeForPrimaryAxis(insets, true) + getSizeForPrimaryAxis(insets, false))); } /** {@collect.stats} * Returns the left inset, unless the Insets are null in which case * 0 is returned. */ protected int getInitialLocation(Insets insets) { if(insets != null) return getSizeForPrimaryAxis(insets, true); return 0; } /** {@collect.stats} * Sets the width of the component c to be size, placing its * x location at location, y to the insets.top and height * to the containersize.height less the top and bottom insets. */ protected void setComponentToSize(Component c, int size, int location, Insets insets, Dimension containerSize) { if(insets != null) { if (axis == 0) { c.setBounds(location, insets.top, size, containerSize.height - (insets.top + insets.bottom)); } else { c.setBounds(insets.left, location, containerSize.width - (insets.left + insets.right), size); } } else { if (axis == 0) { c.setBounds(location, 0, size, containerSize.height); } else { c.setBounds(0, location, containerSize.width, size); } } } /** {@collect.stats} * If the axis == 0, the width is returned, otherwise the height. */ int getSizeForPrimaryAxis(Dimension size) { if (axis == 0) { return size.width; } return size.height; } /** {@collect.stats} * If the axis == 0, the width is returned, otherwise the height. */ int getSizeForSecondaryAxis(Dimension size) { if (axis == 0) { return size.height; } return size.width; } /** {@collect.stats} * Returns a particular value of the inset identified by the * axis and <code>isTop</code><p> * axis isTop * 0 true - left * 0 false - right * 1 true - top * 1 false - bottom */ int getSizeForPrimaryAxis(Insets insets, boolean isTop) { if (axis == 0) { if (isTop) { return insets.left; } return insets.right; } if (isTop) { return insets.top; } return insets.bottom; } /** {@collect.stats} * Returns a particular value of the inset identified by the * axis and <code>isTop</code><p> * axis isTop * 0 true - left * 0 false - right * 1 true - top * 1 false - bottom */ int getSizeForSecondaryAxis(Insets insets, boolean isTop) { if (axis == 0) { if (isTop) { return insets.top; } return insets.bottom; } if (isTop) { return insets.left; } return insets.right; } /** {@collect.stats} * Determines the components. This should be called whenever * a new instance of this is installed into an existing * SplitPane. */ protected void updateComponents() { Component comp; comp = splitPane.getLeftComponent(); if(components[0] != comp) { components[0] = comp; if(comp == null) { sizes[0] = 0; } else { sizes[0] = -1; } } comp = splitPane.getRightComponent(); if(components[1] != comp) { components[1] = comp; if(comp == null) { sizes[1] = 0; } else { sizes[1] = -1; } } /* Find the divider. */ Component[] children = splitPane.getComponents(); Component oldDivider = components[2]; components[2] = null; for(int counter = children.length - 1; counter >= 0; counter--) { if(children[counter] != components[0] && children[counter] != components[1] && children[counter] != nonContinuousLayoutDivider) { if(oldDivider != children[counter]) { components[2] = children[counter]; } else { components[2] = oldDivider; } break; } } if(components[2] == null) { sizes[2] = 0; } else { sizes[2] = getSizeForPrimaryAxis(components[2].getPreferredSize()); } } /** {@collect.stats} * Resets the size of the first component to <code>leftSize</code>, * and the right component to the remainder of the space. */ void setDividerLocation(int leftSize, int availableSize) { boolean lValid = (components[0] != null && components[0].isVisible()); boolean rValid = (components[1] != null && components[1].isVisible()); boolean dValid = (components[2] != null && components[2].isVisible()); int max = availableSize; if (dValid) { max -= sizes[2]; } leftSize = Math.max(0, Math.min(leftSize, max)); if (lValid) { if (rValid) { sizes[0] = leftSize; sizes[1] = max - leftSize; } else { sizes[0] = max; sizes[1] = 0; } } else if (rValid) { sizes[1] = max; sizes[0] = 0; } } /** {@collect.stats} * Returns an array of the minimum sizes of the components. */ int[] getPreferredSizes() { int[] retValue = new int[3]; for (int counter = 0; counter < 3; counter++) { if (components[counter] != null && components[counter].isVisible()) { retValue[counter] = getPreferredSizeOfComponent (components[counter]); } else { retValue[counter] = -1; } } return retValue; } /** {@collect.stats} * Returns an array of the minimum sizes of the components. */ int[] getMinimumSizes() { int[] retValue = new int[3]; for (int counter = 0; counter < 2; counter++) { if (components[counter] != null && components[counter].isVisible()) { retValue[counter] = getMinimumSizeOfComponent (components[counter]); } else { retValue[counter] = -1; } } retValue[2] = (components[2] != null) ? getMinimumSizeOfComponent(components[2]) : -1; return retValue; } /** {@collect.stats} * Resets the components to their preferred sizes. */ void resetToPreferredSizes(int availableSize) { // Set the sizes to the preferred sizes (if fits), otherwise // set to min sizes and distribute any extra space. int[] testSizes = getPreferredSizes(); int totalSize = 0; for (int counter = 0; counter < 3; counter++) { if (testSizes[counter] != -1) { totalSize += testSizes[counter]; } } if (totalSize > availableSize) { testSizes = getMinimumSizes(); totalSize = 0; for (int counter = 0; counter < 3; counter++) { if (testSizes[counter] != -1) { totalSize += testSizes[counter]; } } } setSizes(testSizes); distributeSpace(availableSize - totalSize, false); } /** {@collect.stats} * Distributes <code>space</code> between the two components * (divider won't get any extra space) based on the weighting. This * attempts to honor the min size of the components. * * @param keepHidden if true and one of the components is 0x0 * it gets none of the extra space */ void distributeSpace(int space, boolean keepHidden) { boolean lValid = (components[0] != null && components[0].isVisible()); boolean rValid = (components[1] != null && components[1].isVisible()); if (keepHidden) { if (lValid && getSizeForPrimaryAxis( components[0].getSize()) == 0) { lValid = false; if (rValid && getSizeForPrimaryAxis( components[1].getSize()) == 0) { // Both aren't valid, force them both to be valid lValid = true; } } else if (rValid && getSizeForPrimaryAxis( components[1].getSize()) == 0) { rValid = false; } } if (lValid && rValid) { double weight = splitPane.getResizeWeight(); int lExtra = (int)(weight * (double)space); int rExtra = (space - lExtra); sizes[0] += lExtra; sizes[1] += rExtra; int lMin = getMinimumSizeOfComponent(components[0]); int rMin = getMinimumSizeOfComponent(components[1]); boolean lMinValid = (sizes[0] >= lMin); boolean rMinValid = (sizes[1] >= rMin); if (!lMinValid && !rMinValid) { if (sizes[0] < 0) { sizes[1] += sizes[0]; sizes[0] = 0; } else if (sizes[1] < 0) { sizes[0] += sizes[1]; sizes[1] = 0; } } else if (!lMinValid) { if (sizes[1] - (lMin - sizes[0]) < rMin) { // both below min, just make sure > 0 if (sizes[0] < 0) { sizes[1] += sizes[0]; sizes[0] = 0; } } else { sizes[1] -= (lMin - sizes[0]); sizes[0] = lMin; } } else if (!rMinValid) { if (sizes[0] - (rMin - sizes[1]) < lMin) { // both below min, just make sure > 0 if (sizes[1] < 0) { sizes[0] += sizes[1]; sizes[1] = 0; } } else { sizes[0] -= (rMin - sizes[1]); sizes[1] = rMin; } } if (sizes[0] < 0) { sizes[0] = 0; } if (sizes[1] < 0) { sizes[1] = 0; } } else if (lValid) { sizes[0] = Math.max(0, sizes[0] + space); } else if (rValid) { sizes[1] = Math.max(0, sizes[1] + space); } } } /** {@collect.stats} * LayoutManager used for JSplitPanes with an orientation of * VERTICAL_SPLIT. * <p> */ public class BasicVerticalLayoutManager extends BasicHorizontalLayoutManager { public BasicVerticalLayoutManager() { super(1); } } private class Handler implements FocusListener, PropertyChangeListener { // // PropertyChangeListener // /** {@collect.stats} * Messaged from the <code>JSplitPane</code> the receiver is * contained in. May potentially reset the layout manager and cause a * <code>validate</code> to be sent. */ public void propertyChange(PropertyChangeEvent e) { if(e.getSource() == splitPane) { String changeName = e.getPropertyName(); if(changeName == JSplitPane.ORIENTATION_PROPERTY) { orientation = splitPane.getOrientation(); resetLayoutManager(); } else if(changeName == JSplitPane.CONTINUOUS_LAYOUT_PROPERTY){ setContinuousLayout(splitPane.isContinuousLayout()); if(!isContinuousLayout()) { if(nonContinuousLayoutDivider == null) { setNonContinuousLayoutDivider( createDefaultNonContinuousLayoutDivider(), true); } else if(nonContinuousLayoutDivider.getParent() == null) { setNonContinuousLayoutDivider( nonContinuousLayoutDivider, true); } } } else if(changeName == JSplitPane.DIVIDER_SIZE_PROPERTY){ divider.setDividerSize(splitPane.getDividerSize()); dividerSize = divider.getDividerSize(); splitPane.revalidate(); splitPane.repaint(); } } } // // FocusListener // public void focusGained(FocusEvent ev) { dividerKeyboardResize = true; splitPane.repaint(); } public void focusLost(FocusEvent ev) { dividerKeyboardResize = false; splitPane.repaint(); } } private static class Actions extends UIAction { private static final String NEGATIVE_INCREMENT = "negativeIncrement"; private static final String POSITIVE_INCREMENT = "positiveIncrement"; private static final String SELECT_MIN = "selectMin"; private static final String SELECT_MAX = "selectMax"; private static final String START_RESIZE = "startResize"; private static final String TOGGLE_FOCUS = "toggleFocus"; private static final String FOCUS_OUT_FORWARD = "focusOutForward"; private static final String FOCUS_OUT_BACKWARD = "focusOutBackward"; Actions(String key) { super(key); } public void actionPerformed(ActionEvent ev) { JSplitPane splitPane = (JSplitPane)ev.getSource(); BasicSplitPaneUI ui = (BasicSplitPaneUI)BasicLookAndFeel. getUIOfType(splitPane.getUI(), BasicSplitPaneUI.class); if (ui == null) { return; } String key = getName(); if (key == NEGATIVE_INCREMENT) { if (ui.dividerKeyboardResize) { splitPane.setDividerLocation(Math.max( 0, ui.getDividerLocation (splitPane) - ui.getKeyboardMoveIncrement())); } } else if (key == POSITIVE_INCREMENT) { if (ui.dividerKeyboardResize) { splitPane.setDividerLocation( ui.getDividerLocation(splitPane) + ui.getKeyboardMoveIncrement()); } } else if (key == SELECT_MIN) { if (ui.dividerKeyboardResize) { splitPane.setDividerLocation(0); } } else if (key == SELECT_MAX) { if (ui.dividerKeyboardResize) { Insets insets = splitPane.getInsets(); int bottomI = (insets != null) ? insets.bottom : 0; int rightI = (insets != null) ? insets.right : 0; if (ui.orientation == JSplitPane.VERTICAL_SPLIT) { splitPane.setDividerLocation(splitPane.getHeight() - bottomI); } else { splitPane.setDividerLocation(splitPane.getWidth() - rightI); } } } else if (key == START_RESIZE) { if (!ui.dividerKeyboardResize) { splitPane.requestFocus(); } else { JSplitPane parentSplitPane = (JSplitPane)SwingUtilities.getAncestorOfClass( JSplitPane.class, splitPane); if (parentSplitPane!=null) { parentSplitPane.requestFocus(); } } } else if (key == TOGGLE_FOCUS) { toggleFocus(splitPane); } else if (key == FOCUS_OUT_FORWARD) { moveFocus(splitPane, 1); } else if (key == FOCUS_OUT_BACKWARD) { moveFocus(splitPane, -1); } } private void moveFocus(JSplitPane splitPane, int direction) { Container rootAncestor = splitPane.getFocusCycleRootAncestor(); FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy(); Component focusOn = (direction > 0) ? policy.getComponentAfter(rootAncestor, splitPane) : policy.getComponentBefore(rootAncestor, splitPane); HashSet focusFrom = new HashSet(); if (splitPane.isAncestorOf(focusOn)) { do { focusFrom.add(focusOn); rootAncestor = focusOn.getFocusCycleRootAncestor(); policy = rootAncestor.getFocusTraversalPolicy(); focusOn = (direction > 0) ? policy.getComponentAfter(rootAncestor, focusOn) : policy.getComponentBefore(rootAncestor, focusOn); } while (splitPane.isAncestorOf(focusOn) && !focusFrom.contains(focusOn)); } if ( focusOn!=null && !splitPane.isAncestorOf(focusOn) ) { focusOn.requestFocus(); } } private void toggleFocus(JSplitPane splitPane) { Component left = splitPane.getLeftComponent(); Component right = splitPane.getRightComponent(); KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); Component focus = manager.getFocusOwner(); Component focusOn = getNextSide(splitPane, focus); if (focusOn != null) { // don't change the focus if the new focused component belongs // to the same splitpane and the same side if ( focus!=null && ( (SwingUtilities.isDescendingFrom(focus, left) && SwingUtilities.isDescendingFrom(focusOn, left)) || (SwingUtilities.isDescendingFrom(focus, right) && SwingUtilities.isDescendingFrom(focusOn, right)) ) ) { return; } SwingUtilities2.compositeRequestFocus(focusOn); } } private Component getNextSide(JSplitPane splitPane, Component focus) { Component left = splitPane.getLeftComponent(); Component right = splitPane.getRightComponent(); Component next = null; if (focus!=null && SwingUtilities.isDescendingFrom(focus, left) && right!=null) { next = getFirstAvailableComponent(right); if (next != null) { return next; } } JSplitPane parentSplitPane = (JSplitPane)SwingUtilities.getAncestorOfClass(JSplitPane.class, splitPane); if (parentSplitPane!=null) { // focus next side of the parent split pane next = getNextSide(parentSplitPane, focus); } else { next = getFirstAvailableComponent(left); if (next == null) { next = getFirstAvailableComponent(right); } } return next; } private Component getFirstAvailableComponent(Component c) { if (c!=null && c instanceof JSplitPane) { JSplitPane sp = (JSplitPane)c; Component left = getFirstAvailableComponent(sp.getLeftComponent()); if (left != null) { c = left; } else { c = getFirstAvailableComponent(sp.getRightComponent()); } } return c; } } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import java.awt.event.*; import java.awt.peer.LightweightPeer; import javax.swing.*; import javax.swing.border.*; import javax.swing.plaf.*; import javax.swing.event.*; import java.beans.*; import java.io.Serializable; import sun.swing.DefaultLookup; import sun.swing.UIAction; /** {@collect.stats} * A basic L&F implementation of JInternalFrame. * * @author David Kloba * @author Rich Schiavi */ public class BasicInternalFrameUI extends InternalFrameUI { protected JInternalFrame frame; private Handler handler; protected MouseInputAdapter borderListener; protected PropertyChangeListener propertyChangeListener; protected LayoutManager internalFrameLayout; protected ComponentListener componentListener; protected MouseInputListener glassPaneDispatcher; private InternalFrameListener internalFrameListener; protected JComponent northPane; protected JComponent southPane; protected JComponent westPane; protected JComponent eastPane; protected BasicInternalFrameTitlePane titlePane; // access needs this private static DesktopManager sharedDesktopManager; private boolean componentListenerAdded = false; private Rectangle parentBounds; private boolean dragging = false; private boolean resizing = false; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected KeyStroke openMenuKey; private boolean keyBindingRegistered = false; private boolean keyBindingActive = false; ///////////////////////////////////////////////////////////////////////////// // ComponentUI Interface Implementation methods ///////////////////////////////////////////////////////////////////////////// public static ComponentUI createUI(JComponent b) { return new BasicInternalFrameUI((JInternalFrame)b); } public BasicInternalFrameUI(JInternalFrame b) { LookAndFeel laf = UIManager.getLookAndFeel(); if (laf instanceof BasicLookAndFeel) { ((BasicLookAndFeel)laf).installAWTEventListener(); } } public void installUI(JComponent c) { frame = (JInternalFrame)c; installDefaults(); installListeners(); installComponents(); installKeyboardActions(); LookAndFeel.installProperty(frame, "opaque", Boolean.TRUE); } public void uninstallUI(JComponent c) { if(c != frame) throw new IllegalComponentStateException( this + " was asked to deinstall() " + c + " when it only knows about " + frame + "."); uninstallKeyboardActions(); uninstallComponents(); uninstallListeners(); uninstallDefaults(); updateFrameCursor(); handler = null; frame = null; } protected void installDefaults(){ Icon frameIcon = frame.getFrameIcon(); if (frameIcon == null || frameIcon instanceof UIResource) { frame.setFrameIcon(UIManager.getIcon("InternalFrame.icon")); } // Enable the content pane to inherit background color from its // parent by setting its background color to null. Container contentPane = frame.getContentPane(); if (contentPane != null) { Color bg = contentPane.getBackground(); if (bg instanceof UIResource) contentPane.setBackground(null); } frame.setLayout(internalFrameLayout = createLayoutManager()); frame.setBackground(UIManager.getLookAndFeelDefaults().getColor("control")); LookAndFeel.installBorder(frame, "InternalFrame.border"); } protected void installKeyboardActions(){ createInternalFrameListener(); if (internalFrameListener != null) { frame.addInternalFrameListener(internalFrameListener); } LazyActionMap.installLazyActionMap(frame, BasicInternalFrameUI.class, "InternalFrame.actionMap"); } static void loadActionMap(LazyActionMap map) { map.put(new UIAction("showSystemMenu") { public void actionPerformed(ActionEvent evt) { JInternalFrame iFrame = (JInternalFrame)evt.getSource(); if (iFrame.getUI() instanceof BasicInternalFrameUI) { JComponent comp = ((BasicInternalFrameUI) iFrame.getUI()).getNorthPane(); if (comp instanceof BasicInternalFrameTitlePane) { ((BasicInternalFrameTitlePane)comp). showSystemMenu(); } } } public boolean isEnabled(Object sender){ if (sender instanceof JInternalFrame) { JInternalFrame iFrame = (JInternalFrame)sender; if (iFrame.getUI() instanceof BasicInternalFrameUI) { return ((BasicInternalFrameUI)iFrame.getUI()). isKeyBindingActive(); } } return false; } }); // Set the ActionMap's parent to the Auditory Feedback Action Map BasicLookAndFeel.installAudioActionMap(map); } protected void installComponents(){ setNorthPane(createNorthPane(frame)); setSouthPane(createSouthPane(frame)); setEastPane(createEastPane(frame)); setWestPane(createWestPane(frame)); } /** {@collect.stats} * @since 1.3 */ protected void installListeners() { borderListener = createBorderListener(frame); propertyChangeListener = createPropertyChangeListener(); frame.addPropertyChangeListener(propertyChangeListener); installMouseHandlers(frame); glassPaneDispatcher = createGlassPaneDispatcher(); if (glassPaneDispatcher != null) { frame.getGlassPane().addMouseListener(glassPaneDispatcher); frame.getGlassPane().addMouseMotionListener(glassPaneDispatcher); } componentListener = createComponentListener(); if (frame.getParent() != null) { parentBounds = frame.getParent().getBounds(); } if ((frame.getParent() != null) && !componentListenerAdded) { frame.getParent().addComponentListener(componentListener); componentListenerAdded = true; } } // Provide a FocusListener to listen for a WINDOW_LOST_FOCUS event, // so that a resize can be cancelled if the focus is lost while resizing // when an Alt-Tab, modal dialog popup, iconify, dispose, or remove // of the internal frame occurs. private WindowFocusListener getWindowFocusListener(){ return getHandler(); } // Cancel a resize in progress by calling finishMouseReleased(). private void cancelResize() { if (resizing) { if (borderListener instanceof BorderListener) { ((BorderListener)borderListener).finishMouseReleased(); } } } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } InputMap getInputMap(int condition) { if (condition == JComponent.WHEN_IN_FOCUSED_WINDOW) { return createInputMap(condition); } return null; } InputMap createInputMap(int condition) { if (condition == JComponent.WHEN_IN_FOCUSED_WINDOW) { Object[] bindings = (Object[])DefaultLookup.get( frame, this, "InternalFrame.windowBindings"); if (bindings != null) { return LookAndFeel.makeComponentInputMap(frame, bindings); } } return null; } protected void uninstallDefaults() { Icon frameIcon = frame.getFrameIcon(); if (frameIcon instanceof UIResource) { frame.setFrameIcon(null); } internalFrameLayout = null; frame.setLayout(null); LookAndFeel.uninstallBorder(frame); } protected void uninstallComponents(){ setNorthPane(null); setSouthPane(null); setEastPane(null); setWestPane(null); if(titlePane != null) { titlePane.uninstallDefaults(); } titlePane = null; } /** {@collect.stats} * @since 1.3 */ protected void uninstallListeners() { if ((frame.getParent() != null) && componentListenerAdded) { frame.getParent().removeComponentListener(componentListener); componentListenerAdded = false; } componentListener = null; if (glassPaneDispatcher != null) { frame.getGlassPane().removeMouseListener(glassPaneDispatcher); frame.getGlassPane().removeMouseMotionListener(glassPaneDispatcher); glassPaneDispatcher = null; } deinstallMouseHandlers(frame); frame.removePropertyChangeListener(propertyChangeListener); propertyChangeListener = null; borderListener = null; } protected void uninstallKeyboardActions(){ if (internalFrameListener != null) { frame.removeInternalFrameListener(internalFrameListener); } internalFrameListener = null; SwingUtilities.replaceUIInputMap(frame, JComponent. WHEN_IN_FOCUSED_WINDOW, null); SwingUtilities.replaceUIActionMap(frame, null); } void updateFrameCursor() { if (resizing) { return; } Cursor s = (Cursor)frame.getLastCursor(); if (s == null) { s = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); } frame.setCursor(s); } protected LayoutManager createLayoutManager(){ return getHandler(); } protected PropertyChangeListener createPropertyChangeListener(){ return getHandler(); } public Dimension getPreferredSize(JComponent x) { if((JComponent)frame == x) return frame.getLayout().preferredLayoutSize(x); return new Dimension(100, 100); } public Dimension getMinimumSize(JComponent x) { if((JComponent)frame == x) { return frame.getLayout().minimumLayoutSize(x); } return new Dimension(0, 0); } public Dimension getMaximumSize(JComponent x) { return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } /** {@collect.stats} * Installs necessary mouse handlers on <code>newPane</code> * and adds it to the frame. * Reverse process for the <code>currentPane</code>. */ protected void replacePane(JComponent currentPane, JComponent newPane) { if(currentPane != null) { deinstallMouseHandlers(currentPane); frame.remove(currentPane); } if(newPane != null) { frame.add(newPane); installMouseHandlers(newPane); } } protected void deinstallMouseHandlers(JComponent c) { c.removeMouseListener(borderListener); c.removeMouseMotionListener(borderListener); } protected void installMouseHandlers(JComponent c) { c.addMouseListener(borderListener); c.addMouseMotionListener(borderListener); } protected JComponent createNorthPane(JInternalFrame w) { titlePane = new BasicInternalFrameTitlePane(w); return titlePane; } protected JComponent createSouthPane(JInternalFrame w) { return null; } protected JComponent createWestPane(JInternalFrame w) { return null; } protected JComponent createEastPane(JInternalFrame w) { return null; } protected MouseInputAdapter createBorderListener(JInternalFrame w) { return new BorderListener(); } protected void createInternalFrameListener(){ internalFrameListener = getHandler(); } protected final boolean isKeyBindingRegistered(){ return keyBindingRegistered; } protected final void setKeyBindingRegistered(boolean b){ keyBindingRegistered = b; } public final boolean isKeyBindingActive(){ return keyBindingActive; } protected final void setKeyBindingActive(boolean b){ keyBindingActive = b; } protected void setupMenuOpenKey(){ // PENDING(hania): Why are these WHEN_IN_FOCUSED_WINDOWs? Shouldn't // they be WHEN_ANCESTOR_OF_FOCUSED_COMPONENT? // Also, no longer registering on the desktopicon, the previous // action did nothing. InputMap map = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); SwingUtilities.replaceUIInputMap(frame, JComponent.WHEN_IN_FOCUSED_WINDOW, map); //ActionMap actionMap = getActionMap(); //SwingUtilities.replaceUIActionMap(frame, actionMap); } protected void setupMenuCloseKey(){ } public JComponent getNorthPane() { return northPane; } public void setNorthPane(JComponent c) { if (northPane != null && northPane instanceof BasicInternalFrameTitlePane) { ((BasicInternalFrameTitlePane)northPane).uninstallListeners(); } replacePane(northPane, c); northPane = c; if (c instanceof BasicInternalFrameTitlePane) { titlePane = (BasicInternalFrameTitlePane)c; } } public JComponent getSouthPane() { return southPane; } public void setSouthPane(JComponent c) { southPane = c; } public JComponent getWestPane() { return westPane; } public void setWestPane(JComponent c) { westPane = c; } public JComponent getEastPane() { return eastPane; } public void setEastPane(JComponent c) { eastPane = c; } public class InternalFramePropertyChangeListener implements PropertyChangeListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. /** {@collect.stats} * Detects changes in state from the JInternalFrame and handles * actions. */ public void propertyChange(PropertyChangeEvent evt) { getHandler().propertyChange(evt); } } public class InternalFrameLayout implements LayoutManager { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void addLayoutComponent(String name, Component c) { getHandler().addLayoutComponent(name, c); } public void removeLayoutComponent(Component c) { getHandler().removeLayoutComponent(c); } public Dimension preferredLayoutSize(Container c) { return getHandler().preferredLayoutSize(c); } public Dimension minimumLayoutSize(Container c) { return getHandler().minimumLayoutSize(c); } public void layoutContainer(Container c) { getHandler().layoutContainer(c); } } /// DesktopManager methods /** {@collect.stats} Returns the proper DesktopManager. Calls getDesktopPane() to * find the JDesktop component and returns the desktopManager from * it. If this fails, it will return a default DesktopManager that * should work in arbitrary parents. */ protected DesktopManager getDesktopManager() { if(frame.getDesktopPane() != null && frame.getDesktopPane().getDesktopManager() != null) return frame.getDesktopPane().getDesktopManager(); if(sharedDesktopManager == null) sharedDesktopManager = createDesktopManager(); return sharedDesktopManager; } protected DesktopManager createDesktopManager(){ return new DefaultDesktopManager(); } /** {@collect.stats} * This method is called when the user wants to close the frame. * The <code>playCloseSound</code> Action is fired. * This action is delegated to the desktopManager. */ protected void closeFrame(JInternalFrame f) { // Internal Frame Auditory Cue Activation BasicLookAndFeel.playSound(frame,"InternalFrame.closeSound"); // delegate to desktop manager getDesktopManager().closeFrame(f); } /** {@collect.stats} * This method is called when the user wants to maximize the frame. * The <code>playMaximizeSound</code> Action is fired. * This action is delegated to the desktopManager. */ protected void maximizeFrame(JInternalFrame f) { // Internal Frame Auditory Cue Activation BasicLookAndFeel.playSound(frame,"InternalFrame.maximizeSound"); // delegate to desktop manager getDesktopManager().maximizeFrame(f); } /** {@collect.stats} * This method is called when the user wants to minimize the frame. * The <code>playRestoreDownSound</code> Action is fired. * This action is delegated to the desktopManager. */ protected void minimizeFrame(JInternalFrame f) { // Internal Frame Auditory Cue Activation if ( ! f.isIcon() ) { // This method seems to regularly get called after an // internal frame is iconified. Don't play this sound then. BasicLookAndFeel.playSound(frame,"InternalFrame.restoreDownSound"); } // delegate to desktop manager getDesktopManager().minimizeFrame(f); } /** {@collect.stats} * This method is called when the user wants to iconify the frame. * The <code>playMinimizeSound</code> Action is fired. * This action is delegated to the desktopManager. */ protected void iconifyFrame(JInternalFrame f) { // Internal Frame Auditory Cue Activation BasicLookAndFeel.playSound(frame, "InternalFrame.minimizeSound"); // delegate to desktop manager getDesktopManager().iconifyFrame(f); } /** {@collect.stats} * This method is called when the user wants to deiconify the frame. * The <code>playRestoreUpSound</code> Action is fired. * This action is delegated to the desktopManager. */ protected void deiconifyFrame(JInternalFrame f) { // Internal Frame Auditory Cue Activation if ( ! f.isMaximum() ) { // This method seems to regularly get called after an // internal frame is maximized. Don't play this sound then. BasicLookAndFeel.playSound(frame, "InternalFrame.restoreUpSound"); } // delegate to desktop manager getDesktopManager().deiconifyFrame(f); } /** {@collect.stats} This method is called when the frame becomes selected. * This action is delegated to the desktopManager. */ protected void activateFrame(JInternalFrame f) { getDesktopManager().activateFrame(f); } /** {@collect.stats} This method is called when the frame is no longer selected. * This action is delegated to the desktopManager. */ protected void deactivateFrame(JInternalFrame f) { getDesktopManager().deactivateFrame(f); } ///////////////////////////////////////////////////////////////////////// /// Border Listener Class ///////////////////////////////////////////////////////////////////////// /** {@collect.stats} * Listens for border adjustments. */ protected class BorderListener extends MouseInputAdapter implements SwingConstants { // _x & _y are the mousePressed location in absolute coordinate system int _x, _y; // __x & __y are the mousePressed location in source view's coordinate system int __x, __y; Rectangle startingBounds; int resizeDir; protected final int RESIZE_NONE = 0; private boolean discardRelease = false; int resizeCornerSize = 16; public void mouseClicked(MouseEvent e) { if(e.getClickCount() > 1 && e.getSource() == getNorthPane()) { if(frame.isIconifiable() && frame.isIcon()) { try { frame.setIcon(false); } catch (PropertyVetoException e2) { } } else if(frame.isMaximizable()) { if(!frame.isMaximum()) try { frame.setMaximum(true); } catch (PropertyVetoException e2) { } else try { frame.setMaximum(false); } catch (PropertyVetoException e3) { } } } } // Factor out finishMouseReleased() from mouseReleased(), so that // it can be called by cancelResize() without passing it a null // MouseEvent. void finishMouseReleased() { if (discardRelease) { discardRelease = false; return; } if (resizeDir == RESIZE_NONE) { getDesktopManager().endDraggingFrame(frame); dragging = false; } else { // Remove the WindowFocusListener for handling a // WINDOW_LOST_FOCUS event with a cancelResize(). Window windowAncestor = SwingUtilities.getWindowAncestor(frame); if (windowAncestor != null) { windowAncestor.removeWindowFocusListener( getWindowFocusListener()); } Container c = frame.getTopLevelAncestor(); if (c instanceof RootPaneContainer) { Component glassPane = ((RootPaneContainer)c).getGlassPane(); glassPane.setCursor(Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR)); glassPane.setVisible(false); } getDesktopManager().endResizingFrame(frame); resizing = false; } _x = 0; _y = 0; __x = 0; __y = 0; startingBounds = null; resizeDir = RESIZE_NONE; // Set discardRelease to true, so that only a mousePressed() // which sets it to false, will allow entry to the above code // for finishing a resize. discardRelease = true; } public void mouseReleased(MouseEvent e) { finishMouseReleased(); } public void mousePressed(MouseEvent e) { Point p = SwingUtilities.convertPoint((Component)e.getSource(), e.getX(), e.getY(), null); __x = e.getX(); __y = e.getY(); _x = p.x; _y = p.y; startingBounds = frame.getBounds(); resizeDir = RESIZE_NONE; discardRelease = false; try { frame.setSelected(true); } catch (PropertyVetoException e1) { } Insets i = frame.getInsets(); Point ep = new Point(__x, __y); if (e.getSource() == getNorthPane()) { Point np = getNorthPane().getLocation(); ep.x += np.x; ep.y += np.y; } if (e.getSource() == getNorthPane()) { if (ep.x > i.left && ep.y > i.top && ep.x < frame.getWidth() - i.right) { getDesktopManager().beginDraggingFrame(frame); dragging = true; return; } } if (!frame.isResizable()) { return; } if (e.getSource() == frame || e.getSource() == getNorthPane()) { if (ep.x <= i.left) { if (ep.y < resizeCornerSize + i.top) { resizeDir = NORTH_WEST; } else if (ep.y > frame.getHeight() - resizeCornerSize - i.bottom) { resizeDir = SOUTH_WEST; } else { resizeDir = WEST; } } else if (ep.x >= frame.getWidth() - i.right) { if (ep.y < resizeCornerSize + i.top) { resizeDir = NORTH_EAST; } else if (ep.y > frame.getHeight() - resizeCornerSize - i.bottom) { resizeDir = SOUTH_EAST; } else { resizeDir = EAST; } } else if (ep.y <= i.top) { if (ep.x < resizeCornerSize + i.left) { resizeDir = NORTH_WEST; } else if (ep.x > frame.getWidth() - resizeCornerSize - i.right) { resizeDir = NORTH_EAST; } else { resizeDir = NORTH; } } else if (ep.y >= frame.getHeight() - i.bottom) { if (ep.x < resizeCornerSize + i.left) { resizeDir = SOUTH_WEST; } else if (ep.x > frame.getWidth() - resizeCornerSize - i.right) { resizeDir = SOUTH_EAST; } else { resizeDir = SOUTH; } } else { /* the mouse press happened inside the frame, not in the border */ discardRelease = true; return; } Cursor s = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); switch (resizeDir) { case SOUTH: s = Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR); break; case NORTH: s = Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR); break; case WEST: s = Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR); break; case EAST: s = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR); break; case SOUTH_EAST: s = Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR); break; case SOUTH_WEST: s = Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR); break; case NORTH_WEST: s = Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR); break; case NORTH_EAST: s = Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR); break; } Container c = frame.getTopLevelAncestor(); if (c instanceof RootPaneContainer) { Component glassPane = ((RootPaneContainer)c).getGlassPane(); glassPane.setVisible(true); glassPane.setCursor(s); } getDesktopManager().beginResizingFrame(frame, resizeDir); resizing = true; // Add the WindowFocusListener for handling a // WINDOW_LOST_FOCUS event with a cancelResize(). Window windowAncestor = SwingUtilities.getWindowAncestor(frame); if (windowAncestor != null) { windowAncestor.addWindowFocusListener( getWindowFocusListener()); } return; } } public void mouseDragged(MouseEvent e) { if ( startingBounds == null ) { // (STEVE) Yucky work around for bug ID 4106552 return; } Point p = SwingUtilities.convertPoint((Component)e.getSource(), e.getX(), e.getY(), null); int deltaX = _x - p.x; int deltaY = _y - p.y; Dimension min = frame.getMinimumSize(); Dimension max = frame.getMaximumSize(); int newX, newY, newW, newH; Insets i = frame.getInsets(); // Handle a MOVE if (dragging) { if (frame.isMaximum() || ((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK)) { // don't allow moving of frames if maximixed or left mouse // button was not used. return; } int pWidth, pHeight; Dimension s = frame.getParent().getSize(); pWidth = s.width; pHeight = s.height; newX = startingBounds.x - deltaX; newY = startingBounds.y - deltaY; // Make sure we stay in-bounds if(newX + i.left <= -__x) newX = -__x - i.left + 1; if(newY + i.top <= -__y) newY = -__y - i.top + 1; if(newX + __x + i.right >= pWidth) newX = pWidth - __x - i.right - 1; if(newY + __y + i.bottom >= pHeight) newY = pHeight - __y - i.bottom - 1; getDesktopManager().dragFrame(frame, newX, newY); return; } if(!frame.isResizable()) { return; } newX = frame.getX(); newY = frame.getY(); newW = frame.getWidth(); newH = frame.getHeight(); parentBounds = frame.getParent().getBounds(); switch(resizeDir) { case RESIZE_NONE: return; case NORTH: if(startingBounds.height + deltaY < min.height) deltaY = -(startingBounds.height - min.height); else if(startingBounds.height + deltaY > max.height) deltaY = max.height - startingBounds.height; if (startingBounds.y - deltaY < 0) {deltaY = startingBounds.y;} newX = startingBounds.x; newY = startingBounds.y - deltaY; newW = startingBounds.width; newH = startingBounds.height + deltaY; break; case NORTH_EAST: if(startingBounds.height + deltaY < min.height) deltaY = -(startingBounds.height - min.height); else if(startingBounds.height + deltaY > max.height) deltaY = max.height - startingBounds.height; if (startingBounds.y - deltaY < 0) {deltaY = startingBounds.y;} if(startingBounds.width - deltaX < min.width) deltaX = startingBounds.width - min.width; else if(startingBounds.width - deltaX > max.width) deltaX = -(max.width - startingBounds.width); if (startingBounds.x + startingBounds.width - deltaX > parentBounds.width) { deltaX = startingBounds.x + startingBounds.width - parentBounds.width; } newX = startingBounds.x; newY = startingBounds.y - deltaY; newW = startingBounds.width - deltaX; newH = startingBounds.height + deltaY; break; case EAST: if(startingBounds.width - deltaX < min.width) deltaX = startingBounds.width - min.width; else if(startingBounds.width - deltaX > max.width) deltaX = -(max.width - startingBounds.width); if (startingBounds.x + startingBounds.width - deltaX > parentBounds.width) { deltaX = startingBounds.x + startingBounds.width - parentBounds.width; } newW = startingBounds.width - deltaX; newH = startingBounds.height; break; case SOUTH_EAST: if(startingBounds.width - deltaX < min.width) deltaX = startingBounds.width - min.width; else if(startingBounds.width - deltaX > max.width) deltaX = -(max.width - startingBounds.width); if (startingBounds.x + startingBounds.width - deltaX > parentBounds.width) { deltaX = startingBounds.x + startingBounds.width - parentBounds.width; } if(startingBounds.height - deltaY < min.height) deltaY = startingBounds.height - min.height; else if(startingBounds.height - deltaY > max.height) deltaY = -(max.height - startingBounds.height); if (startingBounds.y + startingBounds.height - deltaY > parentBounds.height) { deltaY = startingBounds.y + startingBounds.height - parentBounds.height ; } newW = startingBounds.width - deltaX; newH = startingBounds.height - deltaY; break; case SOUTH: if(startingBounds.height - deltaY < min.height) deltaY = startingBounds.height - min.height; else if(startingBounds.height - deltaY > max.height) deltaY = -(max.height - startingBounds.height); if (startingBounds.y + startingBounds.height - deltaY > parentBounds.height) { deltaY = startingBounds.y + startingBounds.height - parentBounds.height ; } newW = startingBounds.width; newH = startingBounds.height - deltaY; break; case SOUTH_WEST: if(startingBounds.height - deltaY < min.height) deltaY = startingBounds.height - min.height; else if(startingBounds.height - deltaY > max.height) deltaY = -(max.height - startingBounds.height); if (startingBounds.y + startingBounds.height - deltaY > parentBounds.height) { deltaY = startingBounds.y + startingBounds.height - parentBounds.height ; } if(startingBounds.width + deltaX < min.width) deltaX = -(startingBounds.width - min.width); else if(startingBounds.width + deltaX > max.width) deltaX = max.width - startingBounds.width; if (startingBounds.x - deltaX < 0) { deltaX = startingBounds.x; } newX = startingBounds.x - deltaX; newY = startingBounds.y; newW = startingBounds.width + deltaX; newH = startingBounds.height - deltaY; break; case WEST: if(startingBounds.width + deltaX < min.width) deltaX = -(startingBounds.width - min.width); else if(startingBounds.width + deltaX > max.width) deltaX = max.width - startingBounds.width; if (startingBounds.x - deltaX < 0) { deltaX = startingBounds.x; } newX = startingBounds.x - deltaX; newY = startingBounds.y; newW = startingBounds.width + deltaX; newH = startingBounds.height; break; case NORTH_WEST: if(startingBounds.width + deltaX < min.width) deltaX = -(startingBounds.width - min.width); else if(startingBounds.width + deltaX > max.width) deltaX = max.width - startingBounds.width; if (startingBounds.x - deltaX < 0) { deltaX = startingBounds.x; } if(startingBounds.height + deltaY < min.height) deltaY = -(startingBounds.height - min.height); else if(startingBounds.height + deltaY > max.height) deltaY = max.height - startingBounds.height; if (startingBounds.y - deltaY < 0) {deltaY = startingBounds.y;} newX = startingBounds.x - deltaX; newY = startingBounds.y - deltaY; newW = startingBounds.width + deltaX; newH = startingBounds.height + deltaY; break; default: return; } getDesktopManager().resizeFrame(frame, newX, newY, newW, newH); } public void mouseMoved(MouseEvent e) { if(!frame.isResizable()) return; if (e.getSource() == frame || e.getSource() == getNorthPane()) { Insets i = frame.getInsets(); Point ep = new Point(e.getX(), e.getY()); if (e.getSource() == getNorthPane()) { Point np = getNorthPane().getLocation(); ep.x += np.x; ep.y += np.y; } if(ep.x <= i.left) { if(ep.y < resizeCornerSize + i.top) frame.setCursor(Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR)); else if(ep.y > frame.getHeight() - resizeCornerSize - i.bottom) frame.setCursor(Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR)); else frame.setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR)); } else if(ep.x >= frame.getWidth() - i.right) { if(e.getY() < resizeCornerSize + i.top) frame.setCursor(Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR)); else if(ep.y > frame.getHeight() - resizeCornerSize - i.bottom) frame.setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR)); else frame.setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR)); } else if(ep.y <= i.top) { if(ep.x < resizeCornerSize + i.left) frame.setCursor(Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR)); else if(ep.x > frame.getWidth() - resizeCornerSize - i.right) frame.setCursor(Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR)); else frame.setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR)); } else if(ep.y >= frame.getHeight() - i.bottom) { if(ep.x < resizeCornerSize + i.left) frame.setCursor(Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR)); else if(ep.x > frame.getWidth() - resizeCornerSize - i.right) frame.setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR)); else frame.setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)); } else updateFrameCursor(); return; } updateFrameCursor(); } public void mouseEntered(MouseEvent e) { updateFrameCursor(); } public void mouseExited(MouseEvent e) { updateFrameCursor(); } }; /// End BorderListener Class protected class ComponentHandler implements ComponentListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. /** {@collect.stats} Invoked when a JInternalFrame's parent's size changes. */ public void componentResized(ComponentEvent e) { getHandler().componentResized(e); } public void componentMoved(ComponentEvent e) { getHandler().componentMoved(e); } public void componentShown(ComponentEvent e) { getHandler().componentShown(e); } public void componentHidden(ComponentEvent e) { getHandler().componentHidden(e); } } protected ComponentListener createComponentListener() { return getHandler(); } protected class GlassPaneDispatcher implements MouseInputListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void mousePressed(MouseEvent e) { getHandler().mousePressed(e); } public void mouseEntered(MouseEvent e) { getHandler().mouseEntered(e); } public void mouseMoved(MouseEvent e) { getHandler().mouseMoved(e); } public void mouseExited(MouseEvent e) { getHandler().mouseExited(e); } public void mouseClicked(MouseEvent e) { getHandler().mouseClicked(e); } public void mouseReleased(MouseEvent e) { getHandler().mouseReleased(e); } public void mouseDragged(MouseEvent e) { getHandler().mouseDragged(e); } } protected MouseInputListener createGlassPaneDispatcher() { return null; } protected class BasicInternalFrameListener implements InternalFrameListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void internalFrameClosing(InternalFrameEvent e) { getHandler().internalFrameClosing(e); } public void internalFrameClosed(InternalFrameEvent e) { getHandler().internalFrameClosed(e); } public void internalFrameOpened(InternalFrameEvent e) { getHandler().internalFrameOpened(e); } public void internalFrameIconified(InternalFrameEvent e) { getHandler().internalFrameIconified(e); } public void internalFrameDeiconified(InternalFrameEvent e) { getHandler().internalFrameDeiconified(e); } public void internalFrameActivated(InternalFrameEvent e) { getHandler().internalFrameActivated(e); } public void internalFrameDeactivated(InternalFrameEvent e) { getHandler().internalFrameDeactivated(e); } } private static boolean isDragging = false; private class Handler implements ComponentListener, InternalFrameListener, LayoutManager, MouseInputListener, PropertyChangeListener, WindowFocusListener, SwingConstants { public void windowGainedFocus(WindowEvent e) { } public void windowLostFocus(WindowEvent e) { // Cancel a resize which may be in progress, when a // WINDOW_LOST_FOCUS event occurs, which may be // caused by an Alt-Tab or a modal dialog popup. cancelResize(); } // ComponentHandler methods /** {@collect.stats} Invoked when a JInternalFrame's parent's size changes. */ public void componentResized(ComponentEvent e) { // Get the JInternalFrame's parent container size Rectangle parentNewBounds = ((Component) e.getSource()).getBounds(); JInternalFrame.JDesktopIcon icon = null; if (frame != null) { icon = frame.getDesktopIcon(); // Resize the internal frame if it is maximized and relocate // the associated icon as well. if (frame.isMaximum()) { frame.setBounds(0, 0, parentNewBounds.width, parentNewBounds.height); } } // Relocate the icon base on the new parent bounds. if (icon != null) { Rectangle iconBounds = icon.getBounds(); int y = iconBounds.y + (parentNewBounds.height - parentBounds.height); icon.setBounds(iconBounds.x, y, iconBounds.width, iconBounds.height); } // Update the new parent bounds for next resize. if (!parentBounds.equals(parentNewBounds)) { parentBounds = parentNewBounds; } // Validate the component tree for this container. if (frame != null) frame.validate(); } public void componentMoved(ComponentEvent e) {} public void componentShown(ComponentEvent e) {} public void componentHidden(ComponentEvent e) {} // InternalFrameListener public void internalFrameClosed(InternalFrameEvent e) { frame.removeInternalFrameListener(getHandler()); } public void internalFrameActivated(InternalFrameEvent e) { if (!isKeyBindingRegistered()){ setKeyBindingRegistered(true); setupMenuOpenKey(); setupMenuCloseKey(); } if (isKeyBindingRegistered()) setKeyBindingActive(true); } public void internalFrameDeactivated(InternalFrameEvent e) { setKeyBindingActive(false); } public void internalFrameClosing(InternalFrameEvent e) { } public void internalFrameOpened(InternalFrameEvent e) { } public void internalFrameIconified(InternalFrameEvent e) { } public void internalFrameDeiconified(InternalFrameEvent e) { } // LayoutManager public void addLayoutComponent(String name, Component c) {} public void removeLayoutComponent(Component c) {} public Dimension preferredLayoutSize(Container c) { Dimension result; Insets i = frame.getInsets(); result = new Dimension(frame.getRootPane().getPreferredSize()); result.width += i.left + i.right; result.height += i.top + i.bottom; if(getNorthPane() != null) { Dimension d = getNorthPane().getPreferredSize(); result.width = Math.max(d.width, result.width); result.height += d.height; } if(getSouthPane() != null) { Dimension d = getSouthPane().getPreferredSize(); result.width = Math.max(d.width, result.width); result.height += d.height; } if(getEastPane() != null) { Dimension d = getEastPane().getPreferredSize(); result.width += d.width; result.height = Math.max(d.height, result.height); } if(getWestPane() != null) { Dimension d = getWestPane().getPreferredSize(); result.width += d.width; result.height = Math.max(d.height, result.height); } return result; } public Dimension minimumLayoutSize(Container c) { // The minimum size of the internal frame only takes into // account the title pane since you are allowed to resize // the frames to the point where just the title pane is visible. Dimension result = new Dimension(); if (getNorthPane() != null && getNorthPane() instanceof BasicInternalFrameTitlePane) { result = new Dimension(getNorthPane().getMinimumSize()); } Insets i = frame.getInsets(); result.width += i.left + i.right; result.height += i.top + i.bottom; return result; } public void layoutContainer(Container c) { Insets i = frame.getInsets(); int cx, cy, cw, ch; cx = i.left; cy = i.top; cw = frame.getWidth() - i.left - i.right; ch = frame.getHeight() - i.top - i.bottom; if(getNorthPane() != null) { Dimension size = getNorthPane().getPreferredSize(); if (DefaultLookup.getBoolean(frame, BasicInternalFrameUI.this, "InternalFrame.layoutTitlePaneAtOrigin", false)) { cy = 0; ch += i.top; getNorthPane().setBounds(0, 0, frame.getWidth(), size.height); } else { getNorthPane().setBounds(cx, cy, cw, size.height); } cy += size.height; ch -= size.height; } if(getSouthPane() != null) { Dimension size = getSouthPane().getPreferredSize(); getSouthPane().setBounds(cx, frame.getHeight() - i.bottom - size.height, cw, size.height); ch -= size.height; } if(getWestPane() != null) { Dimension size = getWestPane().getPreferredSize(); getWestPane().setBounds(cx, cy, size.width, ch); cw -= size.width; cx += size.width; } if(getEastPane() != null) { Dimension size = getEastPane().getPreferredSize(); getEastPane().setBounds(cw - size.width, cy, size.width, ch); cw -= size.width; } if(frame.getRootPane() != null) { frame.getRootPane().setBounds(cx, cy, cw, ch); } } // MouseInputListener private Component mouseEventTarget = null; private Component dragSource = null; public void mousePressed(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseMoved(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseDragged(MouseEvent e) { } // PropertyChangeListener public void propertyChange(PropertyChangeEvent evt) { String prop = (String)evt.getPropertyName(); JInternalFrame f = (JInternalFrame)evt.getSource(); Object newValue = evt.getNewValue(); Object oldValue = evt.getOldValue(); if (JInternalFrame.IS_CLOSED_PROPERTY == prop) { if (newValue == Boolean.TRUE) { // Cancel a resize in progress if the internal frame // gets a setClosed(true) or dispose(). cancelResize(); if ((frame.getParent() != null) && componentListenerAdded) { frame.getParent().removeComponentListener( componentListener); } closeFrame(f); } } else if (JInternalFrame.IS_MAXIMUM_PROPERTY == prop) { if(newValue == Boolean.TRUE) { maximizeFrame(f); } else { minimizeFrame(f); } } else if(JInternalFrame.IS_ICON_PROPERTY == prop) { if (newValue == Boolean.TRUE) { iconifyFrame(f); } else { deiconifyFrame(f); } } else if (JInternalFrame.IS_SELECTED_PROPERTY == prop) { if (newValue == Boolean.TRUE && oldValue == Boolean.FALSE) { activateFrame(f); } else if (newValue == Boolean.FALSE && oldValue == Boolean.TRUE) { deactivateFrame(f); } } else if (prop == "ancestor") { if (newValue == null) { // Cancel a resize in progress, if the internal frame // gets a remove(), removeNotify() or setIcon(true). cancelResize(); } if (frame.getParent() != null) { parentBounds = f.getParent().getBounds(); } else { parentBounds = null; } if ((frame.getParent() != null) && !componentListenerAdded) { f.getParent().addComponentListener(componentListener); componentListenerAdded = true; } else if ((newValue == null) && componentListenerAdded) { if (f.getParent() != null) { f.getParent().removeComponentListener( componentListener); } componentListenerAdded = false; } } else if (JInternalFrame.TITLE_PROPERTY == prop || prop == "closable" || prop == "iconable" || prop == "maximizable") { Dimension dim = frame.getMinimumSize(); Dimension frame_dim = frame.getSize(); if (dim.width > frame_dim.width) { frame.setSize(dim.width, frame_dim.height); } } } } }
Java
/* * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import sun.swing.DefaultLookup; import sun.swing.UIAction; import javax.swing.*; import javax.swing.event.*; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.border.*; import javax.swing.plaf.*; /** {@collect.stats} * A default L&F implementation of MenuBarUI. This implementation * is a "combined" view/controller. * * @author Georges Saab * @author David Karlton * @author Arnaud Weber */ public class BasicMenuBarUI extends MenuBarUI { protected JMenuBar menuBar = null; protected ContainerListener containerListener; protected ChangeListener changeListener; private Handler handler; public static ComponentUI createUI(JComponent x) { return new BasicMenuBarUI(); } static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.TAKE_FOCUS)); } public void installUI(JComponent c) { menuBar = (JMenuBar) c; installDefaults(); installListeners(); installKeyboardActions(); } protected void installDefaults() { if (menuBar.getLayout() == null || menuBar.getLayout() instanceof UIResource) { menuBar.setLayout(new DefaultMenuLayout(menuBar,BoxLayout.LINE_AXIS)); } LookAndFeel.installProperty(menuBar, "opaque", Boolean.TRUE); LookAndFeel.installBorder(menuBar,"MenuBar.border"); LookAndFeel.installColorsAndFont(menuBar, "MenuBar.background", "MenuBar.foreground", "MenuBar.font"); } protected void installListeners() { containerListener = createContainerListener(); changeListener = createChangeListener(); for (int i = 0; i < menuBar.getMenuCount(); i++) { JMenu menu = menuBar.getMenu(i); if (menu!=null) menu.getModel().addChangeListener(changeListener); } menuBar.addContainerListener(containerListener); } protected void installKeyboardActions() { InputMap inputMap = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); SwingUtilities.replaceUIInputMap(menuBar, JComponent.WHEN_IN_FOCUSED_WINDOW, inputMap); LazyActionMap.installLazyActionMap(menuBar, BasicMenuBarUI.class, "MenuBar.actionMap"); } InputMap getInputMap(int condition) { if (condition == JComponent.WHEN_IN_FOCUSED_WINDOW) { Object[] bindings = (Object[])DefaultLookup.get (menuBar, this, "MenuBar.windowBindings"); if (bindings != null) { return LookAndFeel.makeComponentInputMap(menuBar, bindings); } } return null; } public void uninstallUI(JComponent c) { uninstallDefaults(); uninstallListeners(); uninstallKeyboardActions(); menuBar = null; } protected void uninstallDefaults() { if (menuBar!=null) { LookAndFeel.uninstallBorder(menuBar); } } protected void uninstallListeners() { menuBar.removeContainerListener(containerListener); for (int i = 0; i < menuBar.getMenuCount(); i++) { JMenu menu = menuBar.getMenu(i); if (menu !=null) menu.getModel().removeChangeListener(changeListener); } containerListener = null; changeListener = null; handler = null; } protected void uninstallKeyboardActions() { SwingUtilities.replaceUIInputMap(menuBar, JComponent. WHEN_IN_FOCUSED_WINDOW, null); SwingUtilities.replaceUIActionMap(menuBar, null); } protected ContainerListener createContainerListener() { return getHandler(); } protected ChangeListener createChangeListener() { return getHandler(); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } public Dimension getMinimumSize(JComponent c) { return null; } public Dimension getMaximumSize(JComponent c) { return null; } private class Handler implements ChangeListener, ContainerListener { // // ChangeListener // public void stateChanged(ChangeEvent e) { int i,c; for(i=0,c = menuBar.getMenuCount() ; i < c ; i++) { JMenu menu = menuBar.getMenu(i); if(menu !=null && menu.isSelected()) { menuBar.getSelectionModel().setSelectedIndex(i); break; } } } // // ContainerListener // public void componentAdded(ContainerEvent e) { Component c = e.getChild(); if (c instanceof JMenu) ((JMenu)c).getModel().addChangeListener(changeListener); } public void componentRemoved(ContainerEvent e) { Component c = e.getChild(); if (c instanceof JMenu) ((JMenu)c).getModel().removeChangeListener(changeListener); } } private static class Actions extends UIAction { private static final String TAKE_FOCUS = "takeFocus"; Actions(String key) { super(key); } public void actionPerformed(ActionEvent e) { // TAKE_FOCUS JMenuBar menuBar = (JMenuBar)e.getSource(); MenuSelectionManager defaultManager = MenuSelectionManager.defaultManager(); MenuElement me[]; MenuElement subElements[]; JMenu menu = menuBar.getMenu(0); if (menu!=null) { me = new MenuElement[3]; me[0] = (MenuElement) menuBar; me[1] = (MenuElement) menu; me[2] = (MenuElement) menu.getPopupMenu(); defaultManager.setSelectedPath(me); } } } }
Java
/* * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.KeyListener; import javax.swing.JList; /** {@collect.stats} * The interface which defines the methods required for the implementation of the popup * portion of a combo box. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Tom Santos */ public interface ComboPopup { /** {@collect.stats} * Shows the popup */ public void show(); /** {@collect.stats} * Hides the popup */ public void hide(); /** {@collect.stats} * Returns true if the popup is visible (currently being displayed). * * @return <code>true</code> if the component is visible; <code>false</code> otherwise. */ public boolean isVisible(); /** {@collect.stats} * Returns the list that is being used to draw the items in the combo box. * This method is highly implementation specific and should not be used * for general list manipulation. */ public JList getList(); /** {@collect.stats} * Returns a mouse listener that will be added to the combo box or null. * If this method returns null then it will not be added to the combo box. * * @return a <code>MouseListener</code> or null */ public MouseListener getMouseListener(); /** {@collect.stats} * Returns a mouse motion listener that will be added to the combo box or null. * If this method returns null then it will not be added to the combo box. * * @return a <code>MouseMotionListener</code> or null */ public MouseMotionListener getMouseMotionListener(); /** {@collect.stats} * Returns a key listener that will be added to the combo box or null. * If this method returns null then it will not be added to the combo box. */ public KeyListener getKeyListener(); /** {@collect.stats} * Called to inform the ComboPopup that the UI is uninstalling. * If the ComboPopup added any listeners in the component, it should remove them here. */ public void uninstallingUI(); }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import sun.swing.DefaultLookup; import sun.swing.UIAction; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.ActionMapUIResource; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.OptionPaneUI; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Locale; import java.security.AccessController; import sun.security.action.GetPropertyAction; /** {@collect.stats} * Provides the basic look and feel for a <code>JOptionPane</code>. * <code>BasicMessagePaneUI</code> provides a means to place an icon, * message and buttons into a <code>Container</code>. * Generally, the layout will look like:<p> * <pre> * ------------------ * | i | message | * | c | message | * | o | message | * | n | message | * ------------------ * | buttons | * |________________| * </pre> * icon is an instance of <code>Icon</code> that is wrapped inside a * <code>JLabel</code>. The message is an opaque object and is tested * for the following: if the message is a <code>Component</code> it is * added to the <code>Container</code>, if it is an <code>Icon</code> * it is wrapped inside a <code>JLabel</code> and added to the * <code>Container</code> otherwise it is wrapped inside a <code>JLabel</code>. * <p> * The above layout is used when the option pane's * <code>ComponentOrientation</code> property is horizontal, left-to-right. * The layout will be adjusted appropriately for other orientations. * <p> * The <code>Container</code>, message, icon, and buttons are all * determined from abstract methods. * * @author James Gosling * @author Scott Violet * @author Amy Fowler */ public class BasicOptionPaneUI extends OptionPaneUI { public static final int MinimumWidth = 262; public static final int MinimumHeight = 90; private static String newline; /** {@collect.stats} * <code>JOptionPane</code> that the receiver is providing the * look and feel for. */ protected JOptionPane optionPane; protected Dimension minimumSize; /** {@collect.stats} JComponent provide for input if optionPane.getWantsInput() returns * true. */ protected JComponent inputComponent; /** {@collect.stats} Component to receive focus when messaged with selectInitialValue. */ protected Component initialFocusComponent; /** {@collect.stats} This is set to true in validateComponent if a Component is contained * in either the message or the buttons. */ protected boolean hasCustomComponents; protected PropertyChangeListener propertyChangeListener; private Handler handler; static { newline = (String)java.security.AccessController.doPrivileged( new GetPropertyAction("line.separator")); if (newline == null) { newline = "\n"; } } static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.CLOSE)); BasicLookAndFeel.installAudioActionMap(map); } /** {@collect.stats} * Creates a new BasicOptionPaneUI instance. */ public static ComponentUI createUI(JComponent x) { return new BasicOptionPaneUI(); } /** {@collect.stats} * Installs the receiver as the L&F for the passed in * <code>JOptionPane</code>. */ public void installUI(JComponent c) { optionPane = (JOptionPane)c; installDefaults(); optionPane.setLayout(createLayoutManager()); installComponents(); installListeners(); installKeyboardActions(); } /** {@collect.stats} * Removes the receiver from the L&F controller of the passed in split * pane. */ public void uninstallUI(JComponent c) { uninstallComponents(); optionPane.setLayout(null); uninstallKeyboardActions(); uninstallListeners(); uninstallDefaults(); optionPane = null; } protected void installDefaults() { LookAndFeel.installColorsAndFont(optionPane, "OptionPane.background", "OptionPane.foreground", "OptionPane.font"); LookAndFeel.installBorder(optionPane, "OptionPane.border"); minimumSize = UIManager.getDimension("OptionPane.minimumSize"); LookAndFeel.installProperty(optionPane, "opaque", Boolean.TRUE); } protected void uninstallDefaults() { LookAndFeel.uninstallBorder(optionPane); } protected void installComponents() { optionPane.add(createMessageArea()); Container separator = createSeparator(); if (separator != null) { optionPane.add(separator); } optionPane.add(createButtonArea()); optionPane.applyComponentOrientation(optionPane.getComponentOrientation()); } protected void uninstallComponents() { hasCustomComponents = false; inputComponent = null; initialFocusComponent = null; optionPane.removeAll(); } protected LayoutManager createLayoutManager() { return new BoxLayout(optionPane, BoxLayout.Y_AXIS); } protected void installListeners() { if ((propertyChangeListener = createPropertyChangeListener()) != null) { optionPane.addPropertyChangeListener(propertyChangeListener); } } protected void uninstallListeners() { if (propertyChangeListener != null) { optionPane.removePropertyChangeListener(propertyChangeListener); propertyChangeListener = null; } handler = null; } protected PropertyChangeListener createPropertyChangeListener() { return getHandler(); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } protected void installKeyboardActions() { InputMap map = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); SwingUtilities.replaceUIInputMap(optionPane, JComponent. WHEN_IN_FOCUSED_WINDOW, map); LazyActionMap.installLazyActionMap(optionPane, BasicOptionPaneUI.class, "OptionPane.actionMap"); } protected void uninstallKeyboardActions() { SwingUtilities.replaceUIInputMap(optionPane, JComponent. WHEN_IN_FOCUSED_WINDOW, null); SwingUtilities.replaceUIActionMap(optionPane, null); } InputMap getInputMap(int condition) { if (condition == JComponent.WHEN_IN_FOCUSED_WINDOW) { Object[] bindings = (Object[])DefaultLookup.get( optionPane, this, "OptionPane.windowBindings"); if (bindings != null) { return LookAndFeel.makeComponentInputMap(optionPane, bindings); } } return null; } /** {@collect.stats} * Returns the minimum size the option pane should be. Primarily * provided for subclassers wishing to offer a different minimum size. */ public Dimension getMinimumOptionPaneSize() { if (minimumSize == null) { return new Dimension(MinimumWidth, MinimumHeight); } return new Dimension(minimumSize.width, minimumSize.height); } /** {@collect.stats} * If <code>c</code> is the <code>JOptionPane</code> the receiver * is contained in, the preferred * size that is returned is the maximum of the preferred size of * the <code>LayoutManager</code> for the <code>JOptionPane</code>, and * <code>getMinimumOptionPaneSize</code>. */ public Dimension getPreferredSize(JComponent c) { if ((JOptionPane)c == optionPane) { Dimension ourMin = getMinimumOptionPaneSize(); LayoutManager lm = c.getLayout(); if (lm != null) { Dimension lmSize = lm.preferredLayoutSize(c); if (ourMin != null) return new Dimension (Math.max(lmSize.width, ourMin.width), Math.max(lmSize.height, ourMin.height)); return lmSize; } return ourMin; } return null; } /** {@collect.stats} * Messaged from installComponents to create a Container containing the * body of the message. The icon is the created by calling * <code>addIcon</code>. */ protected Container createMessageArea() { JPanel top = new JPanel(); Border topBorder = (Border)DefaultLookup.get(optionPane, this, "OptionPane.messageAreaBorder"); if (topBorder != null) { top.setBorder(topBorder); } top.setLayout(new BorderLayout()); /* Fill the body. */ Container body = new JPanel(new GridBagLayout()); Container realBody = new JPanel(new BorderLayout()); body.setName("OptionPane.body"); realBody.setName("OptionPane.realBody"); if (getIcon() != null) { JPanel sep = new JPanel(); sep.setName("OptionPane.separator"); sep.setPreferredSize(new Dimension(15, 1)); realBody.add(sep, BorderLayout.BEFORE_LINE_BEGINS); } realBody.add(body, BorderLayout.CENTER); GridBagConstraints cons = new GridBagConstraints(); cons.gridx = cons.gridy = 0; cons.gridwidth = GridBagConstraints.REMAINDER; cons.gridheight = 1; cons.anchor = DefaultLookup.getInt(optionPane, this, "OptionPane.messageAnchor", GridBagConstraints.CENTER); cons.insets = new Insets(0,0,3,0); addMessageComponents(body, cons, getMessage(), getMaxCharactersPerLineCount(), false); top.add(realBody, BorderLayout.CENTER); addIcon(top); return top; } /** {@collect.stats} * Creates the appropriate object to represent <code>msg</code> and * places it into <code>container</code>. If <code>msg</code> is an * instance of Component, it is added directly, if it is an Icon, * a JLabel is created to represent it, otherwise a JLabel is * created for the string, if <code>d</code> is an Object[], this * method will be recursively invoked for the children. * <code>internallyCreated</code> is true if Objc is an instance * of Component and was created internally by this method (this is * used to correctly set hasCustomComponents only if !internallyCreated). */ protected void addMessageComponents(Container container, GridBagConstraints cons, Object msg, int maxll, boolean internallyCreated) { if (msg == null) { return; } if (msg instanceof Component) { // To workaround problem where Gridbad will set child // to its minimum size if its preferred size will not fit // within allocated cells if (msg instanceof JScrollPane || msg instanceof JPanel) { cons.fill = GridBagConstraints.BOTH; cons.weighty = 1; } else { cons.fill = GridBagConstraints.HORIZONTAL; } cons.weightx = 1; container.add((Component) msg, cons); cons.weightx = 0; cons.weighty = 0; cons.fill = GridBagConstraints.NONE; cons.gridy++; if (!internallyCreated) { hasCustomComponents = true; } } else if (msg instanceof Object[]) { Object [] msgs = (Object[]) msg; for (int i = 0; i < msgs.length; i++) { addMessageComponents(container, cons, msgs[i], maxll, false); } } else if (msg instanceof Icon) { JLabel label = new JLabel( (Icon)msg, SwingConstants.CENTER ); configureMessageLabel(label); addMessageComponents(container, cons, label, maxll, true); } else { String s = msg.toString(); int len = s.length(); if (len <= 0) { return; } int nl = -1; int nll = 0; if ((nl = s.indexOf(newline)) >= 0) { nll = newline.length(); } else if ((nl = s.indexOf("\r\n")) >= 0) { nll = 2; } else if ((nl = s.indexOf('\n')) >= 0) { nll = 1; } if (nl >= 0) { // break up newlines if (nl == 0) { JPanel breakPanel = new JPanel() { public Dimension getPreferredSize() { Font f = getFont(); if (f != null) { return new Dimension(1, f.getSize() + 2); } return new Dimension(0, 0); } }; breakPanel.setName("OptionPane.break"); addMessageComponents(container, cons, breakPanel, maxll, true); } else { addMessageComponents(container, cons, s.substring(0, nl), maxll, false); } addMessageComponents(container, cons, s.substring(nl + nll), maxll, false); } else if (len > maxll) { Container c = Box.createVerticalBox(); c.setName("OptionPane.verticalBox"); burstStringInto(c, s, maxll); addMessageComponents(container, cons, c, maxll, true ); } else { JLabel label; label = new JLabel( s, JLabel.LEADING ); label.setName("OptionPane.label"); configureMessageLabel(label); addMessageComponents(container, cons, label, maxll, true); } } } /** {@collect.stats} * Returns the message to display from the JOptionPane the receiver is * providing the look and feel for. */ protected Object getMessage() { inputComponent = null; if (optionPane != null) { if (optionPane.getWantsInput()) { /* Create a user component to capture the input. If the selectionValues are non null the component and there are < 20 values it'll be a combobox, if non null and >= 20, it'll be a list, otherwise it'll be a textfield. */ Object message = optionPane.getMessage(); Object[] sValues = optionPane.getSelectionValues(); Object inputValue = optionPane .getInitialSelectionValue(); JComponent toAdd; if (sValues != null) { if (sValues.length < 20) { JComboBox cBox = new JComboBox(); cBox.setName("OptionPane.comboBox"); for(int counter = 0, maxCounter = sValues.length; counter < maxCounter; counter++) { cBox.addItem(sValues[counter]); } if (inputValue != null) { cBox.setSelectedItem(inputValue); } inputComponent = cBox; toAdd = cBox; } else { JList list = new JList(sValues); JScrollPane sp = new JScrollPane(list); sp.setName("OptionPane.scrollPane"); list.setName("OptionPane.list"); list.setVisibleRowCount(10); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); if(inputValue != null) list.setSelectedValue(inputValue, true); list.addMouseListener(getHandler()); toAdd = sp; inputComponent = list; } } else { MultiplexingTextField tf = new MultiplexingTextField(20); tf.setName("OptionPane.textField"); tf.setKeyStrokes(new KeyStroke[] { KeyStroke.getKeyStroke("ENTER") } ); if (inputValue != null) { String inputString = inputValue.toString(); tf.setText(inputString); tf.setSelectionStart(0); tf.setSelectionEnd(inputString.length()); } tf.addActionListener(getHandler()); toAdd = inputComponent = tf; } Object[] newMessage; if (message == null) { newMessage = new Object[1]; newMessage[0] = toAdd; } else { newMessage = new Object[2]; newMessage[0] = message; newMessage[1] = toAdd; } return newMessage; } return optionPane.getMessage(); } return null; } /** {@collect.stats} * Creates and adds a JLabel representing the icon returned from * <code>getIcon</code> to <code>top</code>. This is messaged from * <code>createMessageArea</code> */ protected void addIcon(Container top) { /* Create the icon. */ Icon sideIcon = getIcon(); if (sideIcon != null) { JLabel iconLabel = new JLabel(sideIcon); iconLabel.setName("OptionPane.iconLabel"); iconLabel.setVerticalAlignment(SwingConstants.TOP); top.add(iconLabel, BorderLayout.BEFORE_LINE_BEGINS); } } /** {@collect.stats} * Returns the icon from the JOptionPane the receiver is providing * the look and feel for, or the default icon as returned from * <code>getDefaultIcon</code>. */ protected Icon getIcon() { Icon mIcon = (optionPane == null ? null : optionPane.getIcon()); if(mIcon == null && optionPane != null) mIcon = getIconForType(optionPane.getMessageType()); return mIcon; } /** {@collect.stats} * Returns the icon to use for the passed in type. */ protected Icon getIconForType(int messageType) { if(messageType < 0 || messageType > 3) return null; String propertyName = null; switch(messageType) { case 0: propertyName = "OptionPane.errorIcon"; break; case 1: propertyName = "OptionPane.informationIcon"; break; case 2: propertyName = "OptionPane.warningIcon"; break; case 3: propertyName = "OptionPane.questionIcon"; break; } if (propertyName != null) { return (Icon)DefaultLookup.get(optionPane, this, propertyName); } return null; } /** {@collect.stats} * Returns the maximum number of characters to place on a line. */ protected int getMaxCharactersPerLineCount() { return optionPane.getMaxCharactersPerLineCount(); } /** {@collect.stats} * Recursively creates new JLabel instances to represent <code>d</code>. * Each JLabel instance is added to <code>c</code>. */ protected void burstStringInto(Container c, String d, int maxll) { // Primitive line wrapping int len = d.length(); if (len <= 0) return; if (len > maxll) { int p = d.lastIndexOf(' ', maxll); if (p <= 0) p = d.indexOf(' ', maxll); if (p > 0 && p < len) { burstStringInto(c, d.substring(0, p), maxll); burstStringInto(c, d.substring(p + 1), maxll); return; } } JLabel label = new JLabel(d, JLabel.LEFT); label.setName("OptionPane.label"); configureMessageLabel(label); c.add(label); } protected Container createSeparator() { return null; } /** {@collect.stats} * Creates and returns a Container containing the buttons. The buttons * are created by calling <code>getButtons</code>. */ protected Container createButtonArea() { JPanel bottom = new JPanel(); Border border = (Border)DefaultLookup.get(optionPane, this, "OptionPane.buttonAreaBorder"); bottom.setName("OptionPane.buttonArea"); if (border != null) { bottom.setBorder(border); } bottom.setLayout(new ButtonAreaLayout( DefaultLookup.getBoolean(optionPane, this, "OptionPane.sameSizeButtons", true), DefaultLookup.getInt(optionPane, this, "OptionPane.buttonPadding", 6), DefaultLookup.getInt(optionPane, this, "OptionPane.buttonOrientation", SwingConstants.CENTER), DefaultLookup.getBoolean(optionPane, this, "OptionPane.isYesLast", false))); addButtonComponents(bottom, getButtons(), getInitialValueIndex()); return bottom; } /** {@collect.stats} * Creates the appropriate object to represent each of the objects in * <code>buttons</code> and adds it to <code>container</code>. This * differs from addMessageComponents in that it will recurse on * <code>buttons</code> and that if button is not a Component * it will create an instance of JButton. */ protected void addButtonComponents(Container container, Object[] buttons, int initialIndex) { if (buttons != null && buttons.length > 0) { boolean sizeButtonsToSame = getSizeButtonsToSameWidth(); boolean createdAll = true; int numButtons = buttons.length; JButton[] createdButtons = null; int maxWidth = 0; if (sizeButtonsToSame) { createdButtons = new JButton[numButtons]; } for(int counter = 0; counter < numButtons; counter++) { Object button = buttons[counter]; Component newComponent; if (button instanceof Component) { createdAll = false; newComponent = (Component)button; container.add(newComponent); hasCustomComponents = true; } else { JButton aButton; if (button instanceof ButtonFactory) { aButton = ((ButtonFactory)button).createButton(); } else if (button instanceof Icon) aButton = new JButton((Icon)button); else aButton = new JButton(button.toString()); aButton.setName("OptionPane.button"); aButton.setMultiClickThreshhold(DefaultLookup.getInt( optionPane, this, "OptionPane.buttonClickThreshhold", 0)); configureButton(aButton); container.add(aButton); ActionListener buttonListener = createButtonActionListener(counter); if (buttonListener != null) { aButton.addActionListener(buttonListener); } newComponent = aButton; } if (sizeButtonsToSame && createdAll && (newComponent instanceof JButton)) { createdButtons[counter] = (JButton)newComponent; maxWidth = Math.max(maxWidth, newComponent.getMinimumSize().width); } if (counter == initialIndex) { initialFocusComponent = newComponent; if (initialFocusComponent instanceof JButton) { JButton defaultB = (JButton)initialFocusComponent; defaultB.addHierarchyListener(new HierarchyListener() { public void hierarchyChanged(HierarchyEvent e) { if ((e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) { JButton defaultButton = (JButton) e.getComponent(); JRootPane root = SwingUtilities.getRootPane(defaultButton); if (root != null) { root.setDefaultButton(defaultButton); } } } }); } } } ((ButtonAreaLayout)container.getLayout()). setSyncAllWidths((sizeButtonsToSame && createdAll)); /* Set the padding, windows seems to use 8 if <= 2 components, otherwise 4 is used. It may actually just be the size of the buttons is always the same, not sure. */ if (DefaultLookup.getBoolean(optionPane, this, "OptionPane.setButtonMargin", true) && sizeButtonsToSame && createdAll) { JButton aButton; int padSize; padSize = (numButtons <= 2? 8 : 4); for(int counter = 0; counter < numButtons; counter++) { aButton = createdButtons[counter]; aButton.setMargin(new Insets(2, padSize, 2, padSize)); } } } } protected ActionListener createButtonActionListener(int buttonIndex) { return new ButtonActionListener(buttonIndex); } /** {@collect.stats} * Returns the buttons to display from the JOptionPane the receiver is * providing the look and feel for. If the JOptionPane has options * set, they will be provided, otherwise if the optionType is * YES_NO_OPTION, yesNoOptions is returned, if the type is * YES_NO_CANCEL_OPTION yesNoCancelOptions is returned, otherwise * defaultButtons are returned. */ protected Object[] getButtons() { if (optionPane != null) { Object[] suppliedOptions = optionPane.getOptions(); if (suppliedOptions == null) { Object[] defaultOptions; int type = optionPane.getOptionType(); Locale l = optionPane.getLocale(); int minimumWidth = DefaultLookup.getInt(optionPane, this, "OptionPane.buttonMinimumWidth",-1); if (type == JOptionPane.YES_NO_OPTION) { defaultOptions = new ButtonFactory[2]; defaultOptions[0] = new ButtonFactory( UIManager.getString("OptionPane.yesButtonText", l), getMnemonic("OptionPane.yesButtonMnemonic", l), (Icon)DefaultLookup.get(optionPane, this, "OptionPane.yesIcon"), minimumWidth); defaultOptions[1] = new ButtonFactory( UIManager.getString("OptionPane.noButtonText", l), getMnemonic("OptionPane.noButtonMnemonic", l), (Icon)DefaultLookup.get(optionPane, this, "OptionPane.noIcon"), minimumWidth); } else if (type == JOptionPane.YES_NO_CANCEL_OPTION) { defaultOptions = new ButtonFactory[3]; defaultOptions[0] = new ButtonFactory( UIManager.getString("OptionPane.yesButtonText", l), getMnemonic("OptionPane.yesButtonMnemonic", l), (Icon)DefaultLookup.get(optionPane, this, "OptionPane.yesIcon"), minimumWidth); defaultOptions[1] = new ButtonFactory( UIManager.getString("OptionPane.noButtonText",l), getMnemonic("OptionPane.noButtonMnemonic", l), (Icon)DefaultLookup.get(optionPane, this, "OptionPane.noIcon"), minimumWidth); defaultOptions[2] = new ButtonFactory( UIManager.getString("OptionPane.cancelButtonText",l), getMnemonic("OptionPane.cancelButtonMnemonic", l), (Icon)DefaultLookup.get(optionPane, this, "OptionPane.cancelIcon"), minimumWidth); } else if (type == JOptionPane.OK_CANCEL_OPTION) { defaultOptions = new ButtonFactory[2]; defaultOptions[0] = new ButtonFactory( UIManager.getString("OptionPane.okButtonText",l), getMnemonic("OptionPane.okButtonMnemonic", l), (Icon)DefaultLookup.get(optionPane, this, "OptionPane.okIcon"), minimumWidth); defaultOptions[1] = new ButtonFactory( UIManager.getString("OptionPane.cancelButtonText",l), getMnemonic("OptionPane.cancelButtonMnemonic", l), (Icon)DefaultLookup.get(optionPane, this, "OptionPane.cancelIcon"), minimumWidth); } else { defaultOptions = new ButtonFactory[1]; defaultOptions[0] = new ButtonFactory( UIManager.getString("OptionPane.okButtonText",l), getMnemonic("OptionPane.okButtonMnemonic", l), (Icon)DefaultLookup.get(optionPane, this, "OptionPane.okIcon"), minimumWidth); } return defaultOptions; } return suppliedOptions; } return null; } private int getMnemonic(String key, Locale l) { String value = (String)UIManager.get(key, l); if (value == null) { return 0; } try { return Integer.parseInt(value); } catch (NumberFormatException nfe) { } return 0; } /** {@collect.stats} * Returns true, basic L&F wants all the buttons to have the same * width. */ protected boolean getSizeButtonsToSameWidth() { return true; } /** {@collect.stats} * Returns the initial index into the buttons to select. The index * is calculated from the initial value from the JOptionPane and * options of the JOptionPane or 0. */ protected int getInitialValueIndex() { if (optionPane != null) { Object iv = optionPane.getInitialValue(); Object[] options = optionPane.getOptions(); if(options == null) { return 0; } else if(iv != null) { for(int counter = options.length - 1; counter >= 0; counter--){ if(options[counter].equals(iv)) return counter; } } } return -1; } /** {@collect.stats} * Sets the input value in the option pane the receiver is providing * the look and feel for based on the value in the inputComponent. */ protected void resetInputValue() { if(inputComponent != null && (inputComponent instanceof JTextField)) { optionPane.setInputValue(((JTextField)inputComponent).getText()); } else if(inputComponent != null && (inputComponent instanceof JComboBox)) { optionPane.setInputValue(((JComboBox)inputComponent) .getSelectedItem()); } else if(inputComponent != null) { optionPane.setInputValue(((JList)inputComponent) .getSelectedValue()); } } /** {@collect.stats} * If inputComponent is non-null, the focus is requested on that, * otherwise request focus on the default value */ public void selectInitialValue(JOptionPane op) { if (inputComponent != null) inputComponent.requestFocus(); else { if (initialFocusComponent != null) initialFocusComponent.requestFocus(); if (initialFocusComponent instanceof JButton) { JRootPane root = SwingUtilities.getRootPane(initialFocusComponent); if (root != null) { root.setDefaultButton((JButton)initialFocusComponent); } } } } /** {@collect.stats} * Returns true if in the last call to validateComponent the message * or buttons contained a subclass of Component. */ public boolean containsCustomComponents(JOptionPane op) { return hasCustomComponents; } /** {@collect.stats} * <code>ButtonAreaLayout</code> behaves in a similar manner to * <code>FlowLayout</code>. It lays out all components from left to * right. If <code>syncAllWidths</code> is true, the widths of each * component will be set to the largest preferred size width. * * This inner class is marked &quot;public&quot; due to a compiler bug. * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicOptionPaneUI. */ public static class ButtonAreaLayout implements LayoutManager { protected boolean syncAllWidths; protected int padding; /** {@collect.stats} If true, children are lumped together in parent. */ protected boolean centersChildren; private int orientation; private boolean reverseButtons; /** {@collect.stats} * Indicates whether or not centersChildren should be used vs * the orientation. This is done for backward compatability * for subclassers. */ private boolean useOrientation; public ButtonAreaLayout(boolean syncAllWidths, int padding) { this.syncAllWidths = syncAllWidths; this.padding = padding; centersChildren = true; useOrientation = false; } ButtonAreaLayout(boolean syncAllSizes, int padding, int orientation, boolean reverseButtons) { this(syncAllSizes, padding); useOrientation = true; this.orientation = orientation; this.reverseButtons = reverseButtons; } public void setSyncAllWidths(boolean newValue) { syncAllWidths = newValue; } public boolean getSyncAllWidths() { return syncAllWidths; } public void setPadding(int newPadding) { this.padding = newPadding; } public int getPadding() { return padding; } public void setCentersChildren(boolean newValue) { centersChildren = newValue; useOrientation = false; } public boolean getCentersChildren() { return centersChildren; } private int getOrientation(Container container) { if (!useOrientation) { return SwingConstants.CENTER; } if (container.getComponentOrientation().isLeftToRight()) { return orientation; } switch (orientation) { case SwingConstants.LEFT: return SwingConstants.RIGHT; case SwingConstants.RIGHT: return SwingConstants.LEFT; case SwingConstants.CENTER: return SwingConstants.CENTER; } return SwingConstants.LEFT; } public void addLayoutComponent(String string, Component comp) { } public void layoutContainer(Container container) { Component[] children = container.getComponents(); if(children != null && children.length > 0) { int numChildren = children.length; Insets insets = container.getInsets(); int maxWidth = 0; int maxHeight = 0; int totalButtonWidth = 0; int x = 0; int xOffset = 0; boolean ltr = container.getComponentOrientation(). isLeftToRight(); boolean reverse = (ltr) ? reverseButtons : !reverseButtons; for(int counter = 0; counter < numChildren; counter++) { Dimension pref = children[counter].getPreferredSize(); maxWidth = Math.max(maxWidth, pref.width); maxHeight = Math.max(maxHeight, pref.height); totalButtonWidth += pref.width; } if (getSyncAllWidths()) { totalButtonWidth = maxWidth * numChildren; } totalButtonWidth += (numChildren - 1) * padding; switch (getOrientation(container)) { case SwingConstants.LEFT: x = insets.left; break; case SwingConstants.RIGHT: x = container.getWidth() - insets.right - totalButtonWidth; break; case SwingConstants.CENTER: if (getCentersChildren() || numChildren < 2) { x = (container.getWidth() - totalButtonWidth) / 2; } else { x = insets.left; if (getSyncAllWidths()) { xOffset = (container.getWidth() - insets.left - insets.right - totalButtonWidth) / (numChildren - 1) + maxWidth; } else { xOffset = (container.getWidth() - insets.left - insets.right - totalButtonWidth) / (numChildren - 1); } } break; } for (int counter = 0; counter < numChildren; counter++) { int index = (reverse) ? numChildren - counter - 1 : counter; Dimension pref = children[index].getPreferredSize(); if (getSyncAllWidths()) { children[index].setBounds(x, insets.top, maxWidth, maxHeight); } else { children[index].setBounds(x, insets.top, pref.width, pref.height); } if (xOffset != 0) { x += xOffset; } else { x += children[index].getWidth() + padding; } } } } public Dimension minimumLayoutSize(Container c) { if(c != null) { Component[] children = c.getComponents(); if(children != null && children.length > 0) { Dimension aSize; int numChildren = children.length; int height = 0; Insets cInsets = c.getInsets(); int extraHeight = cInsets.top + cInsets.bottom; int extraWidth = cInsets.left + cInsets.right; if (syncAllWidths) { int maxWidth = 0; for(int counter = 0; counter < numChildren; counter++){ aSize = children[counter].getPreferredSize(); height = Math.max(height, aSize.height); maxWidth = Math.max(maxWidth, aSize.width); } return new Dimension(extraWidth + (maxWidth * numChildren) + (numChildren - 1) * padding, extraHeight + height); } else { int totalWidth = 0; for(int counter = 0; counter < numChildren; counter++){ aSize = children[counter].getPreferredSize(); height = Math.max(height, aSize.height); totalWidth += aSize.width; } totalWidth += ((numChildren - 1) * padding); return new Dimension(extraWidth + totalWidth, extraHeight + height); } } } return new Dimension(0, 0); } public Dimension preferredLayoutSize(Container c) { return minimumLayoutSize(c); } public void removeLayoutComponent(Component c) { } } /** {@collect.stats} * This inner class is marked &quot;public&quot; due to a compiler bug. * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicOptionPaneUI. */ public class PropertyChangeHandler implements PropertyChangeListener { /** {@collect.stats} * If the source of the PropertyChangeEvent <code>e</code> equals the * optionPane and is one of the ICON_PROPERTY, MESSAGE_PROPERTY, * OPTIONS_PROPERTY or INITIAL_VALUE_PROPERTY, * validateComponent is invoked. */ public void propertyChange(PropertyChangeEvent e) { getHandler().propertyChange(e); } } /** {@collect.stats} * Configures any necessary colors/fonts for the specified label * used representing the message. */ private void configureMessageLabel(JLabel label) { Color color = (Color)DefaultLookup.get(optionPane, this, "OptionPane.messageForeground"); if (color != null) { label.setForeground(color); } Font messageFont = (Font)DefaultLookup.get(optionPane, this, "OptionPane.messageFont"); if (messageFont != null) { label.setFont(messageFont); } } /** {@collect.stats} * Configures any necessary colors/fonts for the specified button * used representing the button portion of the optionpane. */ private void configureButton(JButton button) { Font buttonFont = (Font)DefaultLookup.get(optionPane, this, "OptionPane.buttonFont"); if (buttonFont != null) { button.setFont(buttonFont); } } /** {@collect.stats} * This inner class is marked &quot;public&quot; due to a compiler bug. * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicOptionPaneUI. */ public class ButtonActionListener implements ActionListener { protected int buttonIndex; public ButtonActionListener(int buttonIndex) { this.buttonIndex = buttonIndex; } public void actionPerformed(ActionEvent e) { if (optionPane != null) { int optionType = optionPane.getOptionType(); Object[] options = optionPane.getOptions(); /* If the option pane takes input, then store the input value * if custom options were specified, if the option type is * DEFAULT_OPTION, OR if option type is set to a predefined * one and the user chose the affirmative answer. */ if (inputComponent != null) { if (options != null || optionType == JOptionPane.DEFAULT_OPTION || ((optionType == JOptionPane.YES_NO_OPTION || optionType == JOptionPane.YES_NO_CANCEL_OPTION || optionType == JOptionPane.OK_CANCEL_OPTION) && buttonIndex == 0)) { resetInputValue(); } } if (options == null) { if (optionType == JOptionPane.OK_CANCEL_OPTION && buttonIndex == 1) { optionPane.setValue(new Integer(2)); } else { optionPane.setValue(new Integer(buttonIndex)); } } else { optionPane.setValue(options[buttonIndex]); } } } } private class Handler implements ActionListener, MouseListener, PropertyChangeListener { // // ActionListener // public void actionPerformed(ActionEvent e) { optionPane.setInputValue(((JTextField)e.getSource()).getText()); } // // MouseListener // public void mouseClicked(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { if (e.getClickCount() == 2) { JList list = (JList)e.getSource(); int index = list.locationToIndex(e.getPoint()); optionPane.setInputValue(list.getModel().getElementAt(index)); } } // // PropertyChangeListener // public void propertyChange(PropertyChangeEvent e) { if(e.getSource() == optionPane) { // Option Pane Auditory Cue Activation // only respond to "ancestor" changes // the idea being that a JOptionPane gets a JDialog when it is // set to appear and loses it's JDialog when it is dismissed. if ("ancestor" == e.getPropertyName()) { JOptionPane op = (JOptionPane)e.getSource(); boolean isComingUp; // if the old value is null, then the JOptionPane is being // created since it didn't previously have an ancestor. if (e.getOldValue() == null) { isComingUp = true; } else { isComingUp = false; } // figure out what to do based on the message type switch (op.getMessageType()) { case JOptionPane.PLAIN_MESSAGE: if (isComingUp) { BasicLookAndFeel.playSound(optionPane, "OptionPane.informationSound"); } break; case JOptionPane.QUESTION_MESSAGE: if (isComingUp) { BasicLookAndFeel.playSound(optionPane, "OptionPane.questionSound"); } break; case JOptionPane.INFORMATION_MESSAGE: if (isComingUp) { BasicLookAndFeel.playSound(optionPane, "OptionPane.informationSound"); } break; case JOptionPane.WARNING_MESSAGE: if (isComingUp) { BasicLookAndFeel.playSound(optionPane, "OptionPane.warningSound"); } break; case JOptionPane.ERROR_MESSAGE: if (isComingUp) { BasicLookAndFeel.playSound(optionPane, "OptionPane.errorSound"); } break; default: System.err.println("Undefined JOptionPane type: " + op.getMessageType()); break; } } // Visual activity String changeName = e.getPropertyName(); if(changeName == JOptionPane.OPTIONS_PROPERTY || changeName == JOptionPane.INITIAL_VALUE_PROPERTY || changeName == JOptionPane.ICON_PROPERTY || changeName == JOptionPane.MESSAGE_TYPE_PROPERTY || changeName == JOptionPane.OPTION_TYPE_PROPERTY || changeName == JOptionPane.MESSAGE_PROPERTY || changeName == JOptionPane.SELECTION_VALUES_PROPERTY || changeName == JOptionPane.INITIAL_SELECTION_VALUE_PROPERTY || changeName == JOptionPane.WANTS_INPUT_PROPERTY) { uninstallComponents(); installComponents(); optionPane.validate(); } else if (changeName == "componentOrientation") { ComponentOrientation o = (ComponentOrientation)e.getNewValue(); JOptionPane op = (JOptionPane)e.getSource(); if (o != (ComponentOrientation)e.getOldValue()) { op.applyComponentOrientation(o); } } } } } // // Classes used when optionPane.getWantsInput returns true. // /** {@collect.stats} * A JTextField that allows you to specify an array of KeyStrokes that * that will have their bindings processed regardless of whether or * not they are registered on the JTextField. This is used as we really * want the ActionListener to be notified so that we can push the * change to the JOptionPane, but we also want additional bindings * (those of the JRootPane) to be processed as well. */ private static class MultiplexingTextField extends JTextField { private KeyStroke[] strokes; MultiplexingTextField(int cols) { super(cols); } /** {@collect.stats} * Sets the KeyStrokes that will be additional processed for * ancestor bindings. */ void setKeyStrokes(KeyStroke[] strokes) { this.strokes = strokes; } protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) { boolean processed = super.processKeyBinding(ks, e, condition, pressed); if (processed && condition != JComponent.WHEN_IN_FOCUSED_WINDOW) { for (int counter = strokes.length - 1; counter >= 0; counter--) { if (strokes[counter].equals(ks)) { // Returning false will allow further processing // of the bindings, eg our parent Containers will get a // crack at them. return false; } } } return processed; } } /** {@collect.stats} * Registered in the ActionMap. Sets the value of the option pane * to <code>JOptionPane.CLOSED_OPTION</code>. */ private static class Actions extends UIAction { private static final String CLOSE = "close"; Actions(String key) { super(key); } public void actionPerformed(ActionEvent e) { if (getName() == CLOSE) { JOptionPane optionPane = (JOptionPane)e.getSource(); optionPane.setValue(new Integer(JOptionPane.CLOSED_OPTION)); } } } /** {@collect.stats} * This class is used to create the default buttons. This indirection is * used so that addButtonComponents can tell which Buttons were created * by us vs subclassers or from the JOptionPane itself. */ private static class ButtonFactory { private String text; private int mnemonic; private Icon icon; private int minimumWidth = -1; ButtonFactory(String text, int mnemonic, Icon icon, int minimumWidth) { this.text = text; this.mnemonic = mnemonic; this.icon = icon; this.minimumWidth = minimumWidth; } JButton createButton() { JButton button = null; if (minimumWidth > 0) { button = new ConstrainedButton(text, minimumWidth); } else { button = new JButton(text); } if (icon != null) { button.setIcon(icon); } if (mnemonic != 0) { button.setMnemonic(mnemonic); } return button; } private static class ConstrainedButton extends JButton { int minimumWidth; ConstrainedButton(String text, int minimumWidth) { super(text); this.minimumWidth = minimumWidth; } public Dimension getMinimumSize() { Dimension min = super.getMinimumSize(); min.width = Math.max(min.width, minimumWidth); return min; } public Dimension getPreferredSize() { Dimension pref = super.getPreferredSize(); pref.width = Math.max(pref.width, minimumWidth); return pref; } } } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import javax.swing.*; import javax.swing.text.*; import javax.swing.event.*; import javax.swing.plaf.*; /** {@collect.stats} * Provides the Windows look and feel for a password field. * The only difference from the standard text field is that * the view of the text is simply a string of the echo * character as specified in JPasswordField, rather than the * real text contained in the field. * * @author Timothy Prinzing */ public class BasicPasswordFieldUI extends BasicTextFieldUI { /** {@collect.stats} * Creates a UI for a JPasswordField. * * @param c the JPasswordField * @return the UI */ public static ComponentUI createUI(JComponent c) { return new BasicPasswordFieldUI(); } /** {@collect.stats} * Fetches the name used as a key to look up properties through the * UIManager. This is used as a prefix to all the standard * text properties. * * @return the name ("PasswordField") */ protected String getPropertyPrefix() { return "PasswordField"; } /** {@collect.stats} * Installs the necessary properties on the JPasswordField. * @since 1.6 */ protected void installDefaults() { super.installDefaults(); String prefix = getPropertyPrefix(); Character echoChar = (Character)UIManager.getDefaults().get(prefix + ".echoChar"); if(echoChar != null) { LookAndFeel.installProperty(getComponent(), "echoChar", echoChar); } } /** {@collect.stats} * Creates a view (PasswordView) for an element. * * @param elem the element * @return the view */ public View create(Element elem) { return new PasswordView(elem); } /** {@collect.stats} * Create the action map for Password Field. This map provides * same actions for double mouse click and * and for triple mouse click (see bug 4231444). */ ActionMap createActionMap() { ActionMap map = super.createActionMap(); if (map.get(DefaultEditorKit.selectWordAction) != null) { Action a = map.get(DefaultEditorKit.selectLineAction); if (a != null) { map.remove(DefaultEditorKit.selectWordAction); map.put(DefaultEditorKit.selectWordAction, a); } } return map; } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.beans.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.InputEvent; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.text.*; import javax.swing.plaf.*; /** {@collect.stats} * Provides the look and feel for a plain text editor. In this * implementation the default UI is extended to act as a simple * view factory. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Timothy Prinzing */ public class BasicTextAreaUI extends BasicTextUI { /** {@collect.stats} * Creates a UI for a JTextArea. * * @param ta a text area * @return the UI */ public static ComponentUI createUI(JComponent ta) { return new BasicTextAreaUI(); } /** {@collect.stats} * Constructs a new BasicTextAreaUI object. */ public BasicTextAreaUI() { super(); } /** {@collect.stats} * Fetches the name used as a key to look up properties through the * UIManager. This is used as a prefix to all the standard * text properties. * * @return the name ("TextArea") */ protected String getPropertyPrefix() { return "TextArea"; } protected void installDefaults() { super.installDefaults(); //the fix for 4785160 is undone } /** {@collect.stats} * This method gets called when a bound property is changed * on the associated JTextComponent. This is a hook * which UI implementations may change to reflect how the * UI displays bound properties of JTextComponent subclasses. * This is implemented to rebuild the View when the * <em>WrapLine</em> or the <em>WrapStyleWord</em> property changes. * * @param evt the property change event */ protected void propertyChange(PropertyChangeEvent evt) { super.propertyChange(evt); if (evt.getPropertyName().equals("lineWrap") || evt.getPropertyName().equals("wrapStyleWord") || evt.getPropertyName().equals("tabSize")) { // rebuild the view modelChanged(); } else if ("editable".equals(evt.getPropertyName())) { updateFocusTraversalKeys(); } } /** {@collect.stats} * The method is overridden to take into account caret width. * * @param c the editor component * @return the preferred size * @throws IllegalArgumentException if invalid value is passed * * @since 1.5 */ public Dimension getPreferredSize(JComponent c) { return super.getPreferredSize(c); //the fix for 4785160 is undone } /** {@collect.stats} * The method is overridden to take into account caret width. * * @param c the editor component * @return the minimum size * @throws IllegalArgumentException if invalid value is passed * * @since 1.5 */ public Dimension getMinimumSize(JComponent c) { return super.getMinimumSize(c); //the fix for 4785160 is undone } /** {@collect.stats} * Creates the view for an element. Returns a WrappedPlainView or * PlainView. * * @param elem the element * @return the view */ public View create(Element elem) { Document doc = elem.getDocument(); Object i18nFlag = doc.getProperty("i18n"/*AbstractDocument.I18NProperty*/); if ((i18nFlag != null) && i18nFlag.equals(Boolean.TRUE)) { // build a view that support bidi return createI18N(elem); } else { JTextComponent c = getComponent(); if (c instanceof JTextArea) { JTextArea area = (JTextArea) c; View v; if (area.getLineWrap()) { v = new WrappedPlainView(elem, area.getWrapStyleWord()); } else { v = new PlainView(elem); } return v; } } return null; } View createI18N(Element elem) { String kind = elem.getName(); if (kind != null) { if (kind.equals(AbstractDocument.ContentElementName)) { return new PlainParagraph(elem); } else if (kind.equals(AbstractDocument.ParagraphElementName)) { return new BoxView(elem, View.Y_AXIS); } } return null; } /** {@collect.stats} * Returns the baseline. * * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public int getBaseline(JComponent c, int width, int height) { super.getBaseline(c, width, height); Object i18nFlag = ((JTextComponent)c).getDocument(). getProperty("i18n"); Insets insets = c.getInsets(); if (Boolean.TRUE.equals(i18nFlag)) { View rootView = getRootView((JTextComponent)c); if (rootView.getViewCount() > 0) { height = height - insets.top - insets.bottom; int baseline = insets.top; int fieldBaseline = BasicHTML.getBaseline( rootView.getView(0), width - insets.left - insets.right, height); if (fieldBaseline < 0) { return -1; } return baseline + fieldBaseline; } return -1; } FontMetrics fm = c.getFontMetrics(c.getFont()); return insets.top + fm.getAscent(); } /** {@collect.stats} * Returns an enum indicating how the baseline of the component * changes as the size changes. * * @throws NullPointerException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public Component.BaselineResizeBehavior getBaselineResizeBehavior( JComponent c) { super.getBaselineResizeBehavior(c); return Component.BaselineResizeBehavior.CONSTANT_ASCENT; } /** {@collect.stats} * Paragraph for representing plain-text lines that support * bidirectional text. */ static class PlainParagraph extends ParagraphView { PlainParagraph(Element elem) { super(elem); layoutPool = new LogicalView(elem); layoutPool.setParent(this); } public void setParent(View parent) { super.setParent(parent); if (parent != null) { setPropertiesFromAttributes(); } } protected void setPropertiesFromAttributes() { Component c = getContainer(); if ((c != null) && (! c.getComponentOrientation().isLeftToRight())) { setJustification(StyleConstants.ALIGN_RIGHT); } else { setJustification(StyleConstants.ALIGN_LEFT); } } /** {@collect.stats} * Fetch the constraining span to flow against for * the given child index. */ public int getFlowSpan(int index) { Component c = getContainer(); if (c instanceof JTextArea) { JTextArea area = (JTextArea) c; if (! area.getLineWrap()) { // no limit if unwrapped return Integer.MAX_VALUE; } } return super.getFlowSpan(index); } protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirements r) { SizeRequirements req = super.calculateMinorAxisRequirements(axis, r); Component c = getContainer(); if (c instanceof JTextArea) { JTextArea area = (JTextArea) c; if (! area.getLineWrap()) { // min is pref if unwrapped req.minimum = req.preferred; } else { req.minimum = 0; req.preferred = getWidth(); if (req.preferred == Integer.MAX_VALUE) { // We have been initially set to MAX_VALUE, but we // don't want this as our preferred. req.preferred = 100; } } } return req; } /** {@collect.stats} * Sets the size of the view. If the size has changed, layout * is redone. The size is the full size of the view including * the inset areas. * * @param width the width >= 0 * @param height the height >= 0 */ public void setSize(float width, float height) { if ((int) width != getWidth()) { preferenceChanged(null, true, true); } super.setSize(width, height); } /** {@collect.stats} * This class can be used to represent a logical view for * a flow. It keeps the children updated to reflect the state * of the model, gives the logical child views access to the * view hierarchy, and calculates a preferred span. It doesn't * do any rendering, layout, or model/view translation. */ static class LogicalView extends CompositeView { LogicalView(Element elem) { super(elem); } protected int getViewIndexAtPosition(int pos) { Element elem = getElement(); if (elem.getElementCount() > 0) { return elem.getElementIndex(pos); } return 0; } protected boolean updateChildren(DocumentEvent.ElementChange ec, DocumentEvent e, ViewFactory f) { return false; } protected void loadChildren(ViewFactory f) { Element elem = getElement(); if (elem.getElementCount() > 0) { super.loadChildren(f); } else { View v = new GlyphView(elem); append(v); } } public float getPreferredSpan(int axis) { if( getViewCount() != 1 ) throw new Error("One child view is assumed."); View v = getView(0); return v.getPreferredSpan(axis); } /** {@collect.stats} * Forward the DocumentEvent to the given child view. This * is implemented to reparent the child to the logical view * (the children may have been parented by a row in the flow * if they fit without breaking) and then execute the superclass * behavior. * * @param v the child view to forward the event to. * @param e the change information from the associated document * @param a the current allocation of the view * @param f the factory to use to rebuild if the view has children * @see #forwardUpdate * @since 1.3 */ protected void forwardUpdateToView(View v, DocumentEvent e, Shape a, ViewFactory f) { v.setParent(this); super.forwardUpdateToView(v, e, a, f); } // The following methods don't do anything useful, they // simply keep the class from being abstract. public void paint(Graphics g, Shape allocation) { } protected boolean isBefore(int x, int y, Rectangle alloc) { return false; } protected boolean isAfter(int x, int y, Rectangle alloc) { return false; } protected View getViewAtPoint(int x, int y, Rectangle alloc) { return null; } protected void childAllocation(int index, Rectangle a) { } } } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import sun.swing.SwingUtilities2; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.*; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.io.Serializable; import sun.swing.DefaultLookup; /** {@collect.stats} * A Basic L&F implementation of ProgressBarUI. * * @author Michael C. Albers * @author Kathy Walrath */ public class BasicProgressBarUI extends ProgressBarUI { private int cachedPercent; private int cellLength, cellSpacing; // The "selectionForeground" is the color of the text when it is painted // over a filled area of the progress bar. The "selectionBackground" // is for the text over the unfilled progress bar area. private Color selectionForeground, selectionBackground; private Animator animator; protected JProgressBar progressBar; protected ChangeListener changeListener; private Handler handler; /** {@collect.stats} * The current state of the indeterminate animation's cycle. * 0, the initial value, means paint the first frame. * When the progress bar is indeterminate and showing, * the default animation thread updates this variable * by invoking incrementAnimationIndex() * every repaintInterval milliseconds. */ private int animationIndex = 0; /** {@collect.stats} * The number of frames per cycle. Under the default implementation, * this depends on the cycleTime and repaintInterval. It * must be an even number for the default painting algorithm. This * value is set in the initIndeterminateValues method. */ private int numFrames; //0 1|numFrames-1 ... numFrames/2 /** {@collect.stats} * Interval (in ms) between repaints of the indeterminate progress bar. * The value of this method is set * (every time the progress bar changes to indeterminate mode) * using the * "ProgressBar.repaintInterval" key in the defaults table. */ private int repaintInterval; /** {@collect.stats} * The number of milliseconds until the animation cycle repeats. * The value of this method is set * (every time the progress bar changes to indeterminate mode) * using the * "ProgressBar.cycleTime" key in the defaults table. */ private int cycleTime; //must be repaintInterval*2*aPositiveInteger //performance stuff private static boolean ADJUSTTIMER = true; //makes a BIG difference; //make this false for //performance tests /** {@collect.stats} * Used to hold the location and size of the bouncing box (returned * by getBox) to be painted. * * @since 1.5 */ protected Rectangle boxRect; /** {@collect.stats} * The rectangle to be updated the next time the * animation thread calls repaint. For bouncing-box * animation this rect should include the union of * the currently displayed box (which needs to be erased) * and the box to be displayed next. * This rectangle's values are set in * the setAnimationIndex method. */ private Rectangle nextPaintRect; //cache /** {@collect.stats} The component's painting area, not including the border. */ private Rectangle componentInnards; //the current painting area private Rectangle oldComponentInnards; //used to see if the size changed /** {@collect.stats} For bouncing-box animation, the change in position per frame. */ private double delta = 0.0; private int maxPosition = 0; //maximum X (horiz) or Y box location public static ComponentUI createUI(JComponent x) { return new BasicProgressBarUI(); } public void installUI(JComponent c) { progressBar = (JProgressBar)c; installDefaults(); installListeners(); if (progressBar.isIndeterminate()) { initIndeterminateValues(); } } public void uninstallUI(JComponent c) { if (progressBar.isIndeterminate()) { cleanUpIndeterminateValues(); } uninstallDefaults(); uninstallListeners(); progressBar = null; } protected void installDefaults() { LookAndFeel.installProperty(progressBar, "opaque", Boolean.TRUE); LookAndFeel.installBorder(progressBar,"ProgressBar.border"); LookAndFeel.installColorsAndFont(progressBar, "ProgressBar.background", "ProgressBar.foreground", "ProgressBar.font"); cellLength = UIManager.getInt("ProgressBar.cellLength"); if (cellLength == 0) cellLength = 1; cellSpacing = UIManager.getInt("ProgressBar.cellSpacing"); selectionForeground = UIManager.getColor("ProgressBar.selectionForeground"); selectionBackground = UIManager.getColor("ProgressBar.selectionBackground"); } protected void uninstallDefaults() { LookAndFeel.uninstallBorder(progressBar); } protected void installListeners() { //Listen for changes in the progress bar's data. changeListener = getHandler(); progressBar.addChangeListener(changeListener); //Listen for changes between determinate and indeterminate state. progressBar.addPropertyChangeListener(getHandler()); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } /** {@collect.stats} * Starts the animation thread, creating and initializing * it if necessary. This method is invoked when an * indeterminate progress bar should start animating. * Reasons for this may include: * <ul> * <li>The progress bar is determinate and becomes displayable * <li>The progress bar is displayable and becomes determinate * <li>The progress bar is displayable and determinate and this * UI is installed * </ul> * If you implement your own animation thread, * you must override this method. * * @since 1.4 * @see #stopAnimationTimer */ protected void startAnimationTimer() { if (animator == null) { animator = new Animator(); } animator.start(getRepaintInterval()); } /** {@collect.stats} * Stops the animation thread. * This method is invoked when the indeterminate * animation should be stopped. Reasons for this may include: * <ul> * <li>The progress bar changes to determinate * <li>The progress bar is no longer part of a displayable hierarchy * <li>This UI in uninstalled * </ul> * If you implement your own animation thread, * you must override this method. * * @since 1.4 * @see #startAnimationTimer */ protected void stopAnimationTimer() { if (animator != null) { animator.stop(); } } /** {@collect.stats} * Removes all listeners installed by this object. */ protected void uninstallListeners() { progressBar.removeChangeListener(changeListener); progressBar.removePropertyChangeListener(getHandler()); handler = null; } /** {@collect.stats} * Returns the baseline. * * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public int getBaseline(JComponent c, int width, int height) { super.getBaseline(c, width, height); if (progressBar.isStringPainted() && progressBar.getOrientation() == JProgressBar.HORIZONTAL) { FontMetrics metrics = progressBar. getFontMetrics(progressBar.getFont()); Insets insets = progressBar.getInsets(); int y = insets.top; height = height - insets.top - insets.bottom; return y + (height + metrics.getAscent() - metrics.getLeading() - metrics.getDescent()) / 2; } return -1; } /** {@collect.stats} * Returns an enum indicating how the baseline of the component * changes as the size changes. * * @throws NullPointerException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public Component.BaselineResizeBehavior getBaselineResizeBehavior( JComponent c) { super.getBaselineResizeBehavior(c); if (progressBar.isStringPainted() && progressBar.getOrientation() == JProgressBar.HORIZONTAL) { return Component.BaselineResizeBehavior.CENTER_OFFSET; } return Component.BaselineResizeBehavior.OTHER; } // Many of the Basic*UI components have the following methods. // This component does not have these methods because *ProgressBarUI // is not a compound component and does not accept input. // // protected void installComponents() // protected void uninstallComponents() // protected void installKeyboardActions() // protected void uninstallKeyboardActions() protected Dimension getPreferredInnerHorizontal() { Dimension horizDim = (Dimension)DefaultLookup.get(progressBar, this, "ProgressBar.horizontalSize"); if (horizDim == null) { horizDim = new Dimension(146, 12); } return horizDim; } protected Dimension getPreferredInnerVertical() { Dimension vertDim = (Dimension)DefaultLookup.get(progressBar, this, "ProgressBar.verticalSize"); if (vertDim == null) { vertDim = new Dimension(12, 146); } return vertDim; } /** {@collect.stats} * The "selectionForeground" is the color of the text when it is painted * over a filled area of the progress bar. */ protected Color getSelectionForeground() { return selectionForeground; } /** {@collect.stats} * The "selectionBackground" is the color of the text when it is painted * over an unfilled area of the progress bar. */ protected Color getSelectionBackground() { return selectionBackground; } private int getCachedPercent() { return cachedPercent; } private void setCachedPercent(int cachedPercent) { this.cachedPercent = cachedPercent; } /** {@collect.stats} * Returns the width (if HORIZONTAL) or height (if VERTICAL) * of each of the indivdual cells/units to be rendered in the * progress bar. However, for text rendering simplification and * aesthetic considerations, this function will return 1 when * the progress string is being rendered. * * @return the value representing the spacing between cells * @see #setCellLength * @see JProgressBar#isStringPainted */ protected int getCellLength() { if (progressBar.isStringPainted()) { return 1; } else { return cellLength; } } protected void setCellLength(int cellLen) { this.cellLength = cellLen; } /** {@collect.stats} * Returns the spacing between each of the cells/units in the * progress bar. However, for text rendering simplification and * aesthetic considerations, this function will return 0 when * the progress string is being rendered. * * @return the value representing the spacing between cells * @see #setCellSpacing * @see JProgressBar#isStringPainted */ protected int getCellSpacing() { if (progressBar.isStringPainted()) { return 0; } else { return cellSpacing; } } protected void setCellSpacing(int cellSpace) { this.cellSpacing = cellSpace; } /** {@collect.stats} * This determines the amount of the progress bar that should be filled * based on the percent done gathered from the model. This is a common * operation so it was abstracted out. It assumes that your progress bar * is linear. That is, if you are making a circular progress indicator, * you will want to override this method. */ protected int getAmountFull(Insets b, int width, int height) { int amountFull = 0; BoundedRangeModel model = progressBar.getModel(); if ( (model.getMaximum() - model.getMinimum()) != 0) { if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) { amountFull = (int)Math.round(width * progressBar.getPercentComplete()); } else { amountFull = (int)Math.round(height * progressBar.getPercentComplete()); } } return amountFull; } /** {@collect.stats} * Delegates painting to one of two methods: * paintDeterminate or paintIndeterminate. */ public void paint(Graphics g, JComponent c) { if (progressBar.isIndeterminate()) { paintIndeterminate(g, c); } else { paintDeterminate(g, c); } } /** {@collect.stats} * Stores the position and size of * the bouncing box that would be painted for the current animation index * in <code>r</code> and returns <code>r</code>. * Subclasses that add to the painting performed * in this class's implementation of <code>paintIndeterminate</code> -- * to draw an outline around the bouncing box, for example -- * can use this method to get the location of the bouncing * box that was just painted. * By overriding this method, * you have complete control over the size and position * of the bouncing box, * without having to reimplement <code>paintIndeterminate</code>. * * @param r the Rectangle instance to be modified; * may be <code>null</code> * @return <code>null</code> if no box should be drawn; * otherwise, returns the passed-in rectangle * (if non-null) * or a new rectangle * * @see #setAnimationIndex * @since 1.4 */ protected Rectangle getBox(Rectangle r) { int currentFrame = getAnimationIndex(); int middleFrame = numFrames/2; if (sizeChanged() || delta == 0.0 || maxPosition == 0.0) { updateSizes(); } r = getGenericBox(r); if (r == null) { return null; } if (middleFrame <= 0) { return null; } //assert currentFrame >= 0 && currentFrame < numFrames if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) { if (currentFrame < middleFrame) { r.x = componentInnards.x + (int)Math.round(delta * (double)currentFrame); } else { r.x = maxPosition - (int)Math.round(delta * (currentFrame - middleFrame)); } } else { //VERTICAL indeterminate progress bar if (currentFrame < middleFrame) { r.y = componentInnards.y + (int)Math.round(delta * currentFrame); } else { r.y = maxPosition - (int)Math.round(delta * (currentFrame - middleFrame)); } } return r; } /** {@collect.stats} * Updates delta, max position. * Assumes componentInnards is correct (e.g. call after sizeChanged()). */ private void updateSizes() { int length = 0; if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) { length = getBoxLength(componentInnards.width, componentInnards.height); maxPosition = componentInnards.x + componentInnards.width - length; } else { //VERTICAL progress bar length = getBoxLength(componentInnards.height, componentInnards.width); maxPosition = componentInnards.y + componentInnards.height - length; } //If we're doing bouncing-box animation, update delta. delta = 2.0 * (double)maxPosition/(double)numFrames; } /** {@collect.stats} * Assumes that the component innards, max position, etc. are up-to-date. */ private Rectangle getGenericBox(Rectangle r) { if (r == null) { r = new Rectangle(); } if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) { r.width = getBoxLength(componentInnards.width, componentInnards.height); if (r.width < 0) { r = null; } else { r.height = componentInnards.height; r.y = componentInnards.y; } // end of HORIZONTAL } else { //VERTICAL progress bar r.height = getBoxLength(componentInnards.height, componentInnards.width); if (r.height < 0) { r = null; } else { r.width = componentInnards.width; r.x = componentInnards.x; } } // end of VERTICAL return r; } /** {@collect.stats} * Returns the length * of the "bouncing box" to be painted. * This method is invoked by the * default implementation of <code>paintIndeterminate</code> * to get the width (if the progress bar is horizontal) * or height (if vertical) of the box. * For example: * <blockquote> * <pre> *boxRect.width = getBoxLength(componentInnards.width, * componentInnards.height); * </pre> * </blockquote> * * @param availableLength the amount of space available * for the bouncing box to move in; * for a horizontal progress bar, * for example, * this should be * the inside width of the progress bar * (the component width minus borders) * @param otherDimension for a horizontal progress bar, this should be * the inside height of the progress bar; this * value might be used to constrain or determine * the return value * * @return the size of the box dimension being determined; * must be no larger than <code>availableLength</code> * * @see javax.swing.SwingUtilities#calculateInnerArea * @since 1.5 */ protected int getBoxLength(int availableLength, int otherDimension) { return (int)Math.round(availableLength/6.0); } /** {@collect.stats} * All purpose paint method that should do the right thing for all * linear bouncing-box progress bars. * Override this if you are making another kind of * progress bar. * * @see #paintDeterminate * * @since 1.4 */ protected void paintIndeterminate(Graphics g, JComponent c) { if (!(g instanceof Graphics2D)) { return; } Insets b = progressBar.getInsets(); // area for border int barRectWidth = progressBar.getWidth() - (b.right + b.left); int barRectHeight = progressBar.getHeight() - (b.top + b.bottom); if (barRectWidth <= 0 || barRectHeight <= 0) { return; } Graphics2D g2 = (Graphics2D)g; // Paint the bouncing box. boxRect = getBox(boxRect); if (boxRect != null) { g2.setColor(progressBar.getForeground()); g2.fillRect(boxRect.x, boxRect.y, boxRect.width, boxRect.height); } // Deal with possible text painting if (progressBar.isStringPainted()) { if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) { paintString(g2, b.left, b.top, barRectWidth, barRectHeight, boxRect.x, boxRect.width, b); } else { paintString(g2, b.left, b.top, barRectWidth, barRectHeight, boxRect.y, boxRect.height, b); } } } /** {@collect.stats} * All purpose paint method that should do the right thing for almost * all linear, determinate progress bars. By setting a few values in * the defaults * table, things should work just fine to paint your progress bar. * Naturally, override this if you are making a circular or * semi-circular progress bar. * * @see #paintIndeterminate * * @since 1.4 */ protected void paintDeterminate(Graphics g, JComponent c) { if (!(g instanceof Graphics2D)) { return; } Insets b = progressBar.getInsets(); // area for border int barRectWidth = progressBar.getWidth() - (b.right + b.left); int barRectHeight = progressBar.getHeight() - (b.top + b.bottom); if (barRectWidth <= 0 || barRectHeight <= 0) { return; } int cellLength = getCellLength(); int cellSpacing = getCellSpacing(); // amount of progress to draw int amountFull = getAmountFull(b, barRectWidth, barRectHeight); Graphics2D g2 = (Graphics2D)g; g2.setColor(progressBar.getForeground()); if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) { // draw the cells if (cellSpacing == 0 && amountFull > 0) { // draw one big Rect because there is no space between cells g2.setStroke(new BasicStroke((float)barRectHeight, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); } else { // draw each individual cell g2.setStroke(new BasicStroke((float)barRectHeight, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.f, new float[] { cellLength, cellSpacing }, 0.f)); } if (BasicGraphicsUtils.isLeftToRight(c)) { g2.drawLine(b.left, (barRectHeight/2) + b.top, amountFull + b.left, (barRectHeight/2) + b.top); } else { g2.drawLine((barRectWidth + b.left), (barRectHeight/2) + b.top, barRectWidth + b.left - amountFull, (barRectHeight/2) + b.top); } } else { // VERTICAL // draw the cells if (cellSpacing == 0 && amountFull > 0) { // draw one big Rect because there is no space between cells g2.setStroke(new BasicStroke((float)barRectWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); } else { // draw each individual cell g2.setStroke(new BasicStroke((float)barRectWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0f, new float[] { cellLength, cellSpacing }, 0f)); } g2.drawLine(barRectWidth/2 + b.left, b.top + barRectHeight, barRectWidth/2 + b.left, b.top + barRectHeight - amountFull); } // Deal with possible text painting if (progressBar.isStringPainted()) { paintString(g, b.left, b.top, barRectWidth, barRectHeight, amountFull, b); } } protected void paintString(Graphics g, int x, int y, int width, int height, int amountFull, Insets b) { if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) { if (BasicGraphicsUtils.isLeftToRight(progressBar)) { if (progressBar.isIndeterminate()) { boxRect = getBox(boxRect); paintString(g, x, y, width, height, boxRect.x, boxRect.width, b); } else { paintString(g, x, y, width, height, x, amountFull, b); } } else { paintString(g, x, y, width, height, x + width - amountFull, amountFull, b); } } else { if (progressBar.isIndeterminate()) { boxRect = getBox(boxRect); paintString(g, x, y, width, height, boxRect.y, boxRect.height, b); } else { paintString(g, x, y, width, height, y + height - amountFull, amountFull, b); } } } /** {@collect.stats} * Paints the progress string. * * @param g Graphics used for drawing. * @param x x location of bounding box * @param y y location of bounding box * @param width width of bounding box * @param height height of bounding box * @param fillStart start location, in x or y depending on orientation, * of the filled portion of the progress bar. * @param amountFull size of the fill region, either width or height * depending upon orientation. * @param b Insets of the progress bar. */ private void paintString(Graphics g, int x, int y, int width, int height, int fillStart, int amountFull, Insets b) { if (!(g instanceof Graphics2D)) { return; } Graphics2D g2 = (Graphics2D)g; String progressString = progressBar.getString(); g2.setFont(progressBar.getFont()); Point renderLocation = getStringPlacement(g2, progressString, x, y, width, height); Rectangle oldClip = g2.getClipBounds(); if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) { g2.setColor(getSelectionBackground()); SwingUtilities2.drawString(progressBar, g2, progressString, renderLocation.x, renderLocation.y); g2.setColor(getSelectionForeground()); g2.clipRect(fillStart, y, amountFull, height); SwingUtilities2.drawString(progressBar, g2, progressString, renderLocation.x, renderLocation.y); } else { // VERTICAL g2.setColor(getSelectionBackground()); AffineTransform rotate = AffineTransform.getRotateInstance(Math.PI/2); g2.setFont(progressBar.getFont().deriveFont(rotate)); renderLocation = getStringPlacement(g2, progressString, x, y, width, height); SwingUtilities2.drawString(progressBar, g2, progressString, renderLocation.x, renderLocation.y); g2.setColor(getSelectionForeground()); g2.clipRect(x, fillStart, width, amountFull); SwingUtilities2.drawString(progressBar, g2, progressString, renderLocation.x, renderLocation.y); } g2.setClip(oldClip); } /** {@collect.stats} * Designate the place where the progress string will be painted. * This implementation places it at the center of the progress * bar (in both x and y). Override this if you want to right, * left, top, or bottom align the progress string or if you need * to nudge it around for any reason. */ protected Point getStringPlacement(Graphics g, String progressString, int x,int y,int width,int height) { FontMetrics fontSizer = SwingUtilities2.getFontMetrics(progressBar, g, progressBar.getFont()); int stringWidth = SwingUtilities2.stringWidth(progressBar, fontSizer, progressString); if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) { return new Point(x + Math.round(width/2 - stringWidth/2), y + ((height + fontSizer.getAscent() - fontSizer.getLeading() - fontSizer.getDescent()) / 2)); } else { // VERTICAL return new Point(x + ((width - fontSizer.getAscent() + fontSizer.getLeading() + fontSizer.getDescent()) / 2), y + Math.round(height/2 - stringWidth/2)); } } public Dimension getPreferredSize(JComponent c) { Dimension size; Insets border = progressBar.getInsets(); FontMetrics fontSizer = progressBar.getFontMetrics( progressBar.getFont()); if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) { size = new Dimension(getPreferredInnerHorizontal()); // Ensure that the progress string will fit if (progressBar.isStringPainted()) { // I'm doing this for completeness. String progString = progressBar.getString(); int stringWidth = SwingUtilities2.stringWidth( progressBar, fontSizer, progString); if (stringWidth > size.width) { size.width = stringWidth; } // This uses both Height and Descent to be sure that // there is more than enough room in the progress bar // for everything. // This does have a strange dependency on // getStringPlacememnt() in a funny way. int stringHeight = fontSizer.getHeight() + fontSizer.getDescent(); if (stringHeight > size.height) { size.height = stringHeight; } } } else { size = new Dimension(getPreferredInnerVertical()); // Ensure that the progress string will fit. if (progressBar.isStringPainted()) { String progString = progressBar.getString(); int stringHeight = fontSizer.getHeight() + fontSizer.getDescent(); if (stringHeight > size.width) { size.width = stringHeight; } // This is also for completeness. int stringWidth = SwingUtilities2.stringWidth( progressBar, fontSizer, progString); if (stringWidth > size.height) { size.height = stringWidth; } } } size.width += border.left + border.right; size.height += border.top + border.bottom; return size; } /** {@collect.stats} * The Minimum size for this component is 10. The rationale here * is that there should be at least one pixel per 10 percent. */ public Dimension getMinimumSize(JComponent c) { Dimension pref = getPreferredSize(progressBar); if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) { pref.width = 10; } else { pref.height = 10; } return pref; } public Dimension getMaximumSize(JComponent c) { Dimension pref = getPreferredSize(progressBar); if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) { pref.width = Short.MAX_VALUE; } else { pref.height = Short.MAX_VALUE; } return pref; } /** {@collect.stats} * Gets the index of the current animation frame. * * @since 1.4 */ protected int getAnimationIndex() { return animationIndex; } /** {@collect.stats} * Returns the number of frames for the complete animation loop * used by an indeterminate JProgessBar. The progress chunk will go * from one end to the other and back during the entire loop. This * visual behavior may be changed by subclasses in other Look and Feels. * * @return the number of frames * @since 1.6 */ protected final int getFrameCount() { return numFrames; } /** {@collect.stats} * Sets the index of the current animation frame * to the specified value and requests that the * progress bar be repainted. * Subclasses that don't use the default painting code * might need to override this method * to change the way that the <code>repaint</code> method * is invoked. * * @param newValue the new animation index; no checking * is performed on its value * @see #incrementAnimationIndex * * @since 1.4 */ protected void setAnimationIndex(int newValue) { if (animationIndex != newValue) { if (sizeChanged()) { animationIndex = newValue; maxPosition = 0; //needs to be recalculated delta = 0.0; //needs to be recalculated progressBar.repaint(); return; } //Get the previous box drawn. nextPaintRect = getBox(nextPaintRect); //Update the frame number. animationIndex = newValue; //Get the next box to draw. if (nextPaintRect != null) { boxRect = getBox(boxRect); if (boxRect != null) { nextPaintRect.add(boxRect); } } } else { //animationIndex == newValue return; } if (nextPaintRect != null) { progressBar.repaint(nextPaintRect); } else { progressBar.repaint(); } } private boolean sizeChanged() { if ((oldComponentInnards == null) || (componentInnards == null)) { return true; } oldComponentInnards.setRect(componentInnards); componentInnards = SwingUtilities.calculateInnerArea(progressBar, componentInnards); return !oldComponentInnards.equals(componentInnards); } /** {@collect.stats} * Sets the index of the current animation frame, * to the next valid value, * which results in the progress bar being repainted. * The next valid value is, by default, * the current animation index plus one. * If the new value would be too large, * this method sets the index to 0. * Subclasses might need to override this method * to ensure that the index does not go over * the number of frames needed for the particular * progress bar instance. * This method is invoked by the default animation thread * every <em>X</em> milliseconds, * where <em>X</em> is specified by the "ProgressBar.repaintInterval" * UI default. * * @see #setAnimationIndex * @since 1.4 */ protected void incrementAnimationIndex() { int newValue = getAnimationIndex() + 1; if (newValue < numFrames) { setAnimationIndex(newValue); } else { setAnimationIndex(0); } } /** {@collect.stats} * Returns the desired number of milliseconds between repaints. * This value is meaningful * only if the progress bar is in indeterminate mode. * The repaint interval determines how often the * default animation thread's timer is fired. * It's also used by the default indeterminate progress bar * painting code when determining * how far to move the bouncing box per frame. * The repaint interval is specified by * the "ProgressBar.repaintInterval" UI default. * * @return the repaint interval, in milliseconds */ private int getRepaintInterval() { return repaintInterval; } private int initRepaintInterval() { repaintInterval = DefaultLookup.getInt(progressBar, this, "ProgressBar.repaintInterval", 50); return repaintInterval; } /** {@collect.stats} * Returns the number of milliseconds per animation cycle. * This value is meaningful * only if the progress bar is in indeterminate mode. * The cycle time is used by the default indeterminate progress bar * painting code when determining * how far to move the bouncing box per frame. * The cycle time is specified by * the "ProgressBar.cycleTime" UI default * and adjusted, if necessary, * by the initIndeterminateDefaults method. * * @return the cycle time, in milliseconds */ private int getCycleTime() { return cycleTime; } private int initCycleTime() { cycleTime = DefaultLookup.getInt(progressBar, this, "ProgressBar.cycleTime", 3000); return cycleTime; } /** {@collect.stats} Initialize cycleTime, repaintInterval, numFrames, animationIndex. */ private void initIndeterminateDefaults() { initRepaintInterval(); //initialize repaint interval initCycleTime(); //initialize cycle length // Make sure repaintInterval is reasonable. if (repaintInterval <= 0) { repaintInterval = 100; } // Make sure cycleTime is reasonable. if (repaintInterval > cycleTime) { cycleTime = repaintInterval * 20; } else { // Force cycleTime to be a even multiple of repaintInterval. int factor = (int)Math.ceil( ((double)cycleTime) / ((double)repaintInterval*2)); cycleTime = repaintInterval*factor*2; } } /** {@collect.stats} * Invoked by PropertyChangeHandler. * * NOTE: This might not be invoked until after the first * paintIndeterminate call. */ private void initIndeterminateValues() { initIndeterminateDefaults(); //assert cycleTime/repaintInterval is a whole multiple of 2. numFrames = cycleTime/repaintInterval; initAnimationIndex(); boxRect = new Rectangle(); nextPaintRect = new Rectangle(); componentInnards = new Rectangle(); oldComponentInnards = new Rectangle(); // we only bother installing the HierarchyChangeListener if we // are indeterminate progressBar.addHierarchyListener(getHandler()); // start the animation thread if necessary if (progressBar.isDisplayable()) { startAnimationTimer(); } } /** {@collect.stats} Invoked by PropertyChangeHandler. */ private void cleanUpIndeterminateValues() { // stop the animation thread if necessary if (progressBar.isDisplayable()) { stopAnimationTimer(); } cycleTime = repaintInterval = 0; numFrames = animationIndex = 0; maxPosition = 0; delta = 0.0; boxRect = nextPaintRect = null; componentInnards = oldComponentInnards = null; progressBar.removeHierarchyListener(getHandler()); } // Called from initIndeterminateValues to initialize the animation index. // This assumes that numFrames is set to a correct value. private void initAnimationIndex() { if ((progressBar.getOrientation() == JProgressBar.HORIZONTAL) && (BasicGraphicsUtils.isLeftToRight(progressBar))) { // If this is a left-to-right progress bar, // start at the first frame. setAnimationIndex(0); } else { // If we go right-to-left or vertically, start at the right/bottom. setAnimationIndex(numFrames/2); } } // // Animation Thread // /** {@collect.stats} * Implements an animation thread that invokes repaint * at a fixed rate. If ADJUSTTIMER is true, this thread * will continuously adjust the repaint interval to * try to make the actual time between repaints match * the requested rate. */ private class Animator implements ActionListener { private Timer timer; private long previousDelay; //used to tune the repaint interval private int interval; //the fixed repaint interval private long lastCall; //the last time actionPerformed was called private int MINIMUM_DELAY = 5; /** {@collect.stats} * Creates a timer if one doesn't already exist, * then starts the timer thread. */ private void start(int interval) { previousDelay = interval; lastCall = 0; if (timer == null) { timer = new Timer(interval, this); } else { timer.setDelay(interval); } if (ADJUSTTIMER) { timer.setRepeats(false); timer.setCoalesce(false); } timer.start(); } /** {@collect.stats} * Stops the timer thread. */ private void stop() { timer.stop(); } /** {@collect.stats} * Reacts to the timer's action events. */ public void actionPerformed(ActionEvent e) { if (ADJUSTTIMER) { long time = System.currentTimeMillis(); if (lastCall > 0) { //adjust nextDelay //XXX maybe should cache this after a while //actual = time - lastCall //difference = actual - interval //nextDelay = previousDelay - difference // = previousDelay - (time - lastCall - interval) int nextDelay = (int)(previousDelay - time + lastCall + getRepaintInterval()); if (nextDelay < MINIMUM_DELAY) { nextDelay = MINIMUM_DELAY; } timer.setInitialDelay(nextDelay); previousDelay = nextDelay; } timer.start(); lastCall = time; } incrementAnimationIndex(); //paint next frame } } /** {@collect.stats} * This inner class is marked &quot;public&quot; due to a compiler bug. * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicProgressBarUI. */ public class ChangeHandler implements ChangeListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void stateChanged(ChangeEvent e) { getHandler().stateChanged(e); } } private class Handler implements ChangeListener, PropertyChangeListener, HierarchyListener { // ChangeListener public void stateChanged(ChangeEvent e) { BoundedRangeModel model = progressBar.getModel(); int newRange = model.getMaximum() - model.getMinimum(); int newPercent; int oldPercent = getCachedPercent(); if (newRange > 0) { newPercent = (int)((100 * (long)model.getValue()) / newRange); } else { newPercent = 0; } if (newPercent != oldPercent) { setCachedPercent(newPercent); progressBar.repaint(); } } // PropertyChangeListener public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); if ("indeterminate" == prop) { if (progressBar.isIndeterminate()) { initIndeterminateValues(); } else { //clean up cleanUpIndeterminateValues(); } progressBar.repaint(); } } // we don't want the animation to keep running if we're not displayable public void hierarchyChanged(HierarchyEvent he) { if ((he.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0) { if (progressBar.isIndeterminate()) { if (progressBar.isDisplayable()) { startAnimationTimer(); } else { stopAnimationTimer(); } } } } } }
Java
/* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.Toolkit; import java.awt.event.*; import java.awt.dnd.DragSource; import javax.swing.*; import sun.awt.dnd.SunDragSourceContextPeer; import sun.awt.AppContext; /** {@collect.stats} * Drag gesture recognition support for classes that have a * <code>TransferHandler</code>. The gesture for a drag in this class is a mouse * press followed by movement by <code>DragSource.getDragThreshold()</code> * pixels. An instance of this class is maintained per AppContext, and the * public static methods call into the appropriate instance. * * @author Shannon Hickey */ class DragRecognitionSupport { private int motionThreshold; private MouseEvent dndArmedEvent; private JComponent component; /** {@collect.stats} * This interface allows us to pass in a handler to mouseDragged, * so that we can be notified immediately before a drag begins. */ public static interface BeforeDrag { public void dragStarting(MouseEvent me); } /** {@collect.stats} * Returns the DragRecognitionSupport for the caller's AppContext. */ private static DragRecognitionSupport getDragRecognitionSupport() { DragRecognitionSupport support = (DragRecognitionSupport)AppContext.getAppContext(). get(DragRecognitionSupport.class); if (support == null) { support = new DragRecognitionSupport(); AppContext.getAppContext().put(DragRecognitionSupport.class, support); } return support; } /** {@collect.stats} * Returns whether or not the event is potentially part of a drag sequence. */ public static boolean mousePressed(MouseEvent me) { return ((DragRecognitionSupport)getDragRecognitionSupport()). mousePressedImpl(me); } /** {@collect.stats} * If a dnd recognition has been going on, return the MouseEvent * that started the recognition. Otherwise, return null. */ public static MouseEvent mouseReleased(MouseEvent me) { return ((DragRecognitionSupport)getDragRecognitionSupport()). mouseReleasedImpl(me); } /** {@collect.stats} * Returns whether or not a drag gesture recognition is ongoing. */ public static boolean mouseDragged(MouseEvent me, BeforeDrag bd) { return ((DragRecognitionSupport)getDragRecognitionSupport()). mouseDraggedImpl(me, bd); } private void clearState() { dndArmedEvent = null; component = null; } private int mapDragOperationFromModifiers(MouseEvent me, TransferHandler th) { if (th == null || !SwingUtilities.isLeftMouseButton(me)) { return TransferHandler.NONE; } return SunDragSourceContextPeer. convertModifiersToDropAction(me.getModifiersEx(), th.getSourceActions(component)); } /** {@collect.stats} * Returns whether or not the event is potentially part of a drag sequence. */ private boolean mousePressedImpl(MouseEvent me) { component = (JComponent)me.getSource(); if (mapDragOperationFromModifiers(me, component.getTransferHandler()) != TransferHandler.NONE) { motionThreshold = DragSource.getDragThreshold(); dndArmedEvent = me; return true; } clearState(); return false; } /** {@collect.stats} * If a dnd recognition has been going on, return the MouseEvent * that started the recognition. Otherwise, return null. */ private MouseEvent mouseReleasedImpl(MouseEvent me) { /* no recognition has been going on */ if (dndArmedEvent == null) { return null; } MouseEvent retEvent = null; if (me.getSource() == component) { retEvent = dndArmedEvent; } // else component has changed unexpectedly, so return null clearState(); return retEvent; } /** {@collect.stats} * Returns whether or not a drag gesture recognition is ongoing. */ private boolean mouseDraggedImpl(MouseEvent me, BeforeDrag bd) { /* no recognition is in progress */ if (dndArmedEvent == null) { return false; } /* component has changed unexpectedly, so bail */ if (me.getSource() != component) { clearState(); return false; } int dx = Math.abs(me.getX() - dndArmedEvent.getX()); int dy = Math.abs(me.getY() - dndArmedEvent.getY()); if ((dx > motionThreshold) || (dy > motionThreshold)) { TransferHandler th = component.getTransferHandler(); int action = mapDragOperationFromModifiers(me, th); if (action != TransferHandler.NONE) { /* notify the BeforeDrag instance */ if (bd != null) { bd.dragStarting(dndArmedEvent); } th.exportAsDrag(component, dndArmedEvent, action); clearState(); } } return true; } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import java.awt.event.*; import java.beans.*; import java.net.URL; import java.net.MalformedURLException; import javax.swing.*; import javax.swing.text.*; import javax.swing.text.html.*; import javax.swing.plaf.*; import javax.swing.border.*; /** {@collect.stats} * Provides the look and feel for a JEditorPane. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Timothy Prinzing */ public class BasicEditorPaneUI extends BasicTextUI { /** {@collect.stats} * Creates a UI for the JTextPane. * * @param c the JTextPane component * @return the UI */ public static ComponentUI createUI(JComponent c) { return new BasicEditorPaneUI(); } /** {@collect.stats} * Creates a new BasicEditorPaneUI. */ public BasicEditorPaneUI() { super(); } /** {@collect.stats} * Fetches the name used as a key to lookup properties through the * UIManager. This is used as a prefix to all the standard * text properties. * * @return the name ("EditorPane") */ protected String getPropertyPrefix() { return "EditorPane"; } /** {@collect.stats} *{@inheritDoc} * * @since 1.5 */ public void installUI(JComponent c) { super.installUI(c); updateDisplayProperties(c.getFont(), c.getForeground()); } /** {@collect.stats} *{@inheritDoc} * * @since 1.5 */ public void uninstallUI(JComponent c) { cleanDisplayProperties(); super.uninstallUI(c); } /** {@collect.stats} * Fetches the EditorKit for the UI. This is whatever is * currently set in the associated JEditorPane. * * @return the editor capabilities * @see TextUI#getEditorKit */ public EditorKit getEditorKit(JTextComponent tc) { JEditorPane pane = (JEditorPane) getComponent(); return pane.getEditorKit(); } /** {@collect.stats} * Fetch an action map to use. The map for a JEditorPane * is not shared because it changes with the EditorKit. */ ActionMap getActionMap() { ActionMap am = new ActionMapUIResource(); am.put("requestFocus", new FocusAction()); EditorKit editorKit = getEditorKit(getComponent()); if (editorKit != null) { Action[] actions = editorKit.getActions(); if (actions != null) { addActions(am, actions); } } am.put(TransferHandler.getCutAction().getValue(Action.NAME), TransferHandler.getCutAction()); am.put(TransferHandler.getCopyAction().getValue(Action.NAME), TransferHandler.getCopyAction()); am.put(TransferHandler.getPasteAction().getValue(Action.NAME), TransferHandler.getPasteAction()); return am; } /** {@collect.stats} * This method gets called when a bound property is changed * on the associated JTextComponent. This is a hook * which UI implementations may change to reflect how the * UI displays bound properties of JTextComponent subclasses. * This is implemented to rebuild the ActionMap based upon an * EditorKit change. * * @param evt the property change event */ protected void propertyChange(PropertyChangeEvent evt) { super.propertyChange(evt); String name = evt.getPropertyName(); if ("editorKit".equals(name)) { ActionMap map = SwingUtilities.getUIActionMap(getComponent()); if (map != null) { Object oldValue = evt.getOldValue(); if (oldValue instanceof EditorKit) { Action[] actions = ((EditorKit)oldValue).getActions(); if (actions != null) { removeActions(map, actions); } } Object newValue = evt.getNewValue(); if (newValue instanceof EditorKit) { Action[] actions = ((EditorKit)newValue).getActions(); if (actions != null) { addActions(map, actions); } } } updateFocusTraversalKeys(); } else if ("editable".equals(name)) { updateFocusTraversalKeys(); } else if ("foreground".equals(name) || "font".equals(name) || "document".equals(name) || JEditorPane.W3C_LENGTH_UNITS.equals(name) || JEditorPane.HONOR_DISPLAY_PROPERTIES.equals(name) ) { JComponent c = getComponent(); updateDisplayProperties(c.getFont(), c.getForeground()); if ( JEditorPane.W3C_LENGTH_UNITS.equals(name) || JEditorPane.HONOR_DISPLAY_PROPERTIES.equals(name) ) { modelChanged(); } if ("foreground".equals(name)) { Object honorDisplayPropertiesObject = c. getClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES); boolean honorDisplayProperties = false; if (honorDisplayPropertiesObject instanceof Boolean) { honorDisplayProperties = ((Boolean)honorDisplayPropertiesObject).booleanValue(); } if (honorDisplayProperties) { modelChanged(); } } } } void removeActions(ActionMap map, Action[] actions) { int n = actions.length; for (int i = 0; i < n; i++) { Action a = actions[i]; map.remove(a.getValue(Action.NAME)); } } void addActions(ActionMap map, Action[] actions) { int n = actions.length; for (int i = 0; i < n; i++) { Action a = actions[i]; map.put(a.getValue(Action.NAME), a); } } void updateDisplayProperties(Font font, Color fg) { JComponent c = getComponent(); Object honorDisplayPropertiesObject = c. getClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES); boolean honorDisplayProperties = false; Object w3cLengthUnitsObject = c.getClientProperty(JEditorPane. W3C_LENGTH_UNITS); boolean w3cLengthUnits = false; if (honorDisplayPropertiesObject instanceof Boolean) { honorDisplayProperties = ((Boolean)honorDisplayPropertiesObject).booleanValue(); } if (w3cLengthUnitsObject instanceof Boolean) { w3cLengthUnits = ((Boolean)w3cLengthUnitsObject).booleanValue(); } if (this instanceof BasicTextPaneUI || honorDisplayProperties) { //using equals because can not use UIResource for Boolean Document doc = getComponent().getDocument(); if (doc instanceof StyledDocument) { if (doc instanceof HTMLDocument && honorDisplayProperties) { updateCSS(font, fg); } else { updateStyle(font, fg); } } } else { cleanDisplayProperties(); } if ( w3cLengthUnits ) { Document doc = getComponent().getDocument(); if (doc instanceof HTMLDocument) { StyleSheet documentStyleSheet = ((HTMLDocument)doc).getStyleSheet(); documentStyleSheet.addRule("W3C_LENGTH_UNITS_ENABLE"); } } else { Document doc = getComponent().getDocument(); if (doc instanceof HTMLDocument) { StyleSheet documentStyleSheet = ((HTMLDocument)doc).getStyleSheet(); documentStyleSheet.addRule("W3C_LENGTH_UNITS_DISABLE"); } } } /** {@collect.stats} * Attribute key to reference the default font. * used in javax.swing.text.StyleContext.getFont * to resolve the default font. */ private static final String FONT_ATTRIBUTE_KEY = "FONT_ATTRIBUTE_KEY"; void cleanDisplayProperties() { Document document = getComponent().getDocument(); if (document instanceof HTMLDocument) { StyleSheet documentStyleSheet = ((HTMLDocument)document).getStyleSheet(); StyleSheet[] styleSheets = documentStyleSheet.getStyleSheets(); if (styleSheets != null) { for (StyleSheet s : styleSheets) { if (s instanceof StyleSheetUIResource) { documentStyleSheet.removeStyleSheet(s); documentStyleSheet.addRule("BASE_SIZE_DISABLE"); break; } } } Style style = ((StyledDocument) document).getStyle(StyleContext.DEFAULT_STYLE); if (style.getAttribute(FONT_ATTRIBUTE_KEY) != null) { style.removeAttribute(FONT_ATTRIBUTE_KEY); } } } static class StyleSheetUIResource extends StyleSheet implements UIResource { } private void updateCSS(Font font, Color fg) { JTextComponent component = getComponent(); Document document = component.getDocument(); if (document instanceof HTMLDocument) { StyleSheet styleSheet = new StyleSheetUIResource(); StyleSheet documentStyleSheet = ((HTMLDocument)document).getStyleSheet(); StyleSheet[] styleSheets = documentStyleSheet.getStyleSheets(); if (styleSheets != null) { for (StyleSheet s : styleSheets) { if (s instanceof StyleSheetUIResource) { documentStyleSheet.removeStyleSheet(s); } } } String cssRule = sun.swing. SwingUtilities2.displayPropertiesToCSS(font, fg); styleSheet.addRule(cssRule); documentStyleSheet.addStyleSheet(styleSheet); documentStyleSheet.addRule("BASE_SIZE " + component.getFont().getSize()); Style style = ((StyledDocument) document).getStyle(StyleContext.DEFAULT_STYLE); if (! font.equals(style.getAttribute(FONT_ATTRIBUTE_KEY))) { style.addAttribute(FONT_ATTRIBUTE_KEY, font); } } } private void updateStyle(Font font, Color fg) { updateFont(font); updateForeground(fg); } /** {@collect.stats} * Update the color in the default style of the document. * * @param color the new color to use or null to remove the color attribute * from the document's style */ private void updateForeground(Color color) { StyledDocument doc = (StyledDocument)getComponent().getDocument(); Style style = doc.getStyle(StyleContext.DEFAULT_STYLE); if (style == null) { return; } if (color == null) { if (style.getAttribute(StyleConstants.Foreground) != null) { style.removeAttribute(StyleConstants.Foreground); } } else { if (! color.equals(StyleConstants.getForeground(style))) { StyleConstants.setForeground(style, color); } } } /** {@collect.stats} * Update the font in the default style of the document. * * @param font the new font to use or null to remove the font attribute * from the document's style */ private void updateFont(Font font) { StyledDocument doc = (StyledDocument)getComponent().getDocument(); Style style = doc.getStyle(StyleContext.DEFAULT_STYLE); if (style == null) { return; } String fontFamily = (String) style.getAttribute(StyleConstants.FontFamily); Integer fontSize = (Integer) style.getAttribute(StyleConstants.FontSize); Boolean isBold = (Boolean) style.getAttribute(StyleConstants.Bold); Boolean isItalic = (Boolean) style.getAttribute(StyleConstants.Italic); Font fontAttribute = (Font) style.getAttribute(FONT_ATTRIBUTE_KEY); if (font == null) { if (fontFamily != null) { style.removeAttribute(StyleConstants.FontFamily); } if (fontSize != null) { style.removeAttribute(StyleConstants.FontSize); } if (isBold != null) { style.removeAttribute(StyleConstants.Bold); } if (isItalic != null) { style.removeAttribute(StyleConstants.Italic); } if (fontAttribute != null) { style.removeAttribute(FONT_ATTRIBUTE_KEY); } } else { if (! font.getName().equals(fontFamily)) { StyleConstants.setFontFamily(style, font.getName()); } if (fontSize == null || fontSize.intValue() != font.getSize()) { StyleConstants.setFontSize(style, font.getSize()); } if (isBold == null || isBold.booleanValue() != font.isBold()) { StyleConstants.setBold(style, font.isBold()); } if (isItalic == null || isItalic.booleanValue() != font.isItalic()) { StyleConstants.setItalic(style, font.isItalic()); } if (! font.equals(fontAttribute)) { style.addAttribute(FONT_ATTRIBUTE_KEY, font); } } } }
Java
/* * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import sun.swing.SwingUtilities2; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.*; import javax.swing.text.View; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.util.Vector; import java.util.Hashtable; import sun.swing.DefaultLookup; import sun.swing.UIAction; /** {@collect.stats} * A Basic L&F implementation of TabbedPaneUI. * * @author Amy Fowler * @author Philip Milne * @author Steve Wilson * @author Tom Santos * @author Dave Moore */ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants { // Instance variables initialized at installation protected JTabbedPane tabPane; protected Color highlight; protected Color lightHighlight; protected Color shadow; protected Color darkShadow; protected Color focus; private Color selectedColor; protected int textIconGap; protected int tabRunOverlay; protected Insets tabInsets; protected Insets selectedTabPadInsets; protected Insets tabAreaInsets; protected Insets contentBorderInsets; private boolean tabsOverlapBorder; private boolean tabsOpaque = true; private boolean contentOpaque = true; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected KeyStroke upKey; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected KeyStroke downKey; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected KeyStroke leftKey; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected KeyStroke rightKey; // Transient variables (recalculated each time TabbedPane is layed out) protected int tabRuns[] = new int[10]; protected int runCount = 0; protected int selectedRun = -1; protected Rectangle rects[] = new Rectangle[0]; protected int maxTabHeight; protected int maxTabWidth; // Listeners protected ChangeListener tabChangeListener; protected PropertyChangeListener propertyChangeListener; protected MouseListener mouseListener; protected FocusListener focusListener; // Private instance data private Insets currentPadInsets = new Insets(0,0,0,0); private Insets currentTabAreaInsets = new Insets(0,0,0,0); private Component visibleComponent; // PENDING(api): See comment for ContainerHandler private Vector htmlViews; private Hashtable mnemonicToIndexMap; /** {@collect.stats} * InputMap used for mnemonics. Only non-null if the JTabbedPane has * mnemonics associated with it. Lazily created in initMnemonics. */ private InputMap mnemonicInputMap; // For use when tabLayoutPolicy = SCROLL_TAB_LAYOUT private ScrollableTabSupport tabScroller; private TabContainer tabContainer; /** {@collect.stats} * A rectangle used for general layout calculations in order * to avoid constructing many new Rectangles on the fly. */ protected transient Rectangle calcRect = new Rectangle(0,0,0,0); /** {@collect.stats} * Tab that has focus. */ private int focusIndex; /** {@collect.stats} * Combined listeners. */ private Handler handler; /** {@collect.stats} * Index of the tab the mouse is over. */ private int rolloverTabIndex; /** {@collect.stats} * This is set to true when a component is added/removed from the tab * pane and set to false when layout happens. If true it indicates that * tabRuns is not valid and shouldn't be used. */ private boolean isRunsDirty; private boolean calculatedBaseline; private int baseline; // UI creation public static ComponentUI createUI(JComponent c) { return new BasicTabbedPaneUI(); } static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.NEXT)); map.put(new Actions(Actions.PREVIOUS)); map.put(new Actions(Actions.RIGHT)); map.put(new Actions(Actions.LEFT)); map.put(new Actions(Actions.UP)); map.put(new Actions(Actions.DOWN)); map.put(new Actions(Actions.PAGE_UP)); map.put(new Actions(Actions.PAGE_DOWN)); map.put(new Actions(Actions.REQUEST_FOCUS)); map.put(new Actions(Actions.REQUEST_FOCUS_FOR_VISIBLE)); map.put(new Actions(Actions.SET_SELECTED)); map.put(new Actions(Actions.SELECT_FOCUSED)); map.put(new Actions(Actions.SCROLL_FORWARD)); map.put(new Actions(Actions.SCROLL_BACKWARD)); } // UI Installation/De-installation public void installUI(JComponent c) { this.tabPane = (JTabbedPane)c; calculatedBaseline = false; rolloverTabIndex = -1; focusIndex = -1; c.setLayout(createLayoutManager()); installComponents(); installDefaults(); installListeners(); installKeyboardActions(); } public void uninstallUI(JComponent c) { uninstallKeyboardActions(); uninstallListeners(); uninstallDefaults(); uninstallComponents(); c.setLayout(null); this.tabPane = null; } /** {@collect.stats} * Invoked by <code>installUI</code> to create * a layout manager object to manage * the <code>JTabbedPane</code>. * * @return a layout manager object * * @see TabbedPaneLayout * @see javax.swing.JTabbedPane#getTabLayoutPolicy */ protected LayoutManager createLayoutManager() { if (tabPane.getTabLayoutPolicy() == JTabbedPane.SCROLL_TAB_LAYOUT) { return new TabbedPaneScrollLayout(); } else { /* WRAP_TAB_LAYOUT */ return new TabbedPaneLayout(); } } /* In an attempt to preserve backward compatibility for programs * which have extended BasicTabbedPaneUI to do their own layout, the * UI uses the installed layoutManager (and not tabLayoutPolicy) to * determine if scrollTabLayout is enabled. */ private boolean scrollableTabLayoutEnabled() { return (tabPane.getLayout() instanceof TabbedPaneScrollLayout); } /** {@collect.stats} * Creates and installs any required subcomponents for the JTabbedPane. * Invoked by installUI. * * @since 1.4 */ protected void installComponents() { if (scrollableTabLayoutEnabled()) { if (tabScroller == null) { tabScroller = new ScrollableTabSupport(tabPane.getTabPlacement()); tabPane.add(tabScroller.viewport); } } installTabContainer(); } private void installTabContainer() { for (int i = 0; i < tabPane.getTabCount(); i++) { Component tabComponent = tabPane.getTabComponentAt(i); if (tabComponent != null) { if(tabContainer == null) { tabContainer = new TabContainer(); } tabContainer.add(tabComponent); } } if(tabContainer == null) { return; } if (scrollableTabLayoutEnabled()) { tabScroller.tabPanel.add(tabContainer); } else { tabPane.add(tabContainer); } } /** {@collect.stats} * Creates and returns a JButton that will provide the user * with a way to scroll the tabs in a particular direction. The * returned JButton must be instance of UIResource. * * @param direction One of the SwingConstants constants: * SOUTH, NORTH, EAST or WEST * @return Widget for user to * @see javax.swing.JTabbedPane#setTabPlacement * @see javax.swing.SwingConstants * @throws IllegalArgumentException if direction is not one of * NORTH, SOUTH, EAST or WEST * @since 1.5 */ protected JButton createScrollButton(int direction) { if (direction != SOUTH && direction != NORTH && direction != EAST && direction != WEST) { throw new IllegalArgumentException("Direction must be one of: " + "SOUTH, NORTH, EAST or WEST"); } return new ScrollableTabButton(direction); } /** {@collect.stats} * Removes any installed subcomponents from the JTabbedPane. * Invoked by uninstallUI. * * @since 1.4 */ protected void uninstallComponents() { uninstallTabContainer(); if (scrollableTabLayoutEnabled()) { tabPane.remove(tabScroller.viewport); tabPane.remove(tabScroller.scrollForwardButton); tabPane.remove(tabScroller.scrollBackwardButton); tabScroller = null; } } private void uninstallTabContainer() { if(tabContainer == null) { return; } // Remove all the tabComponents, making sure not to notify // the tabbedpane. tabContainer.notifyTabbedPane = false; tabContainer.removeAll(); if(scrollableTabLayoutEnabled()) { tabContainer.remove(tabScroller.croppedEdge); tabScroller.tabPanel.remove(tabContainer); } else { tabPane.remove(tabContainer); } tabContainer = null; } protected void installDefaults() { LookAndFeel.installColorsAndFont(tabPane, "TabbedPane.background", "TabbedPane.foreground", "TabbedPane.font"); highlight = UIManager.getColor("TabbedPane.light"); lightHighlight = UIManager.getColor("TabbedPane.highlight"); shadow = UIManager.getColor("TabbedPane.shadow"); darkShadow = UIManager.getColor("TabbedPane.darkShadow"); focus = UIManager.getColor("TabbedPane.focus"); selectedColor = UIManager.getColor("TabbedPane.selected"); textIconGap = UIManager.getInt("TabbedPane.textIconGap"); tabInsets = UIManager.getInsets("TabbedPane.tabInsets"); selectedTabPadInsets = UIManager.getInsets("TabbedPane.selectedTabPadInsets"); tabAreaInsets = UIManager.getInsets("TabbedPane.tabAreaInsets"); tabsOverlapBorder = UIManager.getBoolean("TabbedPane.tabsOverlapBorder"); contentBorderInsets = UIManager.getInsets("TabbedPane.contentBorderInsets"); tabRunOverlay = UIManager.getInt("TabbedPane.tabRunOverlay"); tabsOpaque = UIManager.getBoolean("TabbedPane.tabsOpaque"); contentOpaque = UIManager.getBoolean("TabbedPane.contentOpaque"); Object opaque = UIManager.get("TabbedPane.opaque"); if (opaque == null) { opaque = Boolean.FALSE; } LookAndFeel.installProperty(tabPane, "opaque", opaque); // Fix for 6711145 BasicTabbedPanuUI should not throw a NPE if these // keys are missing. So we are setting them to there default values here // if the keys are missing. if (tabInsets == null) tabInsets = new Insets(0,4,1,4); if (selectedTabPadInsets == null) selectedTabPadInsets = new Insets(2,2,2,1); if (tabAreaInsets == null) tabAreaInsets = new Insets(3,2,0,2); if (contentBorderInsets == null) contentBorderInsets = new Insets(2,2,3,3); } protected void uninstallDefaults() { highlight = null; lightHighlight = null; shadow = null; darkShadow = null; focus = null; tabInsets = null; selectedTabPadInsets = null; tabAreaInsets = null; contentBorderInsets = null; } protected void installListeners() { if ((propertyChangeListener = createPropertyChangeListener()) != null) { tabPane.addPropertyChangeListener(propertyChangeListener); } if ((tabChangeListener = createChangeListener()) != null) { tabPane.addChangeListener(tabChangeListener); } if ((mouseListener = createMouseListener()) != null) { tabPane.addMouseListener(mouseListener); } tabPane.addMouseMotionListener(getHandler()); if ((focusListener = createFocusListener()) != null) { tabPane.addFocusListener(focusListener); } tabPane.addContainerListener(getHandler()); if (tabPane.getTabCount()>0) { htmlViews = createHTMLVector(); } } protected void uninstallListeners() { if (mouseListener != null) { tabPane.removeMouseListener(mouseListener); mouseListener = null; } tabPane.removeMouseMotionListener(getHandler()); if (focusListener != null) { tabPane.removeFocusListener(focusListener); focusListener = null; } tabPane.removeContainerListener(getHandler()); if (htmlViews!=null) { htmlViews.removeAllElements(); htmlViews = null; } if (tabChangeListener != null) { tabPane.removeChangeListener(tabChangeListener); tabChangeListener = null; } if (propertyChangeListener != null) { tabPane.removePropertyChangeListener(propertyChangeListener); propertyChangeListener = null; } handler = null; } protected MouseListener createMouseListener() { return getHandler(); } protected FocusListener createFocusListener() { return getHandler(); } protected ChangeListener createChangeListener() { return getHandler(); } protected PropertyChangeListener createPropertyChangeListener() { return getHandler(); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } protected void installKeyboardActions() { InputMap km = getInputMap(JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); SwingUtilities.replaceUIInputMap(tabPane, JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, km); km = getInputMap(JComponent.WHEN_FOCUSED); SwingUtilities.replaceUIInputMap(tabPane, JComponent.WHEN_FOCUSED, km); LazyActionMap.installLazyActionMap(tabPane, BasicTabbedPaneUI.class, "TabbedPane.actionMap"); updateMnemonics(); } InputMap getInputMap(int condition) { if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) { return (InputMap)DefaultLookup.get(tabPane, this, "TabbedPane.ancestorInputMap"); } else if (condition == JComponent.WHEN_FOCUSED) { return (InputMap)DefaultLookup.get(tabPane, this, "TabbedPane.focusInputMap"); } return null; } protected void uninstallKeyboardActions() { SwingUtilities.replaceUIActionMap(tabPane, null); SwingUtilities.replaceUIInputMap(tabPane, JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null); SwingUtilities.replaceUIInputMap(tabPane, JComponent.WHEN_FOCUSED, null); SwingUtilities.replaceUIInputMap(tabPane, JComponent.WHEN_IN_FOCUSED_WINDOW, null); mnemonicToIndexMap = null; mnemonicInputMap = null; } /** {@collect.stats} * Reloads the mnemonics. This should be invoked when a memonic changes, * when the title of a mnemonic changes, or when tabs are added/removed. */ private void updateMnemonics() { resetMnemonics(); for (int counter = tabPane.getTabCount() - 1; counter >= 0; counter--) { int mnemonic = tabPane.getMnemonicAt(counter); if (mnemonic > 0) { addMnemonic(counter, mnemonic); } } } /** {@collect.stats} * Resets the mnemonics bindings to an empty state. */ private void resetMnemonics() { if (mnemonicToIndexMap != null) { mnemonicToIndexMap.clear(); mnemonicInputMap.clear(); } } /** {@collect.stats} * Adds the specified mnemonic at the specified index. */ private void addMnemonic(int index, int mnemonic) { if (mnemonicToIndexMap == null) { initMnemonics(); } mnemonicInputMap.put(KeyStroke.getKeyStroke(mnemonic, Event.ALT_MASK), "setSelectedIndex"); mnemonicToIndexMap.put(new Integer(mnemonic), new Integer(index)); } /** {@collect.stats} * Installs the state needed for mnemonics. */ private void initMnemonics() { mnemonicToIndexMap = new Hashtable(); mnemonicInputMap = new ComponentInputMapUIResource(tabPane); mnemonicInputMap.setParent(SwingUtilities.getUIInputMap(tabPane, JComponent.WHEN_IN_FOCUSED_WINDOW)); SwingUtilities.replaceUIInputMap(tabPane, JComponent.WHEN_IN_FOCUSED_WINDOW, mnemonicInputMap); } /** {@collect.stats} * Sets the tab the mouse is over by location. This is a cover method * for <code>setRolloverTab(tabForCoordinate(x, y, false))</code>. */ private void setRolloverTab(int x, int y) { // NOTE: // This calls in with false otherwise it could trigger a validate, // which should NOT happen if the user is only dragging the // mouse around. setRolloverTab(tabForCoordinate(tabPane, x, y, false)); } /** {@collect.stats} * Sets the tab the mouse is currently over to <code>index</code>. * <code>index</code> will be -1 if the mouse is no longer over any * tab. No checking is done to ensure the passed in index identifies a * valid tab. * * @param index Index of the tab the mouse is over. * @since 1.5 */ protected void setRolloverTab(int index) { rolloverTabIndex = index; } /** {@collect.stats} * Returns the tab the mouse is currently over, or {@code -1} if the mouse is no * longer over any tab. * * @return the tab the mouse is currently over, or {@code -1} if the mouse is no * longer over any tab * @since 1.5 */ protected int getRolloverTab() { return rolloverTabIndex; } public Dimension getMinimumSize(JComponent c) { // Default to LayoutManager's minimumLayoutSize return null; } public Dimension getMaximumSize(JComponent c) { // Default to LayoutManager's maximumLayoutSize return null; } /** {@collect.stats} * Returns the baseline. * * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public int getBaseline(JComponent c, int width, int height) { super.getBaseline(c, width, height); int baseline = calculateBaselineIfNecessary(); if (baseline != -1) { int placement = tabPane.getTabPlacement(); Insets insets = tabPane.getInsets(); Insets tabAreaInsets = getTabAreaInsets(placement); switch(placement) { case JTabbedPane.TOP: baseline += insets.top + tabAreaInsets.top; return baseline; case JTabbedPane.BOTTOM: baseline = height - insets.bottom - tabAreaInsets.bottom - maxTabHeight + baseline; return baseline; case JTabbedPane.LEFT: case JTabbedPane.RIGHT: baseline += insets.top + tabAreaInsets.top; return baseline; } } return -1; } /** {@collect.stats} * Returns an enum indicating how the baseline of the component * changes as the size changes. * * @throws NullPointerException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public Component.BaselineResizeBehavior getBaselineResizeBehavior( JComponent c) { super.getBaselineResizeBehavior(c); switch(tabPane.getTabPlacement()) { case JTabbedPane.LEFT: case JTabbedPane.RIGHT: case JTabbedPane.TOP: return Component.BaselineResizeBehavior.CONSTANT_ASCENT; case JTabbedPane.BOTTOM: return Component.BaselineResizeBehavior.CONSTANT_DESCENT; } return Component.BaselineResizeBehavior.OTHER; } /** {@collect.stats} * Returns the baseline for the specified tab. * * @param tab index of tab to get baseline for * @exception IndexOutOfBoundsException if index is out of range * (index < 0 || index >= tab count) * @return baseline or a value &lt; 0 indicating there is no reasonable * baseline * @since 1.6 */ protected int getBaseline(int tab) { if (tabPane.getTabComponentAt(tab) != null) { int offset = getBaselineOffset(); if (offset != 0) { // The offset is not applied to the tab component, and so // in general we can't get good alignment like with components // in the tab. return -1; } Component c = tabPane.getTabComponentAt(tab); Dimension pref = c.getPreferredSize(); Insets tabInsets = getTabInsets(tabPane.getTabPlacement(), tab); int cellHeight = maxTabHeight - tabInsets.top - tabInsets.bottom; return c.getBaseline(pref.width, pref.height) + (cellHeight - pref.height) / 2 + tabInsets.top; } else { View view = getTextViewForTab(tab); if (view != null) { int viewHeight = (int)view.getPreferredSpan(View.Y_AXIS); int baseline = BasicHTML.getHTMLBaseline( view, (int)view.getPreferredSpan(View.X_AXIS), viewHeight); if (baseline >= 0) { return maxTabHeight / 2 - viewHeight / 2 + baseline + getBaselineOffset(); } return -1; } } FontMetrics metrics = getFontMetrics(); int fontHeight = metrics.getHeight(); int fontBaseline = metrics.getAscent(); return maxTabHeight / 2 - fontHeight / 2 + fontBaseline + getBaselineOffset(); } /** {@collect.stats} * Returns the amount the baseline is offset by. This is typically * the same as <code>getTabLabelShiftY</code>. * * @return amount to offset the baseline by * @since 1.6 */ protected int getBaselineOffset() { switch(tabPane.getTabPlacement()) { case JTabbedPane.TOP: if (tabPane.getTabCount() > 1) { return 1; } else { return -1; } case JTabbedPane.BOTTOM: if (tabPane.getTabCount() > 1) { return -1; } else { return 1; } default: // RIGHT|LEFT return (maxTabHeight % 2); } } private int calculateBaselineIfNecessary() { if (!calculatedBaseline) { calculatedBaseline = true; baseline = -1; if (tabPane.getTabCount() > 0) { calculateBaseline(); } } return baseline; } private void calculateBaseline() { int tabCount = tabPane.getTabCount(); int tabPlacement = tabPane.getTabPlacement(); maxTabHeight = calculateMaxTabHeight(tabPlacement); baseline = getBaseline(0); if (isHorizontalTabPlacement()) { for(int i = 1; i < tabCount; i++) { if (getBaseline(i) != baseline) { baseline = -1; break; } } } else { // left/right, tabs may be different sizes. FontMetrics fontMetrics = getFontMetrics(); int fontHeight = fontMetrics.getHeight(); int height = calculateTabHeight(tabPlacement, 0, fontHeight); for(int i = 1; i < tabCount; i++) { int newHeight = calculateTabHeight(tabPlacement, i,fontHeight); if (height != newHeight) { // assume different baseline baseline = -1; break; } } } } // UI Rendering public void paint(Graphics g, JComponent c) { int selectedIndex = tabPane.getSelectedIndex(); int tabPlacement = tabPane.getTabPlacement(); ensureCurrentLayout(); // Paint content border and tab area if (tabsOverlapBorder) { paintContentBorder(g, tabPlacement, selectedIndex); } // If scrollable tabs are enabled, the tab area will be // painted by the scrollable tab panel instead. // if (!scrollableTabLayoutEnabled()) { // WRAP_TAB_LAYOUT paintTabArea(g, tabPlacement, selectedIndex); } if (!tabsOverlapBorder) { paintContentBorder(g, tabPlacement, selectedIndex); } } /** {@collect.stats} * Paints the tabs in the tab area. * Invoked by paint(). * The graphics parameter must be a valid <code>Graphics</code> * object. Tab placement may be either: * <code>JTabbedPane.TOP</code>, <code>JTabbedPane.BOTTOM</code>, * <code>JTabbedPane.LEFT</code>, or <code>JTabbedPane.RIGHT</code>. * The selected index must be a valid tabbed pane tab index (0 to * tab count - 1, inclusive) or -1 if no tab is currently selected. * The handling of invalid parameters is unspecified. * * @param g the graphics object to use for rendering * @param tabPlacement the placement for the tabs within the JTabbedPane * @param selectedIndex the tab index of the selected component * * @since 1.4 */ protected void paintTabArea(Graphics g, int tabPlacement, int selectedIndex) { int tabCount = tabPane.getTabCount(); Rectangle iconRect = new Rectangle(), textRect = new Rectangle(); Rectangle clipRect = g.getClipBounds(); // Paint tabRuns of tabs from back to front for (int i = runCount - 1; i >= 0; i--) { int start = tabRuns[i]; int next = tabRuns[(i == runCount - 1)? 0 : i + 1]; int end = (next != 0? next - 1: tabCount - 1); for (int j = start; j <= end; j++) { if (j != selectedIndex && rects[j].intersects(clipRect)) { paintTab(g, tabPlacement, rects, j, iconRect, textRect); } } } // Paint selected tab if its in the front run // since it may overlap other tabs if (selectedIndex >= 0 && rects[selectedIndex].intersects(clipRect)) { paintTab(g, tabPlacement, rects, selectedIndex, iconRect, textRect); } } protected void paintTab(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect) { Rectangle tabRect = rects[tabIndex]; int selectedIndex = tabPane.getSelectedIndex(); boolean isSelected = selectedIndex == tabIndex; if (tabsOpaque || tabPane.isOpaque()) { paintTabBackground(g, tabPlacement, tabIndex, tabRect.x, tabRect.y, tabRect.width, tabRect.height, isSelected); } paintTabBorder(g, tabPlacement, tabIndex, tabRect.x, tabRect.y, tabRect.width, tabRect.height, isSelected); String title = tabPane.getTitleAt(tabIndex); Font font = tabPane.getFont(); FontMetrics metrics = SwingUtilities2.getFontMetrics(tabPane, g, font); Icon icon = getIconForTab(tabIndex); layoutLabel(tabPlacement, metrics, tabIndex, title, icon, tabRect, iconRect, textRect, isSelected); if (tabPane.getTabComponentAt(tabIndex) == null) { String clippedTitle = title; if (scrollableTabLayoutEnabled() && tabScroller.croppedEdge.isParamsSet() && tabScroller.croppedEdge.getTabIndex() == tabIndex && isHorizontalTabPlacement()) { int availTextWidth = tabScroller.croppedEdge.getCropline() - (textRect.x - tabRect.x) - tabScroller.croppedEdge.getCroppedSideWidth(); clippedTitle = SwingUtilities2.clipStringIfNecessary(null, metrics, title, availTextWidth); } paintText(g, tabPlacement, font, metrics, tabIndex, clippedTitle, textRect, isSelected); paintIcon(g, tabPlacement, tabIndex, icon, iconRect, isSelected); } paintFocusIndicator(g, tabPlacement, rects, tabIndex, iconRect, textRect, isSelected); } private boolean isHorizontalTabPlacement() { return tabPane.getTabPlacement() == TOP || tabPane.getTabPlacement() == BOTTOM; } /* This method will create and return a polygon shape for the given tab rectangle * which has been cropped at the specified cropline with a torn edge visual. * e.g. A "File" tab which has cropped been cropped just after the "i": * ------------- * | ..... | * | . | * | ... . | * | . . | * | . . | * | . . | * -------------- * * The x, y arrays below define the pattern used to create a "torn" edge * segment which is repeated to fill the edge of the tab. * For tabs placed on TOP and BOTTOM, this righthand torn edge is created by * line segments which are defined by coordinates obtained by * subtracting xCropLen[i] from (tab.x + tab.width) and adding yCroplen[i] * to (tab.y). * For tabs placed on LEFT or RIGHT, the bottom torn edge is created by * subtracting xCropLen[i] from (tab.y + tab.height) and adding yCropLen[i] * to (tab.x). */ private static int xCropLen[] = {1,1,0,0,1,1,2,2}; private static int yCropLen[] = {0,3,3,6,6,9,9,12}; private static final int CROP_SEGMENT = 12; private static Polygon createCroppedTabShape(int tabPlacement, Rectangle tabRect, int cropline) { int rlen = 0; int start = 0; int end = 0; int ostart = 0; switch(tabPlacement) { case LEFT: case RIGHT: rlen = tabRect.width; start = tabRect.x; end = tabRect.x + tabRect.width; ostart = tabRect.y + tabRect.height; break; case TOP: case BOTTOM: default: rlen = tabRect.height; start = tabRect.y; end = tabRect.y + tabRect.height; ostart = tabRect.x + tabRect.width; } int rcnt = rlen/CROP_SEGMENT; if (rlen%CROP_SEGMENT > 0) { rcnt++; } int npts = 2 + (rcnt*8); int xp[] = new int[npts]; int yp[] = new int[npts]; int pcnt = 0; xp[pcnt] = ostart; yp[pcnt++] = end; xp[pcnt] = ostart; yp[pcnt++] = start; for(int i = 0; i < rcnt; i++) { for(int j = 0; j < xCropLen.length; j++) { xp[pcnt] = cropline - xCropLen[j]; yp[pcnt] = start + (i*CROP_SEGMENT) + yCropLen[j]; if (yp[pcnt] >= end) { yp[pcnt] = end; pcnt++; break; } pcnt++; } } if (tabPlacement == JTabbedPane.TOP || tabPlacement == JTabbedPane.BOTTOM) { return new Polygon(xp, yp, pcnt); } else { // LEFT or RIGHT return new Polygon(yp, xp, pcnt); } } /* If tabLayoutPolicy == SCROLL_TAB_LAYOUT, this method will paint an edge * indicating the tab is cropped in the viewport display */ private void paintCroppedTabEdge(Graphics g) { int tabIndex = tabScroller.croppedEdge.getTabIndex(); int cropline = tabScroller.croppedEdge.getCropline(); int x,y; switch(tabPane.getTabPlacement()) { case LEFT: case RIGHT: x = rects[tabIndex].x; y = cropline; int xx = x; g.setColor(shadow); while(xx <= x+rects[tabIndex].width) { for (int i=0; i < xCropLen.length; i+=2) { g.drawLine(xx+yCropLen[i],y-xCropLen[i], xx+yCropLen[i+1]-1,y-xCropLen[i+1]); } xx+=CROP_SEGMENT; } break; case TOP: case BOTTOM: default: x = cropline; y = rects[tabIndex].y; int yy = y; g.setColor(shadow); while(yy <= y+rects[tabIndex].height) { for (int i=0; i < xCropLen.length; i+=2) { g.drawLine(x-xCropLen[i],yy+yCropLen[i], x-xCropLen[i+1],yy+yCropLen[i+1]-1); } yy+=CROP_SEGMENT; } } } protected void layoutLabel(int tabPlacement, FontMetrics metrics, int tabIndex, String title, Icon icon, Rectangle tabRect, Rectangle iconRect, Rectangle textRect, boolean isSelected ) { textRect.x = textRect.y = iconRect.x = iconRect.y = 0; View v = getTextViewForTab(tabIndex); if (v != null) { tabPane.putClientProperty("html", v); } SwingUtilities.layoutCompoundLabel((JComponent) tabPane, metrics, title, icon, SwingUtilities.CENTER, SwingUtilities.CENTER, SwingUtilities.CENTER, SwingUtilities.TRAILING, tabRect, iconRect, textRect, textIconGap); tabPane.putClientProperty("html", null); int xNudge = getTabLabelShiftX(tabPlacement, tabIndex, isSelected); int yNudge = getTabLabelShiftY(tabPlacement, tabIndex, isSelected); iconRect.x += xNudge; iconRect.y += yNudge; textRect.x += xNudge; textRect.y += yNudge; } protected void paintIcon(Graphics g, int tabPlacement, int tabIndex, Icon icon, Rectangle iconRect, boolean isSelected ) { if (icon != null) { icon.paintIcon(tabPane, g, iconRect.x, iconRect.y); } } protected void paintText(Graphics g, int tabPlacement, Font font, FontMetrics metrics, int tabIndex, String title, Rectangle textRect, boolean isSelected) { g.setFont(font); View v = getTextViewForTab(tabIndex); if (v != null) { // html v.paint(g, textRect); } else { // plain text int mnemIndex = tabPane.getDisplayedMnemonicIndexAt(tabIndex); if (tabPane.isEnabled() && tabPane.isEnabledAt(tabIndex)) { Color fg = tabPane.getForegroundAt(tabIndex); if (isSelected && (fg instanceof UIResource)) { Color selectedFG = UIManager.getColor( "TabbedPane.selectedForeground"); if (selectedFG != null) { fg = selectedFG; } } g.setColor(fg); SwingUtilities2.drawStringUnderlineCharAt(tabPane, g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent()); } else { // tab disabled g.setColor(tabPane.getBackgroundAt(tabIndex).brighter()); SwingUtilities2.drawStringUnderlineCharAt(tabPane, g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent()); g.setColor(tabPane.getBackgroundAt(tabIndex).darker()); SwingUtilities2.drawStringUnderlineCharAt(tabPane, g, title, mnemIndex, textRect.x - 1, textRect.y + metrics.getAscent() - 1); } } } protected int getTabLabelShiftX(int tabPlacement, int tabIndex, boolean isSelected) { Rectangle tabRect = rects[tabIndex]; String propKey = (isSelected ? "selectedLabelShift" : "labelShift"); int nudge = DefaultLookup.getInt( tabPane, this, "TabbedPane." + propKey, 1); switch (tabPlacement) { case LEFT: return nudge; case RIGHT: return -nudge; case BOTTOM: case TOP: default: return tabRect.width % 2; } } protected int getTabLabelShiftY(int tabPlacement, int tabIndex, boolean isSelected) { Rectangle tabRect = rects[tabIndex]; String propKey = (isSelected ? "selectedLabelShift" : "labelShift"); int nudge = DefaultLookup.getInt( tabPane, this, "TabbedPane." + propKey, 1); switch (tabPlacement) { case BOTTOM: return -nudge; case LEFT: case RIGHT: return tabRect.height % 2; case TOP: default: return nudge; } } protected void paintFocusIndicator(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect, boolean isSelected) { Rectangle tabRect = rects[tabIndex]; if (tabPane.hasFocus() && isSelected) { int x, y, w, h; g.setColor(focus); switch(tabPlacement) { case LEFT: x = tabRect.x + 3; y = tabRect.y + 3; w = tabRect.width - 5; h = tabRect.height - 6; break; case RIGHT: x = tabRect.x + 2; y = tabRect.y + 3; w = tabRect.width - 5; h = tabRect.height - 6; break; case BOTTOM: x = tabRect.x + 3; y = tabRect.y + 2; w = tabRect.width - 6; h = tabRect.height - 5; break; case TOP: default: x = tabRect.x + 3; y = tabRect.y + 3; w = tabRect.width - 6; h = tabRect.height - 5; } BasicGraphicsUtils.drawDashedRect(g, x, y, w, h); } } /** {@collect.stats} * this function draws the border around each tab * note that this function does now draw the background of the tab. * that is done elsewhere */ protected void paintTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected ) { g.setColor(lightHighlight); switch (tabPlacement) { case LEFT: g.drawLine(x+1, y+h-2, x+1, y+h-2); // bottom-left highlight g.drawLine(x, y+2, x, y+h-3); // left highlight g.drawLine(x+1, y+1, x+1, y+1); // top-left highlight g.drawLine(x+2, y, x+w-1, y); // top highlight g.setColor(shadow); g.drawLine(x+2, y+h-2, x+w-1, y+h-2); // bottom shadow g.setColor(darkShadow); g.drawLine(x+2, y+h-1, x+w-1, y+h-1); // bottom dark shadow break; case RIGHT: g.drawLine(x, y, x+w-3, y); // top highlight g.setColor(shadow); g.drawLine(x, y+h-2, x+w-3, y+h-2); // bottom shadow g.drawLine(x+w-2, y+2, x+w-2, y+h-3); // right shadow g.setColor(darkShadow); g.drawLine(x+w-2, y+1, x+w-2, y+1); // top-right dark shadow g.drawLine(x+w-2, y+h-2, x+w-2, y+h-2); // bottom-right dark shadow g.drawLine(x+w-1, y+2, x+w-1, y+h-3); // right dark shadow g.drawLine(x, y+h-1, x+w-3, y+h-1); // bottom dark shadow break; case BOTTOM: g.drawLine(x, y, x, y+h-3); // left highlight g.drawLine(x+1, y+h-2, x+1, y+h-2); // bottom-left highlight g.setColor(shadow); g.drawLine(x+2, y+h-2, x+w-3, y+h-2); // bottom shadow g.drawLine(x+w-2, y, x+w-2, y+h-3); // right shadow g.setColor(darkShadow); g.drawLine(x+2, y+h-1, x+w-3, y+h-1); // bottom dark shadow g.drawLine(x+w-2, y+h-2, x+w-2, y+h-2); // bottom-right dark shadow g.drawLine(x+w-1, y, x+w-1, y+h-3); // right dark shadow break; case TOP: default: g.drawLine(x, y+2, x, y+h-1); // left highlight g.drawLine(x+1, y+1, x+1, y+1); // top-left highlight g.drawLine(x+2, y, x+w-3, y); // top highlight g.setColor(shadow); g.drawLine(x+w-2, y+2, x+w-2, y+h-1); // right shadow g.setColor(darkShadow); g.drawLine(x+w-1, y+2, x+w-1, y+h-1); // right dark-shadow g.drawLine(x+w-2, y+1, x+w-2, y+1); // top-right shadow } } protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected ) { g.setColor(!isSelected || selectedColor == null? tabPane.getBackgroundAt(tabIndex) : selectedColor); switch(tabPlacement) { case LEFT: g.fillRect(x+1, y+1, w-1, h-3); break; case RIGHT: g.fillRect(x, y+1, w-2, h-3); break; case BOTTOM: g.fillRect(x+1, y, w-3, h-1); break; case TOP: default: g.fillRect(x+1, y+1, w-3, h-1); } } protected void paintContentBorder(Graphics g, int tabPlacement, int selectedIndex) { int width = tabPane.getWidth(); int height = tabPane.getHeight(); Insets insets = tabPane.getInsets(); Insets tabAreaInsets = getTabAreaInsets(tabPlacement); int x = insets.left; int y = insets.top; int w = width - insets.right - insets.left; int h = height - insets.top - insets.bottom; switch(tabPlacement) { case LEFT: x += calculateTabAreaWidth(tabPlacement, runCount, maxTabWidth); if (tabsOverlapBorder) { x -= tabAreaInsets.right; } w -= (x - insets.left); break; case RIGHT: w -= calculateTabAreaWidth(tabPlacement, runCount, maxTabWidth); if (tabsOverlapBorder) { w += tabAreaInsets.left; } break; case BOTTOM: h -= calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight); if (tabsOverlapBorder) { h += tabAreaInsets.top; } break; case TOP: default: y += calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight); if (tabsOverlapBorder) { y -= tabAreaInsets.bottom; } h -= (y - insets.top); } if ( tabPane.getTabCount() > 0 && (contentOpaque || tabPane.isOpaque()) ) { // Fill region behind content area Color color = UIManager.getColor("TabbedPane.contentAreaColor"); if (color != null) { g.setColor(color); } else if ( selectedColor == null || selectedIndex == -1 ) { g.setColor(tabPane.getBackground()); } else { g.setColor(selectedColor); } g.fillRect(x,y,w,h); } paintContentBorderTopEdge(g, tabPlacement, selectedIndex, x, y, w, h); paintContentBorderLeftEdge(g, tabPlacement, selectedIndex, x, y, w, h); paintContentBorderBottomEdge(g, tabPlacement, selectedIndex, x, y, w, h); paintContentBorderRightEdge(g, tabPlacement, selectedIndex, x, y, w, h); } protected void paintContentBorderTopEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) { Rectangle selRect = selectedIndex < 0? null : getTabBounds(selectedIndex, calcRect); g.setColor(lightHighlight); // Draw unbroken line if tabs are not on TOP, OR // selected tab is not in run adjacent to content, OR // selected tab is not visible (SCROLL_TAB_LAYOUT) // if (tabPlacement != TOP || selectedIndex < 0 || (selRect.y + selRect.height + 1 < y) || (selRect.x < x || selRect.x > x + w)) { g.drawLine(x, y, x+w-2, y); } else { // Break line to show visual connection to selected tab g.drawLine(x, y, selRect.x - 1, y); if (selRect.x + selRect.width < x + w - 2) { g.drawLine(selRect.x + selRect.width, y, x+w-2, y); } else { g.setColor(shadow); g.drawLine(x+w-2, y, x+w-2, y); } } } protected void paintContentBorderLeftEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) { Rectangle selRect = selectedIndex < 0? null : getTabBounds(selectedIndex, calcRect); g.setColor(lightHighlight); // Draw unbroken line if tabs are not on LEFT, OR // selected tab is not in run adjacent to content, OR // selected tab is not visible (SCROLL_TAB_LAYOUT) // if (tabPlacement != LEFT || selectedIndex < 0 || (selRect.x + selRect.width + 1 < x) || (selRect.y < y || selRect.y > y + h)) { g.drawLine(x, y, x, y+h-2); } else { // Break line to show visual connection to selected tab g.drawLine(x, y, x, selRect.y - 1); if (selRect.y + selRect.height < y + h - 2) { g.drawLine(x, selRect.y + selRect.height, x, y+h-2); } } } protected void paintContentBorderBottomEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) { Rectangle selRect = selectedIndex < 0? null : getTabBounds(selectedIndex, calcRect); g.setColor(shadow); // Draw unbroken line if tabs are not on BOTTOM, OR // selected tab is not in run adjacent to content, OR // selected tab is not visible (SCROLL_TAB_LAYOUT) // if (tabPlacement != BOTTOM || selectedIndex < 0 || (selRect.y - 1 > h) || (selRect.x < x || selRect.x > x + w)) { g.drawLine(x+1, y+h-2, x+w-2, y+h-2); g.setColor(darkShadow); g.drawLine(x, y+h-1, x+w-1, y+h-1); } else { // Break line to show visual connection to selected tab g.drawLine(x+1, y+h-2, selRect.x - 1, y+h-2); g.setColor(darkShadow); g.drawLine(x, y+h-1, selRect.x - 1, y+h-1); if (selRect.x + selRect.width < x + w - 2) { g.setColor(shadow); g.drawLine(selRect.x + selRect.width, y+h-2, x+w-2, y+h-2); g.setColor(darkShadow); g.drawLine(selRect.x + selRect.width, y+h-1, x+w-1, y+h-1); } } } protected void paintContentBorderRightEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) { Rectangle selRect = selectedIndex < 0? null : getTabBounds(selectedIndex, calcRect); g.setColor(shadow); // Draw unbroken line if tabs are not on RIGHT, OR // selected tab is not in run adjacent to content, OR // selected tab is not visible (SCROLL_TAB_LAYOUT) // if (tabPlacement != RIGHT || selectedIndex < 0 || (selRect.x - 1 > w) || (selRect.y < y || selRect.y > y + h)) { g.drawLine(x+w-2, y+1, x+w-2, y+h-3); g.setColor(darkShadow); g.drawLine(x+w-1, y, x+w-1, y+h-1); } else { // Break line to show visual connection to selected tab g.drawLine(x+w-2, y+1, x+w-2, selRect.y - 1); g.setColor(darkShadow); g.drawLine(x+w-1, y, x+w-1, selRect.y - 1); if (selRect.y + selRect.height < y + h - 2) { g.setColor(shadow); g.drawLine(x+w-2, selRect.y + selRect.height, x+w-2, y+h-2); g.setColor(darkShadow); g.drawLine(x+w-1, selRect.y + selRect.height, x+w-1, y+h-2); } } } private void ensureCurrentLayout() { if (!tabPane.isValid()) { tabPane.validate(); } /* If tabPane doesn't have a peer yet, the validate() call will * silently fail. We handle that by forcing a layout if tabPane * is still invalid. See bug 4237677. */ if (!tabPane.isValid()) { TabbedPaneLayout layout = (TabbedPaneLayout)tabPane.getLayout(); layout.calculateLayoutInfo(); } } // TabbedPaneUI methods /** {@collect.stats} * Returns the bounds of the specified tab index. The bounds are * with respect to the JTabbedPane's coordinate space. */ public Rectangle getTabBounds(JTabbedPane pane, int i) { ensureCurrentLayout(); Rectangle tabRect = new Rectangle(); return getTabBounds(i, tabRect); } public int getTabRunCount(JTabbedPane pane) { ensureCurrentLayout(); return runCount; } /** {@collect.stats} * Returns the tab index which intersects the specified point * in the JTabbedPane's coordinate space. */ public int tabForCoordinate(JTabbedPane pane, int x, int y) { return tabForCoordinate(pane, x, y, true); } private int tabForCoordinate(JTabbedPane pane, int x, int y, boolean validateIfNecessary) { if (validateIfNecessary) { ensureCurrentLayout(); } if (isRunsDirty) { // We didn't recalculate the layout, runs and tabCount may not // line up, bail. return -1; } Point p = new Point(x, y); if (scrollableTabLayoutEnabled()) { translatePointToTabPanel(x, y, p); Rectangle viewRect = tabScroller.viewport.getViewRect(); if (!viewRect.contains(p)) { return -1; } } int tabCount = tabPane.getTabCount(); for (int i = 0; i < tabCount; i++) { if (rects[i].contains(p.x, p.y)) { return i; } } return -1; } /** {@collect.stats} * Returns the bounds of the specified tab in the coordinate space * of the JTabbedPane component. This is required because the tab rects * are by default defined in the coordinate space of the component where * they are rendered, which could be the JTabbedPane * (for WRAP_TAB_LAYOUT) or a ScrollableTabPanel (SCROLL_TAB_LAYOUT). * This method should be used whenever the tab rectangle must be relative * to the JTabbedPane itself and the result should be placed in a * designated Rectangle object (rather than instantiating and returning * a new Rectangle each time). The tab index parameter must be a valid * tabbed pane tab index (0 to tab count - 1, inclusive). The destination * rectangle parameter must be a valid <code>Rectangle</code> instance. * The handling of invalid parameters is unspecified. * * @param tabIndex the index of the tab * @param dest the rectangle where the result should be placed * @return the resulting rectangle * * @since 1.4 */ protected Rectangle getTabBounds(int tabIndex, Rectangle dest) { dest.width = rects[tabIndex].width; dest.height = rects[tabIndex].height; if (scrollableTabLayoutEnabled()) { // SCROLL_TAB_LAYOUT // Need to translate coordinates based on viewport location & // view position Point vpp = tabScroller.viewport.getLocation(); Point viewp = tabScroller.viewport.getViewPosition(); dest.x = rects[tabIndex].x + vpp.x - viewp.x; dest.y = rects[tabIndex].y + vpp.y - viewp.y; } else { // WRAP_TAB_LAYOUT dest.x = rects[tabIndex].x; dest.y = rects[tabIndex].y; } return dest; } /** {@collect.stats} * Returns the index of the tab closest to the passed in location, note * that the returned tab may not contain the location x,y. */ private int getClosestTab(int x, int y) { int min = 0; int tabCount = Math.min(rects.length, tabPane.getTabCount()); int max = tabCount; int tabPlacement = tabPane.getTabPlacement(); boolean useX = (tabPlacement == TOP || tabPlacement == BOTTOM); int want = (useX) ? x : y; while (min != max) { int current = (max + min) / 2; int minLoc; int maxLoc; if (useX) { minLoc = rects[current].x; maxLoc = minLoc + rects[current].width; } else { minLoc = rects[current].y; maxLoc = minLoc + rects[current].height; } if (want < minLoc) { max = current; if (min == max) { return Math.max(0, current - 1); } } else if (want >= maxLoc) { min = current; if (max - min <= 1) { return Math.max(current + 1, tabCount - 1); } } else { return current; } } return min; } /** {@collect.stats} * Returns a point which is translated from the specified point in the * JTabbedPane's coordinate space to the coordinate space of the * ScrollableTabPanel. This is used for SCROLL_TAB_LAYOUT ONLY. */ private Point translatePointToTabPanel(int srcx, int srcy, Point dest) { Point vpp = tabScroller.viewport.getLocation(); Point viewp = tabScroller.viewport.getViewPosition(); dest.x = srcx - vpp.x + viewp.x; dest.y = srcy - vpp.y + viewp.y; return dest; } // BasicTabbedPaneUI methods protected Component getVisibleComponent() { return visibleComponent; } protected void setVisibleComponent(Component component) { if (visibleComponent != null && visibleComponent != component && visibleComponent.getParent() == tabPane && visibleComponent.isVisible()) { visibleComponent.setVisible(false); } if (component != null && !component.isVisible()) { component.setVisible(true); } visibleComponent = component; } protected void assureRectsCreated(int tabCount) { int rectArrayLen = rects.length; if (tabCount != rectArrayLen ) { Rectangle[] tempRectArray = new Rectangle[tabCount]; System.arraycopy(rects, 0, tempRectArray, 0, Math.min(rectArrayLen, tabCount)); rects = tempRectArray; for (int rectIndex = rectArrayLen; rectIndex < tabCount; rectIndex++) { rects[rectIndex] = new Rectangle(); } } } protected void expandTabRunsArray() { int rectLen = tabRuns.length; int[] newArray = new int[rectLen+10]; System.arraycopy(tabRuns, 0, newArray, 0, runCount); tabRuns = newArray; } protected int getRunForTab(int tabCount, int tabIndex) { for (int i = 0; i < runCount; i++) { int first = tabRuns[i]; int last = lastTabInRun(tabCount, i); if (tabIndex >= first && tabIndex <= last) { return i; } } return 0; } protected int lastTabInRun(int tabCount, int run) { if (runCount == 1) { return tabCount - 1; } int nextRun = (run == runCount - 1? 0 : run + 1); if (tabRuns[nextRun] == 0) { return tabCount - 1; } return tabRuns[nextRun]-1; } protected int getTabRunOverlay(int tabPlacement) { return tabRunOverlay; } protected int getTabRunIndent(int tabPlacement, int run) { return 0; } protected boolean shouldPadTabRun(int tabPlacement, int run) { return runCount > 1; } protected boolean shouldRotateTabRuns(int tabPlacement) { return true; } protected Icon getIconForTab(int tabIndex) { return (!tabPane.isEnabled() || !tabPane.isEnabledAt(tabIndex))? tabPane.getDisabledIconAt(tabIndex) : tabPane.getIconAt(tabIndex); } /** {@collect.stats} * Returns the text View object required to render stylized text (HTML) for * the specified tab or null if no specialized text rendering is needed * for this tab. This is provided to support html rendering inside tabs. * * @param tabIndex the index of the tab * @return the text view to render the tab's text or null if no * specialized rendering is required * * @since 1.4 */ protected View getTextViewForTab(int tabIndex) { if (htmlViews != null) { return (View)htmlViews.elementAt(tabIndex); } return null; } protected int calculateTabHeight(int tabPlacement, int tabIndex, int fontHeight) { int height = 0; Component c = tabPane.getTabComponentAt(tabIndex); if (c != null) { height = c.getPreferredSize().height; } else { View v = getTextViewForTab(tabIndex); if (v != null) { // html height += (int) v.getPreferredSpan(View.Y_AXIS); } else { // plain text height += fontHeight; } Icon icon = getIconForTab(tabIndex); if (icon != null) { height = Math.max(height, icon.getIconHeight()); } } Insets tabInsets = getTabInsets(tabPlacement, tabIndex); height += tabInsets.top + tabInsets.bottom + 2; return height; } protected int calculateMaxTabHeight(int tabPlacement) { FontMetrics metrics = getFontMetrics(); int tabCount = tabPane.getTabCount(); int result = 0; int fontHeight = metrics.getHeight(); for(int i = 0; i < tabCount; i++) { result = Math.max(calculateTabHeight(tabPlacement, i, fontHeight), result); } return result; } protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) { Insets tabInsets = getTabInsets(tabPlacement, tabIndex); int width = tabInsets.left + tabInsets.right + 3; Component tabComponent = tabPane.getTabComponentAt(tabIndex); if (tabComponent != null) { width += tabComponent.getPreferredSize().width; } else { Icon icon = getIconForTab(tabIndex); if (icon != null) { width += icon.getIconWidth() + textIconGap; } View v = getTextViewForTab(tabIndex); if (v != null) { // html width += (int) v.getPreferredSpan(View.X_AXIS); } else { // plain text String title = tabPane.getTitleAt(tabIndex); width += SwingUtilities2.stringWidth(tabPane, metrics, title); } } return width; } protected int calculateMaxTabWidth(int tabPlacement) { FontMetrics metrics = getFontMetrics(); int tabCount = tabPane.getTabCount(); int result = 0; for(int i = 0; i < tabCount; i++) { result = Math.max(calculateTabWidth(tabPlacement, i, metrics), result); } return result; } protected int calculateTabAreaHeight(int tabPlacement, int horizRunCount, int maxTabHeight) { Insets tabAreaInsets = getTabAreaInsets(tabPlacement); int tabRunOverlay = getTabRunOverlay(tabPlacement); return (horizRunCount > 0? horizRunCount * (maxTabHeight-tabRunOverlay) + tabRunOverlay + tabAreaInsets.top + tabAreaInsets.bottom : 0); } protected int calculateTabAreaWidth(int tabPlacement, int vertRunCount, int maxTabWidth) { Insets tabAreaInsets = getTabAreaInsets(tabPlacement); int tabRunOverlay = getTabRunOverlay(tabPlacement); return (vertRunCount > 0? vertRunCount * (maxTabWidth-tabRunOverlay) + tabRunOverlay + tabAreaInsets.left + tabAreaInsets.right : 0); } protected Insets getTabInsets(int tabPlacement, int tabIndex) { return tabInsets; } protected Insets getSelectedTabPadInsets(int tabPlacement) { rotateInsets(selectedTabPadInsets, currentPadInsets, tabPlacement); return currentPadInsets; } protected Insets getTabAreaInsets(int tabPlacement) { rotateInsets(tabAreaInsets, currentTabAreaInsets, tabPlacement); return currentTabAreaInsets; } protected Insets getContentBorderInsets(int tabPlacement) { return contentBorderInsets; } protected FontMetrics getFontMetrics() { Font font = tabPane.getFont(); return tabPane.getFontMetrics(font); } // Tab Navigation methods protected void navigateSelectedTab(int direction) { int tabPlacement = tabPane.getTabPlacement(); int current = DefaultLookup.getBoolean(tabPane, this, "TabbedPane.selectionFollowsFocus", true) ? tabPane.getSelectedIndex() : getFocusIndex(); int tabCount = tabPane.getTabCount(); boolean leftToRight = BasicGraphicsUtils.isLeftToRight(tabPane); // If we have no tabs then don't navigate. if (tabCount <= 0) { return; } int offset; switch(tabPlacement) { case LEFT: case RIGHT: switch(direction) { case NEXT: selectNextTab(current); break; case PREVIOUS: selectPreviousTab(current); break; case NORTH: selectPreviousTabInRun(current); break; case SOUTH: selectNextTabInRun(current); break; case WEST: offset = getTabRunOffset(tabPlacement, tabCount, current, false); selectAdjacentRunTab(tabPlacement, current, offset); break; case EAST: offset = getTabRunOffset(tabPlacement, tabCount, current, true); selectAdjacentRunTab(tabPlacement, current, offset); break; default: } break; case BOTTOM: case TOP: default: switch(direction) { case NEXT: selectNextTab(current); break; case PREVIOUS: selectPreviousTab(current); break; case NORTH: offset = getTabRunOffset(tabPlacement, tabCount, current, false); selectAdjacentRunTab(tabPlacement, current, offset); break; case SOUTH: offset = getTabRunOffset(tabPlacement, tabCount, current, true); selectAdjacentRunTab(tabPlacement, current, offset); break; case EAST: if (leftToRight) { selectNextTabInRun(current); } else { selectPreviousTabInRun(current); } break; case WEST: if (leftToRight) { selectPreviousTabInRun(current); } else { selectNextTabInRun(current); } break; default: } } } protected void selectNextTabInRun(int current) { int tabCount = tabPane.getTabCount(); int tabIndex = getNextTabIndexInRun(tabCount, current); while(tabIndex != current && !tabPane.isEnabledAt(tabIndex)) { tabIndex = getNextTabIndexInRun(tabCount, tabIndex); } navigateTo(tabIndex); } protected void selectPreviousTabInRun(int current) { int tabCount = tabPane.getTabCount(); int tabIndex = getPreviousTabIndexInRun(tabCount, current); while(tabIndex != current && !tabPane.isEnabledAt(tabIndex)) { tabIndex = getPreviousTabIndexInRun(tabCount, tabIndex); } navigateTo(tabIndex); } protected void selectNextTab(int current) { int tabIndex = getNextTabIndex(current); while (tabIndex != current && !tabPane.isEnabledAt(tabIndex)) { tabIndex = getNextTabIndex(tabIndex); } navigateTo(tabIndex); } protected void selectPreviousTab(int current) { int tabIndex = getPreviousTabIndex(current); while (tabIndex != current && !tabPane.isEnabledAt(tabIndex)) { tabIndex = getPreviousTabIndex(tabIndex); } navigateTo(tabIndex); } protected void selectAdjacentRunTab(int tabPlacement, int tabIndex, int offset) { if ( runCount < 2 ) { return; } int newIndex; Rectangle r = rects[tabIndex]; switch(tabPlacement) { case LEFT: case RIGHT: newIndex = tabForCoordinate(tabPane, r.x + r.width/2 + offset, r.y + r.height/2); break; case BOTTOM: case TOP: default: newIndex = tabForCoordinate(tabPane, r.x + r.width/2, r.y + r.height/2 + offset); } if (newIndex != -1) { while (!tabPane.isEnabledAt(newIndex) && newIndex != tabIndex) { newIndex = getNextTabIndex(newIndex); } navigateTo(newIndex); } } private void navigateTo(int index) { if (DefaultLookup.getBoolean(tabPane, this, "TabbedPane.selectionFollowsFocus", true)) { tabPane.setSelectedIndex(index); } else { // Just move focus (not selection) setFocusIndex(index, true); } } void setFocusIndex(int index, boolean repaint) { if (repaint && !isRunsDirty) { repaintTab(focusIndex); focusIndex = index; repaintTab(focusIndex); } else { focusIndex = index; } } /** {@collect.stats} * Repaints the specified tab. */ private void repaintTab(int index) { // If we're not valid that means we will shortly be validated and // painted, which means we don't have to do anything here. if (!isRunsDirty && index >= 0 && index < tabPane.getTabCount()) { tabPane.repaint(getTabBounds(tabPane, index)); } } /** {@collect.stats} * Makes sure the focusIndex is valid. */ private void validateFocusIndex() { if (focusIndex >= tabPane.getTabCount()) { setFocusIndex(tabPane.getSelectedIndex(), false); } } /** {@collect.stats} * Returns the index of the tab that has focus. * * @return index of tab that has focus * @since 1.5 */ protected int getFocusIndex() { return focusIndex; } protected int getTabRunOffset(int tabPlacement, int tabCount, int tabIndex, boolean forward) { int run = getRunForTab(tabCount, tabIndex); int offset; switch(tabPlacement) { case LEFT: { if (run == 0) { offset = (forward? -(calculateTabAreaWidth(tabPlacement, runCount, maxTabWidth)-maxTabWidth) : -maxTabWidth); } else if (run == runCount - 1) { offset = (forward? maxTabWidth : calculateTabAreaWidth(tabPlacement, runCount, maxTabWidth)-maxTabWidth); } else { offset = (forward? maxTabWidth : -maxTabWidth); } break; } case RIGHT: { if (run == 0) { offset = (forward? maxTabWidth : calculateTabAreaWidth(tabPlacement, runCount, maxTabWidth)-maxTabWidth); } else if (run == runCount - 1) { offset = (forward? -(calculateTabAreaWidth(tabPlacement, runCount, maxTabWidth)-maxTabWidth) : -maxTabWidth); } else { offset = (forward? maxTabWidth : -maxTabWidth); } break; } case BOTTOM: { if (run == 0) { offset = (forward? maxTabHeight : calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight)-maxTabHeight); } else if (run == runCount - 1) { offset = (forward? -(calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight)-maxTabHeight) : -maxTabHeight); } else { offset = (forward? maxTabHeight : -maxTabHeight); } break; } case TOP: default: { if (run == 0) { offset = (forward? -(calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight)-maxTabHeight) : -maxTabHeight); } else if (run == runCount - 1) { offset = (forward? maxTabHeight : calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight)-maxTabHeight); } else { offset = (forward? maxTabHeight : -maxTabHeight); } } } return offset; } protected int getPreviousTabIndex(int base) { int tabIndex = (base - 1 >= 0? base - 1 : tabPane.getTabCount() - 1); return (tabIndex >= 0? tabIndex : 0); } protected int getNextTabIndex(int base) { return (base+1)%tabPane.getTabCount(); } protected int getNextTabIndexInRun(int tabCount, int base) { if (runCount < 2) { return getNextTabIndex(base); } int currentRun = getRunForTab(tabCount, base); int next = getNextTabIndex(base); if (next == tabRuns[getNextTabRun(currentRun)]) { return tabRuns[currentRun]; } return next; } protected int getPreviousTabIndexInRun(int tabCount, int base) { if (runCount < 2) { return getPreviousTabIndex(base); } int currentRun = getRunForTab(tabCount, base); if (base == tabRuns[currentRun]) { int previous = tabRuns[getNextTabRun(currentRun)]-1; return (previous != -1? previous : tabCount-1); } return getPreviousTabIndex(base); } protected int getPreviousTabRun(int baseRun) { int runIndex = (baseRun - 1 >= 0? baseRun - 1 : runCount - 1); return (runIndex >= 0? runIndex : 0); } protected int getNextTabRun(int baseRun) { return (baseRun+1)%runCount; } protected static void rotateInsets(Insets topInsets, Insets targetInsets, int targetPlacement) { switch(targetPlacement) { case LEFT: targetInsets.top = topInsets.left; targetInsets.left = topInsets.top; targetInsets.bottom = topInsets.right; targetInsets.right = topInsets.bottom; break; case BOTTOM: targetInsets.top = topInsets.bottom; targetInsets.left = topInsets.left; targetInsets.bottom = topInsets.top; targetInsets.right = topInsets.right; break; case RIGHT: targetInsets.top = topInsets.left; targetInsets.left = topInsets.bottom; targetInsets.bottom = topInsets.right; targetInsets.right = topInsets.top; break; case TOP: default: targetInsets.top = topInsets.top; targetInsets.left = topInsets.left; targetInsets.bottom = topInsets.bottom; targetInsets.right = topInsets.right; } } // REMIND(aim,7/29/98): This method should be made // protected in the next release where // API changes are allowed boolean requestFocusForVisibleComponent() { return SwingUtilities2.tabbedPaneChangeFocusTo(getVisibleComponent()); } private static class Actions extends UIAction { final static String NEXT = "navigateNext"; final static String PREVIOUS = "navigatePrevious"; final static String RIGHT = "navigateRight"; final static String LEFT = "navigateLeft"; final static String UP = "navigateUp"; final static String DOWN = "navigateDown"; final static String PAGE_UP = "navigatePageUp"; final static String PAGE_DOWN = "navigatePageDown"; final static String REQUEST_FOCUS = "requestFocus"; final static String REQUEST_FOCUS_FOR_VISIBLE = "requestFocusForVisibleComponent"; final static String SET_SELECTED = "setSelectedIndex"; final static String SELECT_FOCUSED = "selectTabWithFocus"; final static String SCROLL_FORWARD = "scrollTabsForwardAction"; final static String SCROLL_BACKWARD = "scrollTabsBackwardAction"; Actions(String key) { super(key); } public void actionPerformed(ActionEvent e) { String key = getName(); JTabbedPane pane = (JTabbedPane)e.getSource(); BasicTabbedPaneUI ui = (BasicTabbedPaneUI)BasicLookAndFeel. getUIOfType(pane.getUI(), BasicTabbedPaneUI.class); if (ui == null) { return; } if (key == NEXT) { ui.navigateSelectedTab(SwingConstants.NEXT); } else if (key == PREVIOUS) { ui.navigateSelectedTab(SwingConstants.PREVIOUS); } else if (key == RIGHT) { ui.navigateSelectedTab(SwingConstants.EAST); } else if (key == LEFT) { ui.navigateSelectedTab(SwingConstants.WEST); } else if (key == UP) { ui.navigateSelectedTab(SwingConstants.NORTH); } else if (key == DOWN) { ui.navigateSelectedTab(SwingConstants.SOUTH); } else if (key == PAGE_UP) { int tabPlacement = pane.getTabPlacement(); if (tabPlacement == TOP|| tabPlacement == BOTTOM) { ui.navigateSelectedTab(SwingConstants.WEST); } else { ui.navigateSelectedTab(SwingConstants.NORTH); } } else if (key == PAGE_DOWN) { int tabPlacement = pane.getTabPlacement(); if (tabPlacement == TOP || tabPlacement == BOTTOM) { ui.navigateSelectedTab(SwingConstants.EAST); } else { ui.navigateSelectedTab(SwingConstants.SOUTH); } } else if (key == REQUEST_FOCUS) { pane.requestFocus(); } else if (key == REQUEST_FOCUS_FOR_VISIBLE) { ui.requestFocusForVisibleComponent(); } else if (key == SET_SELECTED) { String command = e.getActionCommand(); if (command != null && command.length() > 0) { int mnemonic = (int)e.getActionCommand().charAt(0); if (mnemonic >= 'a' && mnemonic <='z') { mnemonic -= ('a' - 'A'); } Integer index = (Integer)ui.mnemonicToIndexMap. get(new Integer(mnemonic)); if (index != null && pane.isEnabledAt(index.intValue())) { pane.setSelectedIndex(index.intValue()); } } } else if (key == SELECT_FOCUSED) { int focusIndex = ui.getFocusIndex(); if (focusIndex != -1) { pane.setSelectedIndex(focusIndex); } } else if (key == SCROLL_FORWARD) { if (ui.scrollableTabLayoutEnabled()) { ui.tabScroller.scrollForward(pane.getTabPlacement()); } } else if (key == SCROLL_BACKWARD) { if (ui.scrollableTabLayoutEnabled()) { ui.tabScroller.scrollBackward(pane.getTabPlacement()); } } } } /** {@collect.stats} * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicTabbedPaneUI. */ public class TabbedPaneLayout implements LayoutManager { public void addLayoutComponent(String name, Component comp) {} public void removeLayoutComponent(Component comp) {} public Dimension preferredLayoutSize(Container parent) { return calculateSize(false); } public Dimension minimumLayoutSize(Container parent) { return calculateSize(true); } protected Dimension calculateSize(boolean minimum) { int tabPlacement = tabPane.getTabPlacement(); Insets insets = tabPane.getInsets(); Insets contentInsets = getContentBorderInsets(tabPlacement); Insets tabAreaInsets = getTabAreaInsets(tabPlacement); Dimension zeroSize = new Dimension(0,0); int height = 0; int width = 0; int cWidth = 0; int cHeight = 0; // Determine minimum size required to display largest // child in each dimension // for (int i = 0; i < tabPane.getTabCount(); i++) { Component component = tabPane.getComponentAt(i); if (component != null) { Dimension size = zeroSize; size = minimum? component.getMinimumSize() : component.getPreferredSize(); if (size != null) { cHeight = Math.max(size.height, cHeight); cWidth = Math.max(size.width, cWidth); } } } // Add content border insets to minimum size width += cWidth; height += cHeight; int tabExtent = 0; // Calculate how much space the tabs will need, based on the // minimum size required to display largest child + content border // switch(tabPlacement) { case LEFT: case RIGHT: height = Math.max(height, calculateMaxTabHeight(tabPlacement)); tabExtent = preferredTabAreaWidth(tabPlacement, height - tabAreaInsets.top - tabAreaInsets.bottom); width += tabExtent; break; case TOP: case BOTTOM: default: width = Math.max(width, calculateMaxTabWidth(tabPlacement)); tabExtent = preferredTabAreaHeight(tabPlacement, width - tabAreaInsets.left - tabAreaInsets.right); height += tabExtent; } return new Dimension(width + insets.left + insets.right + contentInsets.left + contentInsets.right, height + insets.bottom + insets.top + contentInsets.top + contentInsets.bottom); } protected int preferredTabAreaHeight(int tabPlacement, int width) { FontMetrics metrics = getFontMetrics(); int tabCount = tabPane.getTabCount(); int total = 0; if (tabCount > 0) { int rows = 1; int x = 0; int maxTabHeight = calculateMaxTabHeight(tabPlacement); for (int i = 0; i < tabCount; i++) { int tabWidth = calculateTabWidth(tabPlacement, i, metrics); if (x != 0 && x + tabWidth > width) { rows++; x = 0; } x += tabWidth; } total = calculateTabAreaHeight(tabPlacement, rows, maxTabHeight); } return total; } protected int preferredTabAreaWidth(int tabPlacement, int height) { FontMetrics metrics = getFontMetrics(); int tabCount = tabPane.getTabCount(); int total = 0; if (tabCount > 0) { int columns = 1; int y = 0; int fontHeight = metrics.getHeight(); maxTabWidth = calculateMaxTabWidth(tabPlacement); for (int i = 0; i < tabCount; i++) { int tabHeight = calculateTabHeight(tabPlacement, i, fontHeight); if (y != 0 && y + tabHeight > height) { columns++; y = 0; } y += tabHeight; } total = calculateTabAreaWidth(tabPlacement, columns, maxTabWidth); } return total; } public void layoutContainer(Container parent) { /* Some of the code in this method deals with changing the * visibility of components to hide and show the contents for the * selected tab. This is older code that has since been duplicated * in JTabbedPane.fireStateChanged(), so as to allow visibility * changes to happen sooner (see the note there). This code remains * for backward compatibility as there are some cases, such as * subclasses that don't fireStateChanged() where it may be used. * Any changes here need to be kept in synch with * JTabbedPane.fireStateChanged(). */ setRolloverTab(-1); int tabPlacement = tabPane.getTabPlacement(); Insets insets = tabPane.getInsets(); int selectedIndex = tabPane.getSelectedIndex(); Component visibleComponent = getVisibleComponent(); calculateLayoutInfo(); Component selectedComponent = null; if (selectedIndex < 0) { if (visibleComponent != null) { // The last tab was removed, so remove the component setVisibleComponent(null); } } else { selectedComponent = tabPane.getComponentAt(selectedIndex); } int cx, cy, cw, ch; int totalTabWidth = 0; int totalTabHeight = 0; Insets contentInsets = getContentBorderInsets(tabPlacement); boolean shouldChangeFocus = false; // In order to allow programs to use a single component // as the display for multiple tabs, we will not change // the visible compnent if the currently selected tab // has a null component. This is a bit dicey, as we don't // explicitly state we support this in the spec, but since // programs are now depending on this, we're making it work. // if(selectedComponent != null) { if(selectedComponent != visibleComponent && visibleComponent != null) { if(SwingUtilities.findFocusOwner(visibleComponent) != null) { shouldChangeFocus = true; } } setVisibleComponent(selectedComponent); } Rectangle bounds = tabPane.getBounds(); int numChildren = tabPane.getComponentCount(); if(numChildren > 0) { switch(tabPlacement) { case LEFT: totalTabWidth = calculateTabAreaWidth(tabPlacement, runCount, maxTabWidth); cx = insets.left + totalTabWidth + contentInsets.left; cy = insets.top + contentInsets.top; break; case RIGHT: totalTabWidth = calculateTabAreaWidth(tabPlacement, runCount, maxTabWidth); cx = insets.left + contentInsets.left; cy = insets.top + contentInsets.top; break; case BOTTOM: totalTabHeight = calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight); cx = insets.left + contentInsets.left; cy = insets.top + contentInsets.top; break; case TOP: default: totalTabHeight = calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight); cx = insets.left + contentInsets.left; cy = insets.top + totalTabHeight + contentInsets.top; } cw = bounds.width - totalTabWidth - insets.left - insets.right - contentInsets.left - contentInsets.right; ch = bounds.height - totalTabHeight - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom; for(int i = 0; i < numChildren; i++) { Component child = tabPane.getComponent(i); if(child == tabContainer) { int tabContainerWidth = totalTabWidth == 0 ? bounds.width : totalTabWidth + insets.left + insets.right + contentInsets.left + contentInsets.right; int tabContainerHeight = totalTabHeight == 0 ? bounds.height : totalTabHeight + insets.top + insets.bottom + contentInsets.top + contentInsets.bottom; int tabContainerX = 0; int tabContainerY = 0; if(tabPlacement == BOTTOM) { tabContainerY = bounds.height - tabContainerHeight; } else if(tabPlacement == RIGHT) { tabContainerX = bounds.width - tabContainerWidth; } child.setBounds(tabContainerX, tabContainerY, tabContainerWidth, tabContainerHeight); } else { child.setBounds(cx, cy, cw, ch); } } } layoutTabComponents(); if(shouldChangeFocus) { if(!requestFocusForVisibleComponent()) { tabPane.requestFocus(); } } } public void calculateLayoutInfo() { int tabCount = tabPane.getTabCount(); assureRectsCreated(tabCount); calculateTabRects(tabPane.getTabPlacement(), tabCount); isRunsDirty = false; } private void layoutTabComponents() { if (tabContainer == null) { return; } Rectangle rect = new Rectangle(); Point delta = new Point(-tabContainer.getX(), -tabContainer.getY()); if (scrollableTabLayoutEnabled()) { translatePointToTabPanel(0, 0, delta); } for (int i = 0; i < tabPane.getTabCount(); i++) { Component c = tabPane.getTabComponentAt(i); if (c == null) { continue; } getTabBounds(i, rect); Dimension preferredSize = c.getPreferredSize(); Insets insets = getTabInsets(tabPane.getTabPlacement(), i); int outerX = rect.x + insets.left + delta.x; int outerY = rect.y + insets.top + delta.y; int outerWidth = rect.width - insets.left - insets.right; int outerHeight = rect.height - insets.top - insets.bottom; //centralize component int x = outerX + (outerWidth - preferredSize.width) / 2; int y = outerY + (outerHeight - preferredSize.height) / 2; int tabPlacement = tabPane.getTabPlacement(); boolean isSeleceted = i == tabPane.getSelectedIndex(); c.setBounds(x + getTabLabelShiftX(tabPlacement, i, isSeleceted), y + getTabLabelShiftY(tabPlacement, i, isSeleceted), preferredSize.width, preferredSize.height); } } protected void calculateTabRects(int tabPlacement, int tabCount) { FontMetrics metrics = getFontMetrics(); Dimension size = tabPane.getSize(); Insets insets = tabPane.getInsets(); Insets tabAreaInsets = getTabAreaInsets(tabPlacement); int fontHeight = metrics.getHeight(); int selectedIndex = tabPane.getSelectedIndex(); int tabRunOverlay; int i, j; int x, y; int returnAt; boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT); boolean leftToRight = BasicGraphicsUtils.isLeftToRight(tabPane); // // Calculate bounds within which a tab run must fit // switch(tabPlacement) { case LEFT: maxTabWidth = calculateMaxTabWidth(tabPlacement); x = insets.left + tabAreaInsets.left; y = insets.top + tabAreaInsets.top; returnAt = size.height - (insets.bottom + tabAreaInsets.bottom); break; case RIGHT: maxTabWidth = calculateMaxTabWidth(tabPlacement); x = size.width - insets.right - tabAreaInsets.right - maxTabWidth; y = insets.top + tabAreaInsets.top; returnAt = size.height - (insets.bottom + tabAreaInsets.bottom); break; case BOTTOM: maxTabHeight = calculateMaxTabHeight(tabPlacement); x = insets.left + tabAreaInsets.left; y = size.height - insets.bottom - tabAreaInsets.bottom - maxTabHeight; returnAt = size.width - (insets.right + tabAreaInsets.right); break; case TOP: default: maxTabHeight = calculateMaxTabHeight(tabPlacement); x = insets.left + tabAreaInsets.left; y = insets.top + tabAreaInsets.top; returnAt = size.width - (insets.right + tabAreaInsets.right); break; } tabRunOverlay = getTabRunOverlay(tabPlacement); runCount = 0; selectedRun = -1; if (tabCount == 0) { return; } // Run through tabs and partition them into runs Rectangle rect; for (i = 0; i < tabCount; i++) { rect = rects[i]; if (!verticalTabRuns) { // Tabs on TOP or BOTTOM.... if (i > 0) { rect.x = rects[i-1].x + rects[i-1].width; } else { tabRuns[0] = 0; runCount = 1; maxTabWidth = 0; rect.x = x; } rect.width = calculateTabWidth(tabPlacement, i, metrics); maxTabWidth = Math.max(maxTabWidth, rect.width); // Never move a TAB down a run if it is in the first column. // Even if there isn't enough room, moving it to a fresh // line won't help. if (rect.x != 2 + insets.left && rect.x + rect.width > returnAt) { if (runCount > tabRuns.length - 1) { expandTabRunsArray(); } tabRuns[runCount] = i; runCount++; rect.x = x; } // Initialize y position in case there's just one run rect.y = y; rect.height = maxTabHeight/* - 2*/; } else { // Tabs on LEFT or RIGHT... if (i > 0) { rect.y = rects[i-1].y + rects[i-1].height; } else { tabRuns[0] = 0; runCount = 1; maxTabHeight = 0; rect.y = y; } rect.height = calculateTabHeight(tabPlacement, i, fontHeight); maxTabHeight = Math.max(maxTabHeight, rect.height); // Never move a TAB over a run if it is in the first run. // Even if there isn't enough room, moving it to a fresh // column won't help. if (rect.y != 2 + insets.top && rect.y + rect.height > returnAt) { if (runCount > tabRuns.length - 1) { expandTabRunsArray(); } tabRuns[runCount] = i; runCount++; rect.y = y; } // Initialize x position in case there's just one column rect.x = x; rect.width = maxTabWidth/* - 2*/; } if (i == selectedIndex) { selectedRun = runCount - 1; } } if (runCount > 1) { // Re-distribute tabs in case last run has leftover space normalizeTabRuns(tabPlacement, tabCount, verticalTabRuns? y : x, returnAt); selectedRun = getRunForTab(tabCount, selectedIndex); // Rotate run array so that selected run is first if (shouldRotateTabRuns(tabPlacement)) { rotateTabRuns(tabPlacement, selectedRun); } } // Step through runs from back to front to calculate // tab y locations and to pad runs appropriately for (i = runCount - 1; i >= 0; i--) { int start = tabRuns[i]; int next = tabRuns[i == (runCount - 1)? 0 : i + 1]; int end = (next != 0? next - 1 : tabCount - 1); if (!verticalTabRuns) { for (j = start; j <= end; j++) { rect = rects[j]; rect.y = y; rect.x += getTabRunIndent(tabPlacement, i); } if (shouldPadTabRun(tabPlacement, i)) { padTabRun(tabPlacement, start, end, returnAt); } if (tabPlacement == BOTTOM) { y -= (maxTabHeight - tabRunOverlay); } else { y += (maxTabHeight - tabRunOverlay); } } else { for (j = start; j <= end; j++) { rect = rects[j]; rect.x = x; rect.y += getTabRunIndent(tabPlacement, i); } if (shouldPadTabRun(tabPlacement, i)) { padTabRun(tabPlacement, start, end, returnAt); } if (tabPlacement == RIGHT) { x -= (maxTabWidth - tabRunOverlay); } else { x += (maxTabWidth - tabRunOverlay); } } } // Pad the selected tab so that it appears raised in front padSelectedTab(tabPlacement, selectedIndex); // if right to left and tab placement on the top or // the bottom, flip x positions and adjust by widths if (!leftToRight && !verticalTabRuns) { int rightMargin = size.width - (insets.right + tabAreaInsets.right); for (i = 0; i < tabCount; i++) { rects[i].x = rightMargin - rects[i].x - rects[i].width; } } } /* * Rotates the run-index array so that the selected run is run[0] */ protected void rotateTabRuns(int tabPlacement, int selectedRun) { for (int i = 0; i < selectedRun; i++) { int save = tabRuns[0]; for (int j = 1; j < runCount; j++) { tabRuns[j - 1] = tabRuns[j]; } tabRuns[runCount-1] = save; } } protected void normalizeTabRuns(int tabPlacement, int tabCount, int start, int max) { boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT); int run = runCount - 1; boolean keepAdjusting = true; double weight = 1.25; // At this point the tab runs are packed to fit as many // tabs as possible, which can leave the last run with a lot // of extra space (resulting in very fat tabs on the last run). // So we'll attempt to distribute this extra space more evenly // across the runs in order to make the runs look more consistent. // // Starting with the last run, determine whether the last tab in // the previous run would fit (generously) in this run; if so, // move tab to current run and shift tabs accordingly. Cycle // through remaining runs using the same algorithm. // while (keepAdjusting) { int last = lastTabInRun(tabCount, run); int prevLast = lastTabInRun(tabCount, run-1); int end; int prevLastLen; if (!verticalTabRuns) { end = rects[last].x + rects[last].width; prevLastLen = (int)(maxTabWidth*weight); } else { end = rects[last].y + rects[last].height; prevLastLen = (int)(maxTabHeight*weight*2); } // Check if the run has enough extra space to fit the last tab // from the previous row... if (max - end > prevLastLen) { // Insert tab from previous row and shift rest over tabRuns[run] = prevLast; if (!verticalTabRuns) { rects[prevLast].x = start; } else { rects[prevLast].y = start; } for (int i = prevLast+1; i <= last; i++) { if (!verticalTabRuns) { rects[i].x = rects[i-1].x + rects[i-1].width; } else { rects[i].y = rects[i-1].y + rects[i-1].height; } } } else if (run == runCount - 1) { // no more room left in last run, so we're done! keepAdjusting = false; } if (run - 1 > 0) { // check previous run next... run -= 1; } else { // check last run again...but require a higher ratio // of extraspace-to-tabsize because we don't want to // end up with too many tabs on the last run! run = runCount - 1; weight += .25; } } } protected void padTabRun(int tabPlacement, int start, int end, int max) { Rectangle lastRect = rects[end]; if (tabPlacement == TOP || tabPlacement == BOTTOM) { int runWidth = (lastRect.x + lastRect.width) - rects[start].x; int deltaWidth = max - (lastRect.x + lastRect.width); float factor = (float)deltaWidth / (float)runWidth; for (int j = start; j <= end; j++) { Rectangle pastRect = rects[j]; if (j > start) { pastRect.x = rects[j-1].x + rects[j-1].width; } pastRect.width += Math.round((float)pastRect.width * factor); } lastRect.width = max - lastRect.x; } else { int runHeight = (lastRect.y + lastRect.height) - rects[start].y; int deltaHeight = max - (lastRect.y + lastRect.height); float factor = (float)deltaHeight / (float)runHeight; for (int j = start; j <= end; j++) { Rectangle pastRect = rects[j]; if (j > start) { pastRect.y = rects[j-1].y + rects[j-1].height; } pastRect.height += Math.round((float)pastRect.height * factor); } lastRect.height = max - lastRect.y; } } protected void padSelectedTab(int tabPlacement, int selectedIndex) { if (selectedIndex >= 0) { Rectangle selRect = rects[selectedIndex]; Insets padInsets = getSelectedTabPadInsets(tabPlacement); selRect.x -= padInsets.left; selRect.width += (padInsets.left + padInsets.right); selRect.y -= padInsets.top; selRect.height += (padInsets.top + padInsets.bottom); if (!scrollableTabLayoutEnabled()) { // WRAP_TAB_LAYOUT // do not expand selected tab more then necessary Dimension size = tabPane.getSize(); Insets insets = tabPane.getInsets(); if ((tabPlacement == LEFT) || (tabPlacement == RIGHT)) { int top = insets.top - selRect.y; if (top > 0) { selRect.y += top; selRect.height -= top; } int bottom = (selRect.y + selRect.height) + insets.bottom - size.height; if (bottom > 0) { selRect.height -= bottom; } } else { int left = insets.left - selRect.x; if (left > 0) { selRect.x += left; selRect.width -= left; } int right = (selRect.x + selRect.width) + insets.right - size.width; if (right > 0) { selRect.width -= right; } } } } } } private class TabbedPaneScrollLayout extends TabbedPaneLayout { protected int preferredTabAreaHeight(int tabPlacement, int width) { return calculateMaxTabHeight(tabPlacement); } protected int preferredTabAreaWidth(int tabPlacement, int height) { return calculateMaxTabWidth(tabPlacement); } public void layoutContainer(Container parent) { /* Some of the code in this method deals with changing the * visibility of components to hide and show the contents for the * selected tab. This is older code that has since been duplicated * in JTabbedPane.fireStateChanged(), so as to allow visibility * changes to happen sooner (see the note there). This code remains * for backward compatibility as there are some cases, such as * subclasses that don't fireStateChanged() where it may be used. * Any changes here need to be kept in synch with * JTabbedPane.fireStateChanged(). */ setRolloverTab(-1); int tabPlacement = tabPane.getTabPlacement(); int tabCount = tabPane.getTabCount(); Insets insets = tabPane.getInsets(); int selectedIndex = tabPane.getSelectedIndex(); Component visibleComponent = getVisibleComponent(); calculateLayoutInfo(); Component selectedComponent = null; if (selectedIndex < 0) { if (visibleComponent != null) { // The last tab was removed, so remove the component setVisibleComponent(null); } } else { selectedComponent = tabPane.getComponentAt(selectedIndex); } if (tabPane.getTabCount() == 0) { tabScroller.croppedEdge.resetParams(); tabScroller.scrollForwardButton.setVisible(false); tabScroller.scrollBackwardButton.setVisible(false); return; } boolean shouldChangeFocus = false; // In order to allow programs to use a single component // as the display for multiple tabs, we will not change // the visible compnent if the currently selected tab // has a null component. This is a bit dicey, as we don't // explicitly state we support this in the spec, but since // programs are now depending on this, we're making it work. // if(selectedComponent != null) { if(selectedComponent != visibleComponent && visibleComponent != null) { if(SwingUtilities.findFocusOwner(visibleComponent) != null) { shouldChangeFocus = true; } } setVisibleComponent(selectedComponent); } int tx, ty, tw, th; // tab area bounds int cx, cy, cw, ch; // content area bounds Insets contentInsets = getContentBorderInsets(tabPlacement); Rectangle bounds = tabPane.getBounds(); int numChildren = tabPane.getComponentCount(); if(numChildren > 0) { switch(tabPlacement) { case LEFT: // calculate tab area bounds tw = calculateTabAreaWidth(tabPlacement, runCount, maxTabWidth); th = bounds.height - insets.top - insets.bottom; tx = insets.left; ty = insets.top; // calculate content area bounds cx = tx + tw + contentInsets.left; cy = ty + contentInsets.top; cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right; ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom; break; case RIGHT: // calculate tab area bounds tw = calculateTabAreaWidth(tabPlacement, runCount, maxTabWidth); th = bounds.height - insets.top - insets.bottom; tx = bounds.width - insets.right - tw; ty = insets.top; // calculate content area bounds cx = insets.left + contentInsets.left; cy = insets.top + contentInsets.top; cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right; ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom; break; case BOTTOM: // calculate tab area bounds tw = bounds.width - insets.left - insets.right; th = calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight); tx = insets.left; ty = bounds.height - insets.bottom - th; // calculate content area bounds cx = insets.left + contentInsets.left; cy = insets.top + contentInsets.top; cw = bounds.width - insets.left - insets.right - contentInsets.left - contentInsets.right; ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom; break; case TOP: default: // calculate tab area bounds tw = bounds.width - insets.left - insets.right; th = calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight); tx = insets.left; ty = insets.top; // calculate content area bounds cx = tx + contentInsets.left; cy = ty + th + contentInsets.top; cw = bounds.width - insets.left - insets.right - contentInsets.left - contentInsets.right; ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom; } for(int i = 0; i < numChildren; i++) { Component child = tabPane.getComponent(i); if(tabScroller != null && child == tabScroller.viewport) { JViewport viewport = (JViewport) child; Rectangle viewRect = viewport.getViewRect(); int vw = tw; int vh = th; Dimension butSize = tabScroller.scrollForwardButton.getPreferredSize(); switch(tabPlacement) { case LEFT: case RIGHT: int totalTabHeight = rects[tabCount - 1].y + rects[tabCount - 1].height; if(totalTabHeight > th) { // Allow space for scrollbuttons vh = (th > 2 * butSize.height) ? th - 2 * butSize.height : 0; if(totalTabHeight - viewRect.y <= vh) { // Scrolled to the end, so ensure the viewport size is // such that the scroll offset aligns with a tab vh = totalTabHeight - viewRect.y; } } break; case BOTTOM: case TOP: default: int totalTabWidth = rects[tabCount - 1].x + rects[tabCount - 1].width; if(totalTabWidth > tw) { // Need to allow space for scrollbuttons vw = (tw > 2 * butSize.width) ? tw - 2 * butSize.width : 0; if(totalTabWidth - viewRect.x <= vw) { // Scrolled to the end, so ensure the viewport size is // such that the scroll offset aligns with a tab vw = totalTabWidth - viewRect.x; } } } child.setBounds(tx, ty, vw, vh); } else if(tabScroller != null && (child == tabScroller.scrollForwardButton || child == tabScroller.scrollBackwardButton)) { Component scrollbutton = child; Dimension bsize = scrollbutton.getPreferredSize(); int bx = 0; int by = 0; int bw = bsize.width; int bh = bsize.height; boolean visible = false; switch(tabPlacement) { case LEFT: case RIGHT: int totalTabHeight = rects[tabCount - 1].y + rects[tabCount - 1].height; if(totalTabHeight > th) { visible = true; bx = (tabPlacement == LEFT ? tx + tw - bsize.width : tx); by = (child == tabScroller.scrollForwardButton) ? bounds.height - insets.bottom - bsize.height : bounds.height - insets.bottom - 2 * bsize.height; } break; case BOTTOM: case TOP: default: int totalTabWidth = rects[tabCount - 1].x + rects[tabCount - 1].width; if(totalTabWidth > tw) { visible = true; bx = (child == tabScroller.scrollForwardButton) ? bounds.width - insets.left - bsize.width : bounds.width - insets.left - 2 * bsize.width; by = (tabPlacement == TOP ? ty + th - bsize.height : ty); } } child.setVisible(visible); if(visible) { child.setBounds(bx, by, bw, bh); } } else { // All content children... child.setBounds(cx, cy, cw, ch); } } super.layoutTabComponents(); layoutCroppedEdge(); if(shouldChangeFocus) { if(!requestFocusForVisibleComponent()) { tabPane.requestFocus(); } } } } private void layoutCroppedEdge() { tabScroller.croppedEdge.resetParams(); Rectangle viewRect = tabScroller.viewport.getViewRect(); int cropline; for (int i = 0; i < rects.length; i++) { Rectangle tabRect = rects[i]; switch (tabPane.getTabPlacement()) { case LEFT: case RIGHT: cropline = viewRect.y + viewRect.height; if ((tabRect.y < cropline) && (tabRect.y + tabRect.height > cropline)) { tabScroller.croppedEdge.setParams(i, cropline - tabRect.y - 1, -currentTabAreaInsets.left, 0); } break; case TOP: case BOTTOM: default: cropline = viewRect.x + viewRect.width; if ((tabRect.x < cropline - 1) && (tabRect.x + tabRect.width > cropline)) { tabScroller.croppedEdge.setParams(i, cropline - tabRect.x - 1, 0, -currentTabAreaInsets.top); } } } } protected void calculateTabRects(int tabPlacement, int tabCount) { FontMetrics metrics = getFontMetrics(); Dimension size = tabPane.getSize(); Insets insets = tabPane.getInsets(); Insets tabAreaInsets = getTabAreaInsets(tabPlacement); int fontHeight = metrics.getHeight(); int selectedIndex = tabPane.getSelectedIndex(); int i, j; boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT); boolean leftToRight = BasicGraphicsUtils.isLeftToRight(tabPane); int x = tabAreaInsets.left; int y = tabAreaInsets.top; int totalWidth = 0; int totalHeight = 0; // // Calculate bounds within which a tab run must fit // switch(tabPlacement) { case LEFT: case RIGHT: maxTabWidth = calculateMaxTabWidth(tabPlacement); break; case BOTTOM: case TOP: default: maxTabHeight = calculateMaxTabHeight(tabPlacement); } runCount = 0; selectedRun = -1; if (tabCount == 0) { return; } selectedRun = 0; runCount = 1; // Run through tabs and lay them out in a single run Rectangle rect; for (i = 0; i < tabCount; i++) { rect = rects[i]; if (!verticalTabRuns) { // Tabs on TOP or BOTTOM.... if (i > 0) { rect.x = rects[i-1].x + rects[i-1].width; } else { tabRuns[0] = 0; maxTabWidth = 0; totalHeight += maxTabHeight; rect.x = x; } rect.width = calculateTabWidth(tabPlacement, i, metrics); totalWidth = rect.x + rect.width; maxTabWidth = Math.max(maxTabWidth, rect.width); rect.y = y; rect.height = maxTabHeight/* - 2*/; } else { // Tabs on LEFT or RIGHT... if (i > 0) { rect.y = rects[i-1].y + rects[i-1].height; } else { tabRuns[0] = 0; maxTabHeight = 0; totalWidth = maxTabWidth; rect.y = y; } rect.height = calculateTabHeight(tabPlacement, i, fontHeight); totalHeight = rect.y + rect.height; maxTabHeight = Math.max(maxTabHeight, rect.height); rect.x = x; rect.width = maxTabWidth/* - 2*/; } } if (tabsOverlapBorder) { // Pad the selected tab so that it appears raised in front padSelectedTab(tabPlacement, selectedIndex); } // if right to left and tab placement on the top or // the bottom, flip x positions and adjust by widths if (!leftToRight && !verticalTabRuns) { int rightMargin = size.width - (insets.right + tabAreaInsets.right); for (i = 0; i < tabCount; i++) { rects[i].x = rightMargin - rects[i].x - rects[i].width; } } tabScroller.tabPanel.setPreferredSize(new Dimension(totalWidth, totalHeight)); } } private class ScrollableTabSupport implements ActionListener, ChangeListener { public ScrollableTabViewport viewport; public ScrollableTabPanel tabPanel; public JButton scrollForwardButton; public JButton scrollBackwardButton; public CroppedEdge croppedEdge; public int leadingTabIndex; private Point tabViewPosition = new Point(0,0); ScrollableTabSupport(int tabPlacement) { viewport = new ScrollableTabViewport(); tabPanel = new ScrollableTabPanel(); viewport.setView(tabPanel); viewport.addChangeListener(this); croppedEdge = new CroppedEdge(); createButtons(); } /** {@collect.stats} * Recreates the scroll buttons and adds them to the TabbedPane. */ void createButtons() { if (scrollForwardButton != null) { tabPane.remove(scrollForwardButton); scrollForwardButton.removeActionListener(this); tabPane.remove(scrollBackwardButton); scrollBackwardButton.removeActionListener(this); } int tabPlacement = tabPane.getTabPlacement(); if (tabPlacement == TOP || tabPlacement == BOTTOM) { scrollForwardButton = createScrollButton(EAST); scrollBackwardButton = createScrollButton(WEST); } else { // tabPlacement = LEFT || RIGHT scrollForwardButton = createScrollButton(SOUTH); scrollBackwardButton = createScrollButton(NORTH); } scrollForwardButton.addActionListener(this); scrollBackwardButton.addActionListener(this); tabPane.add(scrollForwardButton); tabPane.add(scrollBackwardButton); } public void scrollForward(int tabPlacement) { Dimension viewSize = viewport.getViewSize(); Rectangle viewRect = viewport.getViewRect(); if (tabPlacement == TOP || tabPlacement == BOTTOM) { if (viewRect.width >= viewSize.width - viewRect.x) { return; // no room left to scroll } } else { // tabPlacement == LEFT || tabPlacement == RIGHT if (viewRect.height >= viewSize.height - viewRect.y) { return; } } setLeadingTabIndex(tabPlacement, leadingTabIndex+1); } public void scrollBackward(int tabPlacement) { if (leadingTabIndex == 0) { return; // no room left to scroll } setLeadingTabIndex(tabPlacement, leadingTabIndex-1); } public void setLeadingTabIndex(int tabPlacement, int index) { leadingTabIndex = index; Dimension viewSize = viewport.getViewSize(); Rectangle viewRect = viewport.getViewRect(); switch(tabPlacement) { case TOP: case BOTTOM: tabViewPosition.x = leadingTabIndex == 0? 0 : rects[leadingTabIndex].x; if ((viewSize.width - tabViewPosition.x) < viewRect.width) { // We've scrolled to the end, so adjust the viewport size // to ensure the view position remains aligned on a tab boundary Dimension extentSize = new Dimension(viewSize.width - tabViewPosition.x, viewRect.height); viewport.setExtentSize(extentSize); } break; case LEFT: case RIGHT: tabViewPosition.y = leadingTabIndex == 0? 0 : rects[leadingTabIndex].y; if ((viewSize.height - tabViewPosition.y) < viewRect.height) { // We've scrolled to the end, so adjust the viewport size // to ensure the view position remains aligned on a tab boundary Dimension extentSize = new Dimension(viewRect.width, viewSize.height - tabViewPosition.y); viewport.setExtentSize(extentSize); } } viewport.setViewPosition(tabViewPosition); } public void stateChanged(ChangeEvent e) { updateView(); } private void updateView() { int tabPlacement = tabPane.getTabPlacement(); int tabCount = tabPane.getTabCount(); Rectangle vpRect = viewport.getBounds(); Dimension viewSize = viewport.getViewSize(); Rectangle viewRect = viewport.getViewRect(); leadingTabIndex = getClosestTab(viewRect.x, viewRect.y); // If the tab isn't right aligned, adjust it. if (leadingTabIndex + 1 < tabCount) { switch (tabPlacement) { case TOP: case BOTTOM: if (rects[leadingTabIndex].x < viewRect.x) { leadingTabIndex++; } break; case LEFT: case RIGHT: if (rects[leadingTabIndex].y < viewRect.y) { leadingTabIndex++; } break; } } Insets contentInsets = getContentBorderInsets(tabPlacement); switch(tabPlacement) { case LEFT: tabPane.repaint(vpRect.x+vpRect.width, vpRect.y, contentInsets.left, vpRect.height); scrollBackwardButton.setEnabled( viewRect.y > 0 && leadingTabIndex > 0); scrollForwardButton.setEnabled( leadingTabIndex < tabCount-1 && viewSize.height-viewRect.y > viewRect.height); break; case RIGHT: tabPane.repaint(vpRect.x-contentInsets.right, vpRect.y, contentInsets.right, vpRect.height); scrollBackwardButton.setEnabled( viewRect.y > 0 && leadingTabIndex > 0); scrollForwardButton.setEnabled( leadingTabIndex < tabCount-1 && viewSize.height-viewRect.y > viewRect.height); break; case BOTTOM: tabPane.repaint(vpRect.x, vpRect.y-contentInsets.bottom, vpRect.width, contentInsets.bottom); scrollBackwardButton.setEnabled( viewRect.x > 0 && leadingTabIndex > 0); scrollForwardButton.setEnabled( leadingTabIndex < tabCount-1 && viewSize.width-viewRect.x > viewRect.width); break; case TOP: default: tabPane.repaint(vpRect.x, vpRect.y+vpRect.height, vpRect.width, contentInsets.top); scrollBackwardButton.setEnabled( viewRect.x > 0 && leadingTabIndex > 0); scrollForwardButton.setEnabled( leadingTabIndex < tabCount-1 && viewSize.width-viewRect.x > viewRect.width); } } /** {@collect.stats} * ActionListener for the scroll buttons. */ public void actionPerformed(ActionEvent e) { ActionMap map = tabPane.getActionMap(); if (map != null) { String actionKey; if (e.getSource() == scrollForwardButton) { actionKey = "scrollTabsForwardAction"; } else { actionKey = "scrollTabsBackwardAction"; } Action action = map.get(actionKey); if (action != null && action.isEnabled()) { action.actionPerformed(new ActionEvent(tabPane, ActionEvent.ACTION_PERFORMED, null, e.getWhen(), e.getModifiers())); } } } public String toString() { return new String("viewport.viewSize="+viewport.getViewSize()+"\n"+ "viewport.viewRectangle="+viewport.getViewRect()+"\n"+ "leadingTabIndex="+leadingTabIndex+"\n"+ "tabViewPosition="+tabViewPosition); } } private class ScrollableTabViewport extends JViewport implements UIResource { public ScrollableTabViewport() { super(); setName("TabbedPane.scrollableViewport"); setScrollMode(SIMPLE_SCROLL_MODE); setOpaque(tabPane.isOpaque()); Color bgColor = UIManager.getColor("TabbedPane.tabAreaBackground"); if (bgColor == null) { bgColor = tabPane.getBackground(); } setBackground(bgColor); } } private class ScrollableTabPanel extends JPanel implements UIResource { public ScrollableTabPanel() { super(null); setOpaque(tabPane.isOpaque()); Color bgColor = UIManager.getColor("TabbedPane.tabAreaBackground"); if (bgColor == null) { bgColor = tabPane.getBackground(); } setBackground(bgColor); } public void paintComponent(Graphics g) { super.paintComponent(g); BasicTabbedPaneUI.this.paintTabArea(g, tabPane.getTabPlacement(), tabPane.getSelectedIndex()); if (tabScroller.croppedEdge.isParamsSet() && tabContainer == null) { Rectangle croppedRect = rects[tabScroller.croppedEdge.getTabIndex()]; g.translate(croppedRect.x, croppedRect.y); tabScroller.croppedEdge.paintComponent(g); g.translate(-croppedRect.x, -croppedRect.y); } } public void doLayout() { if (getComponentCount() > 0) { Component child = getComponent(0); child.setBounds(0, 0, getWidth(), getHeight()); } } } private class ScrollableTabButton extends BasicArrowButton implements UIResource, SwingConstants { public ScrollableTabButton(int direction) { super(direction, UIManager.getColor("TabbedPane.selected"), UIManager.getColor("TabbedPane.shadow"), UIManager.getColor("TabbedPane.darkShadow"), UIManager.getColor("TabbedPane.highlight")); } } // Controller: event listeners private class Handler implements ChangeListener, ContainerListener, FocusListener, MouseListener, MouseMotionListener, PropertyChangeListener { // // PropertyChangeListener // public void propertyChange(PropertyChangeEvent e) { JTabbedPane pane = (JTabbedPane)e.getSource(); String name = e.getPropertyName(); boolean isScrollLayout = scrollableTabLayoutEnabled(); if (name == "mnemonicAt") { updateMnemonics(); pane.repaint(); } else if (name == "displayedMnemonicIndexAt") { pane.repaint(); } else if (name =="indexForTitle") { calculatedBaseline = false; updateHtmlViews((Integer)e.getNewValue()); } else if (name == "tabLayoutPolicy") { BasicTabbedPaneUI.this.uninstallUI(pane); BasicTabbedPaneUI.this.installUI(pane); calculatedBaseline = false; } else if (name == "tabPlacement") { if (scrollableTabLayoutEnabled()) { tabScroller.createButtons(); } calculatedBaseline = false; } else if (name == "opaque" && isScrollLayout) { boolean newVal = ((Boolean)e.getNewValue()).booleanValue(); tabScroller.tabPanel.setOpaque(newVal); tabScroller.viewport.setOpaque(newVal); } else if (name == "background" && isScrollLayout) { Color newVal = (Color)e.getNewValue(); tabScroller.tabPanel.setBackground(newVal); tabScroller.viewport.setBackground(newVal); Color newColor = selectedColor == null ? newVal : selectedColor; tabScroller.scrollForwardButton.setBackground(newColor); tabScroller.scrollBackwardButton.setBackground(newColor); } else if (name == "indexForTabComponent") { if (tabContainer != null) { tabContainer.removeUnusedTabComponents(); } Component c = tabPane.getTabComponentAt( (Integer)e.getNewValue()); if (c != null) { if (tabContainer == null) { installTabContainer(); } else { tabContainer.add(c); } } tabPane.revalidate(); tabPane.repaint(); calculatedBaseline = false; } else if (name == "indexForNullComponent") { isRunsDirty = true; updateHtmlViews((Integer)e.getNewValue()); } else if (name == "font") { calculatedBaseline = false; } } private void updateHtmlViews(int index) { String title = tabPane.getTitleAt(index); boolean isHTML = BasicHTML.isHTMLString(title); if (isHTML) { if (htmlViews==null) { // Initialize vector htmlViews = createHTMLVector(); } else { // Vector already exists View v = BasicHTML.createHTMLView(tabPane, title); htmlViews.insertElementAt(v, index); } } else { // Not HTML if (htmlViews!=null) { // Add placeholder htmlViews.insertElementAt(null, index); } // else nada! } updateMnemonics(); } // // ChangeListener // public void stateChanged(ChangeEvent e) { JTabbedPane tabPane = (JTabbedPane)e.getSource(); tabPane.revalidate(); tabPane.repaint(); setFocusIndex(tabPane.getSelectedIndex(), false); if (scrollableTabLayoutEnabled()) { int index = tabPane.getSelectedIndex(); if (index < rects.length && index != -1) { tabScroller.tabPanel.scrollRectToVisible( (Rectangle)rects[index].clone()); } } } // // MouseListener // public void mouseClicked(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { setRolloverTab(e.getX(), e.getY()); } public void mouseExited(MouseEvent e) { setRolloverTab(-1); } public void mousePressed(MouseEvent e) { if (!tabPane.isEnabled()) { return; } int tabIndex = tabForCoordinate(tabPane, e.getX(), e.getY()); if (tabIndex >= 0 && tabPane.isEnabledAt(tabIndex)) { if (tabIndex != tabPane.getSelectedIndex()) { // Clicking on unselected tab, change selection, do NOT // request focus. // This will trigger the focusIndex to change by way // of stateChanged. tabPane.setSelectedIndex(tabIndex); } else if (tabPane.isRequestFocusEnabled()) { // Clicking on selected tab, try and give the tabbedpane // focus. Repaint will occur in focusGained. tabPane.requestFocus(); } } } // // MouseMotionListener // public void mouseDragged(MouseEvent e) { } public void mouseMoved(MouseEvent e) { setRolloverTab(e.getX(), e.getY()); } // // FocusListener // public void focusGained(FocusEvent e) { setFocusIndex(tabPane.getSelectedIndex(), true); } public void focusLost(FocusEvent e) { repaintTab(focusIndex); } // // ContainerListener // /* GES 2/3/99: The container listener code was added to support HTML rendering of tab titles. Ideally, we would be able to listen for property changes when a tab is added or its text modified. At the moment there are no such events because the Beans spec doesn't allow 'indexed' property changes (i.e. tab 2's text changed from A to B). In order to get around this, we listen for tabs to be added or removed by listening for the container events. we then queue up a runnable (so the component has a chance to complete the add) which checks the tab title of the new component to see if it requires HTML rendering. The Views (one per tab title requiring HTML rendering) are stored in the htmlViews Vector, which is only allocated after the first time we run into an HTML tab. Note that this vector is kept in step with the number of pages, and nulls are added for those pages whose tab title do not require HTML rendering. This makes it easy for the paint and layout code to tell whether to invoke the HTML engine without having to check the string during time-sensitive operations. When we have added a way to listen for tab additions and changes to tab text, this code should be removed and replaced by something which uses that. */ public void componentAdded(ContainerEvent e) { JTabbedPane tp = (JTabbedPane)e.getContainer(); Component child = e.getChild(); if (child instanceof UIResource) { return; } isRunsDirty = true; updateHtmlViews(tp.indexOfComponent(child)); } public void componentRemoved(ContainerEvent e) { JTabbedPane tp = (JTabbedPane)e.getContainer(); Component child = e.getChild(); if (child instanceof UIResource) { return; } // NOTE 4/15/2002 (joutwate): // This fix is implemented using client properties since there is // currently no IndexPropertyChangeEvent. Once // IndexPropertyChangeEvents have been added this code should be // modified to use it. Integer indexObj = (Integer)tp.getClientProperty("__index_to_remove__"); if (indexObj != null) { int index = indexObj.intValue(); if (htmlViews != null && htmlViews.size() > index) { htmlViews.removeElementAt(index); } tp.putClientProperty("__index_to_remove__", null); } isRunsDirty = true; updateMnemonics(); validateFocusIndex(); } } /** {@collect.stats} * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicTabbedPaneUI. */ public class PropertyChangeHandler implements PropertyChangeListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void propertyChange(PropertyChangeEvent e) { getHandler().propertyChange(e); } } /** {@collect.stats} * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicTabbedPaneUI. */ public class TabSelectionHandler implements ChangeListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void stateChanged(ChangeEvent e) { getHandler().stateChanged(e); } } /** {@collect.stats} * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicTabbedPaneUI. */ public class MouseHandler extends MouseAdapter { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void mousePressed(MouseEvent e) { getHandler().mousePressed(e); } } /** {@collect.stats} * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicTabbedPaneUI. */ public class FocusHandler extends FocusAdapter { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void focusGained(FocusEvent e) { getHandler().focusGained(e); } public void focusLost(FocusEvent e) { getHandler().focusLost(e); } } private Vector createHTMLVector() { Vector htmlViews = new Vector(); int count = tabPane.getTabCount(); if (count>0) { for (int i=0 ; i<count; i++) { String title = tabPane.getTitleAt(i); if (BasicHTML.isHTMLString(title)) { htmlViews.addElement(BasicHTML.createHTMLView(tabPane, title)); } else { htmlViews.addElement(null); } } } return htmlViews; } private class TabContainer extends JPanel implements UIResource { private boolean notifyTabbedPane = true; public TabContainer() { super(null); setOpaque(false); } public void remove(Component comp) { int index = tabPane.indexOfTabComponent(comp); super.remove(comp); if (notifyTabbedPane && index != -1) { tabPane.setTabComponentAt(index, null); } } private void removeUnusedTabComponents() { for (Component c : getComponents()) { if (!(c instanceof UIResource)) { int index = tabPane.indexOfTabComponent(c); if (index == -1) { super.remove(c); } } } } public boolean isOptimizedDrawingEnabled() { return tabScroller != null && !tabScroller.croppedEdge.isParamsSet(); } public void doLayout() { // We layout tabComponents in JTabbedPane's layout manager // and use this method as a hook for repainting tabs // to update tabs area e.g. when the size of tabComponent was changed if (scrollableTabLayoutEnabled()) { tabScroller.tabPanel.repaint(); tabScroller.updateView(); } else { tabPane.repaint(getBounds()); } } } private class CroppedEdge extends JPanel implements UIResource { private Shape shape; private int tabIndex; private int cropline; private int cropx, cropy; public CroppedEdge() { setOpaque(false); } public void setParams(int tabIndex, int cropline, int cropx, int cropy) { this.tabIndex = tabIndex; this.cropline = cropline; this.cropx = cropx; this.cropy = cropy; Rectangle tabRect = rects[tabIndex]; setBounds(tabRect); shape = createCroppedTabShape(tabPane.getTabPlacement(), tabRect, cropline); if (getParent() == null && tabContainer != null) { tabContainer.add(this, 0); } } public void resetParams() { shape = null; if (getParent() == tabContainer && tabContainer != null) { tabContainer.remove(this); } } public boolean isParamsSet() { return shape != null; } public int getTabIndex() { return tabIndex; } public int getCropline() { return cropline; } public int getCroppedSideWidth() { return 3; } private Color getBgColor() { Component parent = tabPane.getParent(); if (parent != null) { Color bg = parent.getBackground(); if (bg != null) { return bg; } } return UIManager.getColor("control"); } protected void paintComponent(Graphics g) { super.paintComponent(g); if (isParamsSet() && g instanceof Graphics2D) { Graphics2D g2 = (Graphics2D) g; g2.clipRect(0, 0, getWidth(), getHeight()); g2.setColor(getBgColor()); g2.translate(cropx, cropy); g2.fill(shape); paintCroppedTabEdge(g); g2.translate(-cropx, -cropy); } } } }
Java
/* * Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import java.util.Enumeration; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.*; import javax.swing.table.*; import javax.swing.plaf.basic.DragRecognitionSupport.BeforeDrag; import sun.swing.SwingUtilities2; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import sun.swing.DefaultLookup; import sun.swing.UIAction; /** {@collect.stats} * BasicTableUI implementation * * @author Philip Milne * @author Shannon Hickey (drag and drop) */ public class BasicTableUI extends TableUI { private static final Object BASELINE_COMPONENT_KEY = new Object(); // Table.baselineComponent // // Instance Variables // // The JTable that is delegating the painting to this UI. protected JTable table; protected CellRendererPane rendererPane; // Listeners that are attached to the JTable protected KeyListener keyListener; protected FocusListener focusListener; protected MouseInputListener mouseInputListener; private Handler handler; /** {@collect.stats} * Local cache of Table's client property "Table.isFileList" */ private boolean isFileList = false; // // Helper class for keyboard actions // private static class Actions extends UIAction { private static final String CANCEL_EDITING = "cancel"; private static final String SELECT_ALL = "selectAll"; private static final String CLEAR_SELECTION = "clearSelection"; private static final String START_EDITING = "startEditing"; private static final String NEXT_ROW = "selectNextRow"; private static final String NEXT_ROW_CELL = "selectNextRowCell"; private static final String NEXT_ROW_EXTEND_SELECTION = "selectNextRowExtendSelection"; private static final String NEXT_ROW_CHANGE_LEAD = "selectNextRowChangeLead"; private static final String PREVIOUS_ROW = "selectPreviousRow"; private static final String PREVIOUS_ROW_CELL = "selectPreviousRowCell"; private static final String PREVIOUS_ROW_EXTEND_SELECTION = "selectPreviousRowExtendSelection"; private static final String PREVIOUS_ROW_CHANGE_LEAD = "selectPreviousRowChangeLead"; private static final String NEXT_COLUMN = "selectNextColumn"; private static final String NEXT_COLUMN_CELL = "selectNextColumnCell"; private static final String NEXT_COLUMN_EXTEND_SELECTION = "selectNextColumnExtendSelection"; private static final String NEXT_COLUMN_CHANGE_LEAD = "selectNextColumnChangeLead"; private static final String PREVIOUS_COLUMN = "selectPreviousColumn"; private static final String PREVIOUS_COLUMN_CELL = "selectPreviousColumnCell"; private static final String PREVIOUS_COLUMN_EXTEND_SELECTION = "selectPreviousColumnExtendSelection"; private static final String PREVIOUS_COLUMN_CHANGE_LEAD = "selectPreviousColumnChangeLead"; private static final String SCROLL_LEFT_CHANGE_SELECTION = "scrollLeftChangeSelection"; private static final String SCROLL_LEFT_EXTEND_SELECTION = "scrollLeftExtendSelection"; private static final String SCROLL_RIGHT_CHANGE_SELECTION = "scrollRightChangeSelection"; private static final String SCROLL_RIGHT_EXTEND_SELECTION = "scrollRightExtendSelection"; private static final String SCROLL_UP_CHANGE_SELECTION = "scrollUpChangeSelection"; private static final String SCROLL_UP_EXTEND_SELECTION = "scrollUpExtendSelection"; private static final String SCROLL_DOWN_CHANGE_SELECTION = "scrollDownChangeSelection"; private static final String SCROLL_DOWN_EXTEND_SELECTION = "scrollDownExtendSelection"; private static final String FIRST_COLUMN = "selectFirstColumn"; private static final String FIRST_COLUMN_EXTEND_SELECTION = "selectFirstColumnExtendSelection"; private static final String LAST_COLUMN = "selectLastColumn"; private static final String LAST_COLUMN_EXTEND_SELECTION = "selectLastColumnExtendSelection"; private static final String FIRST_ROW = "selectFirstRow"; private static final String FIRST_ROW_EXTEND_SELECTION = "selectFirstRowExtendSelection"; private static final String LAST_ROW = "selectLastRow"; private static final String LAST_ROW_EXTEND_SELECTION = "selectLastRowExtendSelection"; // add the lead item to the selection without changing lead or anchor private static final String ADD_TO_SELECTION = "addToSelection"; // toggle the selected state of the lead item and move the anchor to it private static final String TOGGLE_AND_ANCHOR = "toggleAndAnchor"; // extend the selection to the lead item private static final String EXTEND_TO = "extendTo"; // move the anchor to the lead and ensure only that item is selected private static final String MOVE_SELECTION_TO = "moveSelectionTo"; // give focus to the JTableHeader, if one exists private static final String FOCUS_HEADER = "focusHeader"; protected int dx; protected int dy; protected boolean extend; protected boolean inSelection; // horizontally, forwards always means right, // regardless of component orientation protected boolean forwards; protected boolean vertically; protected boolean toLimit; protected int leadRow; protected int leadColumn; Actions(String name) { super(name); } Actions(String name, int dx, int dy, boolean extend, boolean inSelection) { super(name); // Actions spcifying true for "inSelection" are // fairly sensitive to bad parameter values. They require // that one of dx and dy be 0 and the other be -1 or 1. // Bogus parameter values could cause an infinite loop. // To prevent any problems we massage the params here // and complain if we get something we can't deal with. if (inSelection) { this.inSelection = true; // look at the sign of dx and dy only dx = sign(dx); dy = sign(dy); // make sure one is zero, but not both assert (dx == 0 || dy == 0) && !(dx == 0 && dy == 0); } this.dx = dx; this.dy = dy; this.extend = extend; } Actions(String name, boolean extend, boolean forwards, boolean vertically, boolean toLimit) { this(name, 0, 0, extend, false); this.forwards = forwards; this.vertically = vertically; this.toLimit = toLimit; } private static int clipToRange(int i, int a, int b) { return Math.min(Math.max(i, a), b-1); } private void moveWithinTableRange(JTable table, int dx, int dy) { leadRow = clipToRange(leadRow+dy, 0, table.getRowCount()); leadColumn = clipToRange(leadColumn+dx, 0, table.getColumnCount()); } private static int sign(int num) { return (num < 0) ? -1 : ((num == 0) ? 0 : 1); } /** {@collect.stats} * Called to move within the selected range of the given JTable. * This method uses the table's notion of selection, which is * important to allow the user to navigate between items visually * selected on screen. This notion may or may not be the same as * what could be determined by directly querying the selection models. * It depends on certain table properties (such as whether or not * row or column selection is allowed). When performing modifications, * it is recommended that caution be taken in order to preserve * the intent of this method, especially when deciding whether to * query the selection models or interact with JTable directly. */ private boolean moveWithinSelectedRange(JTable table, int dx, int dy, ListSelectionModel rsm, ListSelectionModel csm) { // Note: The Actions constructor ensures that only one of // dx and dy is 0, and the other is either -1 or 1 // find out how many items the table is showing as selected // and the range of items to navigate through int totalCount; int minX, maxX, minY, maxY; boolean rs = table.getRowSelectionAllowed(); boolean cs = table.getColumnSelectionAllowed(); // both column and row selection if (rs && cs) { totalCount = table.getSelectedRowCount() * table.getSelectedColumnCount(); minX = csm.getMinSelectionIndex(); maxX = csm.getMaxSelectionIndex(); minY = rsm.getMinSelectionIndex(); maxY = rsm.getMaxSelectionIndex(); // row selection only } else if (rs) { totalCount = table.getSelectedRowCount(); minX = 0; maxX = table.getColumnCount() - 1; minY = rsm.getMinSelectionIndex(); maxY = rsm.getMaxSelectionIndex(); // column selection only } else if (cs) { totalCount = table.getSelectedColumnCount(); minX = csm.getMinSelectionIndex(); maxX = csm.getMaxSelectionIndex(); minY = 0; maxY = table.getRowCount() - 1; // no selection allowed } else { totalCount = 0; // A bogus assignment to stop javac from complaining // about unitialized values. In this case, these // won't even be used. minX = maxX = minY = maxY = 0; } // For some cases, there is no point in trying to stay within the // selected area. Instead, move outside the selection, wrapping at // the table boundaries. The cases are: boolean stayInSelection; // - nothing selected if (totalCount == 0 || // - one item selected, and the lead is already selected (totalCount == 1 && table.isCellSelected(leadRow, leadColumn))) { stayInSelection = false; maxX = table.getColumnCount() - 1; maxY = table.getRowCount() - 1; // the mins are calculated like this in case the max is -1 minX = Math.min(0, maxX); minY = Math.min(0, maxY); } else { stayInSelection = true; } // the algorithm below isn't prepared to deal with -1 lead/anchor // so massage appropriately here first if (dy == 1 && leadColumn == -1) { leadColumn = minX; leadRow = -1; } else if (dx == 1 && leadRow == -1) { leadRow = minY; leadColumn = -1; } else if (dy == -1 && leadColumn == -1) { leadColumn = maxX; leadRow = maxY + 1; } else if (dx == -1 && leadRow == -1) { leadRow = maxY; leadColumn = maxX + 1; } // In cases where the lead is not within the search range, // we need to bring it within one cell for the the search // to work properly. Check these here. leadRow = Math.min(Math.max(leadRow, minY - 1), maxY + 1); leadColumn = Math.min(Math.max(leadColumn, minX - 1), maxX + 1); // find the next position, possibly looping until it is selected do { calcNextPos(dx, minX, maxX, dy, minY, maxY); } while (stayInSelection && !table.isCellSelected(leadRow, leadColumn)); return stayInSelection; } /** {@collect.stats} * Find the next lead row and column based on the given * dx/dy and max/min values. */ private void calcNextPos(int dx, int minX, int maxX, int dy, int minY, int maxY) { if (dx != 0) { leadColumn += dx; if (leadColumn > maxX) { leadColumn = minX; leadRow++; if (leadRow > maxY) { leadRow = minY; } } else if (leadColumn < minX) { leadColumn = maxX; leadRow--; if (leadRow < minY) { leadRow = maxY; } } } else { leadRow += dy; if (leadRow > maxY) { leadRow = minY; leadColumn++; if (leadColumn > maxX) { leadColumn = minX; } } else if (leadRow < minY) { leadRow = maxY; leadColumn--; if (leadColumn < minX) { leadColumn = maxX; } } } } public void actionPerformed(ActionEvent e) { String key = getName(); JTable table = (JTable)e.getSource(); ListSelectionModel rsm = table.getSelectionModel(); leadRow = getAdjustedLead(table, true, rsm); ListSelectionModel csm = table.getColumnModel().getSelectionModel(); leadColumn = getAdjustedLead(table, false, csm); if (key == SCROLL_LEFT_CHANGE_SELECTION || // Paging Actions key == SCROLL_LEFT_EXTEND_SELECTION || key == SCROLL_RIGHT_CHANGE_SELECTION || key == SCROLL_RIGHT_EXTEND_SELECTION || key == SCROLL_UP_CHANGE_SELECTION || key == SCROLL_UP_EXTEND_SELECTION || key == SCROLL_DOWN_CHANGE_SELECTION || key == SCROLL_DOWN_EXTEND_SELECTION || key == FIRST_COLUMN || key == FIRST_COLUMN_EXTEND_SELECTION || key == FIRST_ROW || key == FIRST_ROW_EXTEND_SELECTION || key == LAST_COLUMN || key == LAST_COLUMN_EXTEND_SELECTION || key == LAST_ROW || key == LAST_ROW_EXTEND_SELECTION) { if (toLimit) { if (vertically) { int rowCount = table.getRowCount(); this.dx = 0; this.dy = forwards ? rowCount : -rowCount; } else { int colCount = table.getColumnCount(); this.dx = forwards ? colCount : -colCount; this.dy = 0; } } else { if (!(table.getParent().getParent() instanceof JScrollPane)) { return; } Dimension delta = table.getParent().getSize(); if (vertically) { Rectangle r = table.getCellRect(leadRow, 0, true); if (forwards) { // scroll by at least one cell r.y += Math.max(delta.height, r.height); } else { r.y -= delta.height; } this.dx = 0; int newRow = table.rowAtPoint(r.getLocation()); if (newRow == -1 && forwards) { newRow = table.getRowCount(); } this.dy = newRow - leadRow; } else { Rectangle r = table.getCellRect(0, leadColumn, true); if (forwards) { // scroll by at least one cell r.x += Math.max(delta.width, r.width); } else { r.x -= delta.width; } int newColumn = table.columnAtPoint(r.getLocation()); if (newColumn == -1) { boolean ltr = table.getComponentOrientation().isLeftToRight(); newColumn = forwards ? (ltr ? table.getColumnCount() : 0) : (ltr ? 0 : table.getColumnCount()); } this.dx = newColumn - leadColumn; this.dy = 0; } } } if (key == NEXT_ROW || // Navigate Actions key == NEXT_ROW_CELL || key == NEXT_ROW_EXTEND_SELECTION || key == NEXT_ROW_CHANGE_LEAD || key == NEXT_COLUMN || key == NEXT_COLUMN_CELL || key == NEXT_COLUMN_EXTEND_SELECTION || key == NEXT_COLUMN_CHANGE_LEAD || key == PREVIOUS_ROW || key == PREVIOUS_ROW_CELL || key == PREVIOUS_ROW_EXTEND_SELECTION || key == PREVIOUS_ROW_CHANGE_LEAD || key == PREVIOUS_COLUMN || key == PREVIOUS_COLUMN_CELL || key == PREVIOUS_COLUMN_EXTEND_SELECTION || key == PREVIOUS_COLUMN_CHANGE_LEAD || // Paging Actions. key == SCROLL_LEFT_CHANGE_SELECTION || key == SCROLL_LEFT_EXTEND_SELECTION || key == SCROLL_RIGHT_CHANGE_SELECTION || key == SCROLL_RIGHT_EXTEND_SELECTION || key == SCROLL_UP_CHANGE_SELECTION || key == SCROLL_UP_EXTEND_SELECTION || key == SCROLL_DOWN_CHANGE_SELECTION || key == SCROLL_DOWN_EXTEND_SELECTION || key == FIRST_COLUMN || key == FIRST_COLUMN_EXTEND_SELECTION || key == FIRST_ROW || key == FIRST_ROW_EXTEND_SELECTION || key == LAST_COLUMN || key == LAST_COLUMN_EXTEND_SELECTION || key == LAST_ROW || key == LAST_ROW_EXTEND_SELECTION) { if (table.isEditing() && !table.getCellEditor().stopCellEditing()) { return; } // Unfortunately, this strategy introduces bugs because // of the asynchronous nature of requestFocus() call below. // Introducing a delay with invokeLater() makes this work // in the typical case though race conditions then allow // focus to disappear altogether. The right solution appears // to be to fix requestFocus() so that it queues a request // for the focus regardless of who owns the focus at the // time the call to requestFocus() is made. The optimisation // to ignore the call to requestFocus() when the component // already has focus may ligitimately be made as the // request focus event is dequeued, not before. // boolean wasEditingWithFocus = table.isEditing() && // table.getEditorComponent().isFocusOwner(); boolean changeLead = false; if (key == NEXT_ROW_CHANGE_LEAD || key == PREVIOUS_ROW_CHANGE_LEAD) { changeLead = (rsm.getSelectionMode() == ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); } else if (key == NEXT_COLUMN_CHANGE_LEAD || key == PREVIOUS_COLUMN_CHANGE_LEAD) { changeLead = (csm.getSelectionMode() == ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); } if (changeLead) { moveWithinTableRange(table, dx, dy); if (dy != 0) { // casting should be safe since the action is only enabled // for DefaultListSelectionModel ((DefaultListSelectionModel)rsm).moveLeadSelectionIndex(leadRow); if (getAdjustedLead(table, false, csm) == -1 && table.getColumnCount() > 0) { ((DefaultListSelectionModel)csm).moveLeadSelectionIndex(0); } } else { // casting should be safe since the action is only enabled // for DefaultListSelectionModel ((DefaultListSelectionModel)csm).moveLeadSelectionIndex(leadColumn); if (getAdjustedLead(table, true, rsm) == -1 && table.getRowCount() > 0) { ((DefaultListSelectionModel)rsm).moveLeadSelectionIndex(0); } } Rectangle cellRect = table.getCellRect(leadRow, leadColumn, false); if (cellRect != null) { table.scrollRectToVisible(cellRect); } } else if (!inSelection) { moveWithinTableRange(table, dx, dy); table.changeSelection(leadRow, leadColumn, false, extend); } else { if (table.getRowCount() <= 0 || table.getColumnCount() <= 0) { // bail - don't try to move selection on an empty table return; } if (moveWithinSelectedRange(table, dx, dy, rsm, csm)) { // this is the only way we have to set both the lead // and the anchor without changing the selection if (rsm.isSelectedIndex(leadRow)) { rsm.addSelectionInterval(leadRow, leadRow); } else { rsm.removeSelectionInterval(leadRow, leadRow); } if (csm.isSelectedIndex(leadColumn)) { csm.addSelectionInterval(leadColumn, leadColumn); } else { csm.removeSelectionInterval(leadColumn, leadColumn); } Rectangle cellRect = table.getCellRect(leadRow, leadColumn, false); if (cellRect != null) { table.scrollRectToVisible(cellRect); } } else { table.changeSelection(leadRow, leadColumn, false, false); } } /* if (wasEditingWithFocus) { table.editCellAt(leadRow, leadColumn); final Component editorComp = table.getEditorComponent(); if (editorComp != null) { SwingUtilities.invokeLater(new Runnable() { public void run() { editorComp.requestFocus(); } }); } } */ } else if (key == CANCEL_EDITING) { table.removeEditor(); } else if (key == SELECT_ALL) { table.selectAll(); } else if (key == CLEAR_SELECTION) { table.clearSelection(); } else if (key == START_EDITING) { if (!table.hasFocus()) { CellEditor cellEditor = table.getCellEditor(); if (cellEditor != null && !cellEditor.stopCellEditing()) { return; } table.requestFocus(); return; } table.editCellAt(leadRow, leadColumn, e); Component editorComp = table.getEditorComponent(); if (editorComp != null) { editorComp.requestFocus(); } } else if (key == ADD_TO_SELECTION) { if (!table.isCellSelected(leadRow, leadColumn)) { int oldAnchorRow = rsm.getAnchorSelectionIndex(); int oldAnchorColumn = csm.getAnchorSelectionIndex(); rsm.setValueIsAdjusting(true); csm.setValueIsAdjusting(true); table.changeSelection(leadRow, leadColumn, true, false); rsm.setAnchorSelectionIndex(oldAnchorRow); csm.setAnchorSelectionIndex(oldAnchorColumn); rsm.setValueIsAdjusting(false); csm.setValueIsAdjusting(false); } } else if (key == TOGGLE_AND_ANCHOR) { table.changeSelection(leadRow, leadColumn, true, false); } else if (key == EXTEND_TO) { table.changeSelection(leadRow, leadColumn, false, true); } else if (key == MOVE_SELECTION_TO) { table.changeSelection(leadRow, leadColumn, false, false); } else if (key == FOCUS_HEADER) { JTableHeader th = table.getTableHeader(); if (th != null) { //Set the header's selected column to match the table. int col = table.getSelectedColumn(); if (col >= 0) { TableHeaderUI thUI = th.getUI(); if (thUI instanceof BasicTableHeaderUI) { ((BasicTableHeaderUI)thUI).selectColumn(col); } } //Then give the header the focus. th.requestFocusInWindow(); } } } public boolean isEnabled(Object sender) { String key = getName(); if (sender instanceof JTable && Boolean.TRUE.equals(((JTable)sender).getClientProperty("Table.isFileList"))) { if (key == NEXT_COLUMN || key == NEXT_COLUMN_CELL || key == NEXT_COLUMN_EXTEND_SELECTION || key == NEXT_COLUMN_CHANGE_LEAD || key == PREVIOUS_COLUMN || key == PREVIOUS_COLUMN_CELL || key == PREVIOUS_COLUMN_EXTEND_SELECTION || key == PREVIOUS_COLUMN_CHANGE_LEAD || key == SCROLL_LEFT_CHANGE_SELECTION || key == SCROLL_LEFT_EXTEND_SELECTION || key == SCROLL_RIGHT_CHANGE_SELECTION || key == SCROLL_RIGHT_EXTEND_SELECTION || key == FIRST_COLUMN || key == FIRST_COLUMN_EXTEND_SELECTION || key == LAST_COLUMN || key == LAST_COLUMN_EXTEND_SELECTION || key == NEXT_ROW_CELL || key == PREVIOUS_ROW_CELL) { return false; } } if (key == CANCEL_EDITING && sender instanceof JTable) { return ((JTable)sender).isEditing(); } else if (key == NEXT_ROW_CHANGE_LEAD || key == PREVIOUS_ROW_CHANGE_LEAD) { // discontinuous selection actions are only enabled for // DefaultListSelectionModel return sender != null && ((JTable)sender).getSelectionModel() instanceof DefaultListSelectionModel; } else if (key == NEXT_COLUMN_CHANGE_LEAD || key == PREVIOUS_COLUMN_CHANGE_LEAD) { // discontinuous selection actions are only enabled for // DefaultListSelectionModel return sender != null && ((JTable)sender).getColumnModel().getSelectionModel() instanceof DefaultListSelectionModel; } else if (key == ADD_TO_SELECTION && sender instanceof JTable) { // This action is typically bound to SPACE. // If the table is already in an editing mode, SPACE should // simply enter a space character into the table, and not // select a cell. Likewise, if the lead cell is already selected // then hitting SPACE should just enter a space character // into the cell and begin editing. In both of these cases // this action will be disabled. JTable table = (JTable)sender; int leadRow = getAdjustedLead(table, true); int leadCol = getAdjustedLead(table, false); return !(table.isEditing() || table.isCellSelected(leadRow, leadCol)); } else if (key == FOCUS_HEADER && sender instanceof JTable) { JTable table = (JTable)sender; return table.getTableHeader() != null; } return true; } } // // The Table's Key listener // /** {@collect.stats} * This inner class is marked &quot;public&quot; due to a compiler bug. * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicTableUI. * <p>As of Java 2 platform v1.3 this class is no longer used. * Instead <code>JTable</code> * overrides <code>processKeyBinding</code> to dispatch the event to * the current <code>TableCellEditor</code>. */ public class KeyHandler implements KeyListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void keyPressed(KeyEvent e) { getHandler().keyPressed(e); } public void keyReleased(KeyEvent e) { getHandler().keyReleased(e); } public void keyTyped(KeyEvent e) { getHandler().keyTyped(e); } } // // The Table's focus listener // /** {@collect.stats} * This inner class is marked &quot;public&quot; due to a compiler bug. * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicTableUI. */ public class FocusHandler implements FocusListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void focusGained(FocusEvent e) { getHandler().focusGained(e); } public void focusLost(FocusEvent e) { getHandler().focusLost(e); } } // // The Table's mouse and mouse motion listeners // /** {@collect.stats} * This inner class is marked &quot;public&quot; due to a compiler bug. * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicTableUI. */ public class MouseInputHandler implements MouseInputListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void mouseClicked(MouseEvent e) { getHandler().mouseClicked(e); } public void mousePressed(MouseEvent e) { getHandler().mousePressed(e); } public void mouseReleased(MouseEvent e) { getHandler().mouseReleased(e); } public void mouseEntered(MouseEvent e) { getHandler().mouseEntered(e); } public void mouseExited(MouseEvent e) { getHandler().mouseExited(e); } public void mouseMoved(MouseEvent e) { getHandler().mouseMoved(e); } public void mouseDragged(MouseEvent e) { getHandler().mouseDragged(e); } } private class Handler implements FocusListener, MouseInputListener, PropertyChangeListener, ListSelectionListener, ActionListener, BeforeDrag { // FocusListener private void repaintLeadCell( ) { int lr = getAdjustedLead(table, true); int lc = getAdjustedLead(table, false); if (lr < 0 || lc < 0) { return; } Rectangle dirtyRect = table.getCellRect(lr, lc, false); table.repaint(dirtyRect); } public void focusGained(FocusEvent e) { repaintLeadCell(); } public void focusLost(FocusEvent e) { repaintLeadCell(); } // KeyListener public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { KeyStroke keyStroke = KeyStroke.getKeyStroke(e.getKeyChar(), e.getModifiers()); // We register all actions using ANCESTOR_OF_FOCUSED_COMPONENT // which means that we might perform the appropriate action // in the table and then forward it to the editor if the editor // had focus. Make sure this doesn't happen by checking our // InputMaps. InputMap map = table.getInputMap(JComponent.WHEN_FOCUSED); if (map != null && map.get(keyStroke) != null) { return; } map = table.getInputMap(JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); if (map != null && map.get(keyStroke) != null) { return; } keyStroke = KeyStroke.getKeyStrokeForEvent(e); // The AWT seems to generate an unconsumed \r event when // ENTER (\n) is pressed. if (e.getKeyChar() == '\r') { return; } int leadRow = getAdjustedLead(table, true); int leadColumn = getAdjustedLead(table, false); if (leadRow != -1 && leadColumn != -1 && !table.isEditing()) { if (!table.editCellAt(leadRow, leadColumn)) { return; } } // Forwarding events this way seems to put the component // in a state where it believes it has focus. In reality // the table retains focus - though it is difficult for // a user to tell, since the caret is visible and flashing. // Calling table.requestFocus() here, to get the focus back to // the table, seems to have no effect. Component editorComp = table.getEditorComponent(); if (table.isEditing() && editorComp != null) { if (editorComp instanceof JComponent) { JComponent component = (JComponent)editorComp; map = component.getInputMap(JComponent.WHEN_FOCUSED); Object binding = (map != null) ? map.get(keyStroke) : null; if (binding == null) { map = component.getInputMap(JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); binding = (map != null) ? map.get(keyStroke) : null; } if (binding != null) { ActionMap am = component.getActionMap(); Action action = (am != null) ? am.get(binding) : null; if (action != null && SwingUtilities. notifyAction(action, keyStroke, e, component, e.getModifiers())) { e.consume(); } } } } } // MouseInputListener // Component receiving mouse events during editing. // May not be editorComponent. private Component dispatchComponent; public void mouseClicked(MouseEvent e) {} private void setDispatchComponent(MouseEvent e) { Component editorComponent = table.getEditorComponent(); Point p = e.getPoint(); Point p2 = SwingUtilities.convertPoint(table, p, editorComponent); dispatchComponent = SwingUtilities.getDeepestComponentAt(editorComponent, p2.x, p2.y); SwingUtilities2.setSkipClickCount(dispatchComponent, e.getClickCount() - 1); } private boolean repostEvent(MouseEvent e) { // Check for isEditing() in case another event has // caused the editor to be removed. See bug #4306499. if (dispatchComponent == null || !table.isEditing()) { return false; } MouseEvent e2 = SwingUtilities.convertMouseEvent(table, e, dispatchComponent); dispatchComponent.dispatchEvent(e2); return true; } private void setValueIsAdjusting(boolean flag) { table.getSelectionModel().setValueIsAdjusting(flag); table.getColumnModel().getSelectionModel(). setValueIsAdjusting(flag); } // The row and column where the press occurred and the // press event itself private int pressedRow; private int pressedCol; private MouseEvent pressedEvent; // Whether or not the mouse press (which is being considered as part // of a drag sequence) also caused the selection change to be fully // processed. private boolean dragPressDidSelection; // Set to true when a drag gesture has been fully recognized and DnD // begins. Use this to ignore further mouse events which could be // delivered if DnD is cancelled (via ESCAPE for example) private boolean dragStarted; // Whether or not we should start the editing timer on release private boolean shouldStartTimer; // To cache the return value of pointOutsidePrefSize since we use // it multiple times. private boolean outsidePrefSize; // Used to delay the start of editing. private Timer timer = null; private boolean canStartDrag() { if (pressedRow == -1 || pressedCol == -1) { return false; } if (isFileList) { return !outsidePrefSize; } // if this is a single selection table if ((table.getSelectionModel().getSelectionMode() == ListSelectionModel.SINGLE_SELECTION) && (table.getColumnModel().getSelectionModel().getSelectionMode() == ListSelectionModel.SINGLE_SELECTION)) { return true; } return table.isCellSelected(pressedRow, pressedCol); } public void mousePressed(MouseEvent e) { if (SwingUtilities2.shouldIgnore(e, table)) { return; } if (table.isEditing() && !table.getCellEditor().stopCellEditing()) { Component editorComponent = table.getEditorComponent(); if (editorComponent != null && !editorComponent.hasFocus()) { SwingUtilities2.compositeRequestFocus(editorComponent); } return; } Point p = e.getPoint(); pressedRow = table.rowAtPoint(p); pressedCol = table.columnAtPoint(p); outsidePrefSize = pointOutsidePrefSize(pressedRow, pressedCol, p); if (isFileList) { shouldStartTimer = table.isCellSelected(pressedRow, pressedCol) && !e.isShiftDown() && !e.isControlDown() && !outsidePrefSize; } if (table.getDragEnabled()) { mousePressedDND(e); } else { SwingUtilities2.adjustFocus(table); if (!isFileList) { setValueIsAdjusting(true); } adjustSelection(e); } } private void mousePressedDND(MouseEvent e) { pressedEvent = e; boolean grabFocus = true; dragStarted = false; if (canStartDrag() && DragRecognitionSupport.mousePressed(e)) { dragPressDidSelection = false; if (e.isControlDown() && isFileList) { // do nothing for control - will be handled on release // or when drag starts return; } else if (!e.isShiftDown() && table.isCellSelected(pressedRow, pressedCol)) { // clicking on something that's already selected // and need to make it the lead now table.getSelectionModel().addSelectionInterval(pressedRow, pressedRow); table.getColumnModel().getSelectionModel(). addSelectionInterval(pressedCol, pressedCol); return; } dragPressDidSelection = true; // could be a drag initiating event - don't grab focus grabFocus = false; } else if (!isFileList) { // When drag can't happen, mouse drags might change the selection in the table // so we want the isAdjusting flag to be set setValueIsAdjusting(true); } if (grabFocus) { SwingUtilities2.adjustFocus(table); } adjustSelection(e); } private void adjustSelection(MouseEvent e) { // Fix for 4835633 if (outsidePrefSize) { // If shift is down in multi-select, we should just return. // For single select or non-shift-click, clear the selection if (e.getID() == MouseEvent.MOUSE_PRESSED && (!e.isShiftDown() || table.getSelectionModel().getSelectionMode() == ListSelectionModel.SINGLE_SELECTION)) { table.clearSelection(); TableCellEditor tce = table.getCellEditor(); if (tce != null) { tce.stopCellEditing(); } } return; } // The autoscroller can generate drag events outside the // table's range. if ((pressedCol == -1) || (pressedRow == -1)) { return; } boolean dragEnabled = table.getDragEnabled(); if (!dragEnabled && !isFileList && table.editCellAt(pressedRow, pressedCol, e)) { setDispatchComponent(e); repostEvent(e); } CellEditor editor = table.getCellEditor(); if (dragEnabled || editor == null || editor.shouldSelectCell(e)) { table.changeSelection(pressedRow, pressedCol, e.isControlDown(), e.isShiftDown()); } } public void valueChanged(ListSelectionEvent e) { if (timer != null) { timer.stop(); timer = null; } } public void actionPerformed(ActionEvent ae) { table.editCellAt(pressedRow, pressedCol, null); Component editorComponent = table.getEditorComponent(); if (editorComponent != null && !editorComponent.hasFocus()) { SwingUtilities2.compositeRequestFocus(editorComponent); } return; } private void maybeStartTimer() { if (!shouldStartTimer) { return; } if (timer == null) { timer = new Timer(1200, this); timer.setRepeats(false); } timer.start(); } public void mouseReleased(MouseEvent e) { if (SwingUtilities2.shouldIgnore(e, table)) { return; } if (table.getDragEnabled()) { mouseReleasedDND(e); } else { if (isFileList) { maybeStartTimer(); } } pressedEvent = null; repostEvent(e); dispatchComponent = null; setValueIsAdjusting(false); } private void mouseReleasedDND(MouseEvent e) { MouseEvent me = DragRecognitionSupport.mouseReleased(e); if (me != null) { SwingUtilities2.adjustFocus(table); if (!dragPressDidSelection) { adjustSelection(me); } } if (!dragStarted) { if (isFileList) { maybeStartTimer(); return; } Point p = e.getPoint(); if (pressedEvent != null && table.rowAtPoint(p) == pressedRow && table.columnAtPoint(p) == pressedCol && table.editCellAt(pressedRow, pressedCol, pressedEvent)) { setDispatchComponent(pressedEvent); repostEvent(pressedEvent); // This may appear completely odd, but must be done for backward // compatibility reasons. Developers have been known to rely on // a call to shouldSelectCell after editing has begun. CellEditor ce = table.getCellEditor(); if (ce != null) { ce.shouldSelectCell(pressedEvent); } } } } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseMoved(MouseEvent e) {} public void dragStarting(MouseEvent me) { dragStarted = true; if (me.isControlDown() && isFileList) { table.getSelectionModel().addSelectionInterval(pressedRow, pressedRow); table.getColumnModel().getSelectionModel(). addSelectionInterval(pressedCol, pressedCol); } pressedEvent = null; } public void mouseDragged(MouseEvent e) { if (SwingUtilities2.shouldIgnore(e, table)) { return; } if (table.getDragEnabled() && (DragRecognitionSupport.mouseDragged(e, this) || dragStarted)) { return; } repostEvent(e); // Check isFileList: // Until we support drag-selection, dragging should not change // the selection (act like single-select). if (isFileList || table.isEditing()) { return; } Point p = e.getPoint(); int row = table.rowAtPoint(p); int column = table.columnAtPoint(p); // The autoscroller can generate drag events outside the // table's range. if ((column == -1) || (row == -1)) { return; } table.changeSelection(row, column, e.isControlDown(), true); } // PropertyChangeListener public void propertyChange(PropertyChangeEvent event) { String changeName = event.getPropertyName(); if ("componentOrientation" == changeName) { InputMap inputMap = getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); SwingUtilities.replaceUIInputMap(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, inputMap); JTableHeader header = table.getTableHeader(); if (header != null) { header.setComponentOrientation( (ComponentOrientation)event.getNewValue()); } } else if ("dropLocation" == changeName) { JTable.DropLocation oldValue = (JTable.DropLocation)event.getOldValue(); repaintDropLocation(oldValue); repaintDropLocation(table.getDropLocation()); } else if ("Table.isFileList" == changeName) { isFileList = Boolean.TRUE.equals(table.getClientProperty("Table.isFileList")); table.revalidate(); table.repaint(); if (isFileList) { table.getSelectionModel().addListSelectionListener(getHandler()); } else { table.getSelectionModel().removeListSelectionListener(getHandler()); timer = null; } } else if ("selectionModel" == changeName) { if (isFileList) { ListSelectionModel old = (ListSelectionModel)event.getOldValue(); old.removeListSelectionListener(getHandler()); table.getSelectionModel().addListSelectionListener(getHandler()); } } } private void repaintDropLocation(JTable.DropLocation loc) { if (loc == null) { return; } if (!loc.isInsertRow() && !loc.isInsertColumn()) { Rectangle rect = table.getCellRect(loc.getRow(), loc.getColumn(), false); if (rect != null) { table.repaint(rect); } return; } if (loc.isInsertRow()) { Rectangle rect = extendRect(getHDropLineRect(loc), true); if (rect != null) { table.repaint(rect); } } if (loc.isInsertColumn()) { Rectangle rect = extendRect(getVDropLineRect(loc), false); if (rect != null) { table.repaint(rect); } } } } /* * Returns true if the given point is outside the preferredSize of the * item at the given row of the table. (Column must be 0). * Returns false if the "Table.isFileList" client property is not set. */ private boolean pointOutsidePrefSize(int row, int column, Point p) { if (!isFileList) { return false; } return SwingUtilities2.pointOutsidePrefSize(table, row, column, p); } // // Factory methods for the Listeners // private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } /** {@collect.stats} * Creates the key listener for handling keyboard navigation in the JTable. */ protected KeyListener createKeyListener() { return null; } /** {@collect.stats} * Creates the focus listener for handling keyboard navigation in the JTable. */ protected FocusListener createFocusListener() { return getHandler(); } /** {@collect.stats} * Creates the mouse listener for the JTable. */ protected MouseInputListener createMouseInputListener() { return getHandler(); } // // The installation/uninstall procedures and support // public static ComponentUI createUI(JComponent c) { return new BasicTableUI(); } // Installation public void installUI(JComponent c) { table = (JTable)c; rendererPane = new CellRendererPane(); table.add(rendererPane); installDefaults(); installDefaults2(); installListeners(); installKeyboardActions(); } /** {@collect.stats} * Initialize JTable properties, e.g. font, foreground, and background. * The font, foreground, and background properties are only set if their * current value is either null or a UIResource, other properties are set * if the current value is null. * * @see #installUI */ protected void installDefaults() { LookAndFeel.installColorsAndFont(table, "Table.background", "Table.foreground", "Table.font"); // JTable's original row height is 16. To correctly display the // contents on Linux we should have set it to 18, Windows 19 and // Solaris 20. As these values vary so much it's too hard to // be backward compatable and try to update the row height, we're // therefor NOT going to adjust the row height based on font. If the // developer changes the font, it's there responsability to update // the row height. LookAndFeel.installProperty(table, "opaque", Boolean.TRUE); Color sbg = table.getSelectionBackground(); if (sbg == null || sbg instanceof UIResource) { sbg = UIManager.getColor("Table.selectionBackground"); table.setSelectionBackground(sbg != null ? sbg : UIManager.getColor("textHighlight")); } Color sfg = table.getSelectionForeground(); if (sfg == null || sfg instanceof UIResource) { sfg = UIManager.getColor("Table.selectionForeground"); table.setSelectionForeground(sfg != null ? sfg : UIManager.getColor("textHighlightText")); } Color gridColor = table.getGridColor(); if (gridColor == null || gridColor instanceof UIResource) { gridColor = UIManager.getColor("Table.gridColor"); table.setGridColor(gridColor != null ? gridColor : Color.GRAY); } // install the scrollpane border Container parent = table.getParent(); // should be viewport if (parent != null) { parent = parent.getParent(); // should be the scrollpane if (parent != null && parent instanceof JScrollPane) { LookAndFeel.installBorder((JScrollPane)parent, "Table.scrollPaneBorder"); } } isFileList = Boolean.TRUE.equals(table.getClientProperty("Table.isFileList")); } private void installDefaults2() { TransferHandler th = table.getTransferHandler(); if (th == null || th instanceof UIResource) { table.setTransferHandler(defaultTransferHandler); // default TransferHandler doesn't support drop // so we don't want drop handling if (table.getDropTarget() instanceof UIResource) { table.setDropTarget(null); } } } /** {@collect.stats} * Attaches listeners to the JTable. */ protected void installListeners() { focusListener = createFocusListener(); keyListener = createKeyListener(); mouseInputListener = createMouseInputListener(); table.addFocusListener(focusListener); table.addKeyListener(keyListener); table.addMouseListener(mouseInputListener); table.addMouseMotionListener(mouseInputListener); table.addPropertyChangeListener(getHandler()); if (isFileList) { table.getSelectionModel().addListSelectionListener(getHandler()); } } /** {@collect.stats} * Register all keyboard actions on the JTable. */ protected void installKeyboardActions() { LazyActionMap.installLazyActionMap(table, BasicTableUI.class, "Table.actionMap"); InputMap inputMap = getInputMap(JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); SwingUtilities.replaceUIInputMap(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, inputMap); } InputMap getInputMap(int condition) { if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) { InputMap keyMap = (InputMap)DefaultLookup.get(table, this, "Table.ancestorInputMap"); InputMap rtlKeyMap; if (table.getComponentOrientation().isLeftToRight() || ((rtlKeyMap = (InputMap)DefaultLookup.get(table, this, "Table.ancestorInputMap.RightToLeft")) == null)) { return keyMap; } else { rtlKeyMap.setParent(keyMap); return rtlKeyMap; } } return null; } static void loadActionMap(LazyActionMap map) { // IMPORTANT: There is a very close coupling between the parameters // passed to the Actions constructor. Only certain parameter // combinations are supported. For example, the following Action would // not work as expected: // new Actions(Actions.NEXT_ROW_CELL, 1, 4, false, true) // Actions which move within the selection only (having a true // inSelection parameter) require that one of dx or dy be // zero and the other be -1 or 1. The point of this warning is // that you should be very careful about making sure a particular // combination of parameters is supported before changing or // adding anything here. map.put(new Actions(Actions.NEXT_COLUMN, 1, 0, false, false)); map.put(new Actions(Actions.NEXT_COLUMN_CHANGE_LEAD, 1, 0, false, false)); map.put(new Actions(Actions.PREVIOUS_COLUMN, -1, 0, false, false)); map.put(new Actions(Actions.PREVIOUS_COLUMN_CHANGE_LEAD, -1, 0, false, false)); map.put(new Actions(Actions.NEXT_ROW, 0, 1, false, false)); map.put(new Actions(Actions.NEXT_ROW_CHANGE_LEAD, 0, 1, false, false)); map.put(new Actions(Actions.PREVIOUS_ROW, 0, -1, false, false)); map.put(new Actions(Actions.PREVIOUS_ROW_CHANGE_LEAD, 0, -1, false, false)); map.put(new Actions(Actions.NEXT_COLUMN_EXTEND_SELECTION, 1, 0, true, false)); map.put(new Actions(Actions.PREVIOUS_COLUMN_EXTEND_SELECTION, -1, 0, true, false)); map.put(new Actions(Actions.NEXT_ROW_EXTEND_SELECTION, 0, 1, true, false)); map.put(new Actions(Actions.PREVIOUS_ROW_EXTEND_SELECTION, 0, -1, true, false)); map.put(new Actions(Actions.SCROLL_UP_CHANGE_SELECTION, false, false, true, false)); map.put(new Actions(Actions.SCROLL_DOWN_CHANGE_SELECTION, false, true, true, false)); map.put(new Actions(Actions.FIRST_COLUMN, false, false, false, true)); map.put(new Actions(Actions.LAST_COLUMN, false, true, false, true)); map.put(new Actions(Actions.SCROLL_UP_EXTEND_SELECTION, true, false, true, false)); map.put(new Actions(Actions.SCROLL_DOWN_EXTEND_SELECTION, true, true, true, false)); map.put(new Actions(Actions.FIRST_COLUMN_EXTEND_SELECTION, true, false, false, true)); map.put(new Actions(Actions.LAST_COLUMN_EXTEND_SELECTION, true, true, false, true)); map.put(new Actions(Actions.FIRST_ROW, false, false, true, true)); map.put(new Actions(Actions.LAST_ROW, false, true, true, true)); map.put(new Actions(Actions.FIRST_ROW_EXTEND_SELECTION, true, false, true, true)); map.put(new Actions(Actions.LAST_ROW_EXTEND_SELECTION, true, true, true, true)); map.put(new Actions(Actions.NEXT_COLUMN_CELL, 1, 0, false, true)); map.put(new Actions(Actions.PREVIOUS_COLUMN_CELL, -1, 0, false, true)); map.put(new Actions(Actions.NEXT_ROW_CELL, 0, 1, false, true)); map.put(new Actions(Actions.PREVIOUS_ROW_CELL, 0, -1, false, true)); map.put(new Actions(Actions.SELECT_ALL)); map.put(new Actions(Actions.CLEAR_SELECTION)); map.put(new Actions(Actions.CANCEL_EDITING)); map.put(new Actions(Actions.START_EDITING)); map.put(TransferHandler.getCutAction().getValue(Action.NAME), TransferHandler.getCutAction()); map.put(TransferHandler.getCopyAction().getValue(Action.NAME), TransferHandler.getCopyAction()); map.put(TransferHandler.getPasteAction().getValue(Action.NAME), TransferHandler.getPasteAction()); map.put(new Actions(Actions.SCROLL_LEFT_CHANGE_SELECTION, false, false, false, false)); map.put(new Actions(Actions.SCROLL_RIGHT_CHANGE_SELECTION, false, true, false, false)); map.put(new Actions(Actions.SCROLL_LEFT_EXTEND_SELECTION, true, false, false, false)); map.put(new Actions(Actions.SCROLL_RIGHT_EXTEND_SELECTION, true, true, false, false)); map.put(new Actions(Actions.ADD_TO_SELECTION)); map.put(new Actions(Actions.TOGGLE_AND_ANCHOR)); map.put(new Actions(Actions.EXTEND_TO)); map.put(new Actions(Actions.MOVE_SELECTION_TO)); map.put(new Actions(Actions.FOCUS_HEADER)); } // Uninstallation public void uninstallUI(JComponent c) { uninstallDefaults(); uninstallListeners(); uninstallKeyboardActions(); table.remove(rendererPane); rendererPane = null; table = null; } protected void uninstallDefaults() { if (table.getTransferHandler() instanceof UIResource) { table.setTransferHandler(null); } } protected void uninstallListeners() { table.removeFocusListener(focusListener); table.removeKeyListener(keyListener); table.removeMouseListener(mouseInputListener); table.removeMouseMotionListener(mouseInputListener); table.removePropertyChangeListener(getHandler()); if (isFileList) { table.getSelectionModel().removeListSelectionListener(getHandler()); } focusListener = null; keyListener = null; mouseInputListener = null; handler = null; } protected void uninstallKeyboardActions() { SwingUtilities.replaceUIInputMap(table, JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null); SwingUtilities.replaceUIActionMap(table, null); } /** {@collect.stats} * Returns the baseline. * * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public int getBaseline(JComponent c, int width, int height) { super.getBaseline(c, width, height); UIDefaults lafDefaults = UIManager.getLookAndFeelDefaults(); Component renderer = (Component)lafDefaults.get( BASELINE_COMPONENT_KEY); if (renderer == null) { DefaultTableCellRenderer tcr = new DefaultTableCellRenderer(); renderer = tcr.getTableCellRendererComponent( table, "a", false, false, -1, -1); lafDefaults.put(BASELINE_COMPONENT_KEY, renderer); } renderer.setFont(table.getFont()); int rowMargin = table.getRowMargin(); return renderer.getBaseline(Integer.MAX_VALUE, table.getRowHeight() - rowMargin) + rowMargin / 2; } /** {@collect.stats} * Returns an enum indicating how the baseline of the component * changes as the size changes. * * @throws NullPointerException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public Component.BaselineResizeBehavior getBaselineResizeBehavior( JComponent c) { super.getBaselineResizeBehavior(c); return Component.BaselineResizeBehavior.CONSTANT_ASCENT; } // // Size Methods // private Dimension createTableSize(long width) { int height = 0; int rowCount = table.getRowCount(); if (rowCount > 0 && table.getColumnCount() > 0) { Rectangle r = table.getCellRect(rowCount-1, 0, true); height = r.y + r.height; } // Width is always positive. The call to abs() is a workaround for // a bug in the 1.1.6 JIT on Windows. long tmp = Math.abs(width); if (tmp > Integer.MAX_VALUE) { tmp = Integer.MAX_VALUE; } return new Dimension((int)tmp, height); } /** {@collect.stats} * Return the minimum size of the table. The minimum height is the * row height times the number of rows. * The minimum width is the sum of the minimum widths of each column. */ public Dimension getMinimumSize(JComponent c) { long width = 0; Enumeration enumeration = table.getColumnModel().getColumns(); while (enumeration.hasMoreElements()) { TableColumn aColumn = (TableColumn)enumeration.nextElement(); width = width + aColumn.getMinWidth(); } return createTableSize(width); } /** {@collect.stats} * Return the preferred size of the table. The preferred height is the * row height times the number of rows. * The preferred width is the sum of the preferred widths of each column. */ public Dimension getPreferredSize(JComponent c) { long width = 0; Enumeration enumeration = table.getColumnModel().getColumns(); while (enumeration.hasMoreElements()) { TableColumn aColumn = (TableColumn)enumeration.nextElement(); width = width + aColumn.getPreferredWidth(); } return createTableSize(width); } /** {@collect.stats} * Return the maximum size of the table. The maximum height is the * row heighttimes the number of rows. * The maximum width is the sum of the maximum widths of each column. */ public Dimension getMaximumSize(JComponent c) { long width = 0; Enumeration enumeration = table.getColumnModel().getColumns(); while (enumeration.hasMoreElements()) { TableColumn aColumn = (TableColumn)enumeration.nextElement(); width = width + aColumn.getMaxWidth(); } return createTableSize(width); } // // Paint methods and support // /** {@collect.stats} Paint a representation of the <code>table</code> instance * that was set in installUI(). */ public void paint(Graphics g, JComponent c) { Rectangle clip = g.getClipBounds(); Rectangle bounds = table.getBounds(); // account for the fact that the graphics has already been translated // into the table's bounds bounds.x = bounds.y = 0; if (table.getRowCount() <= 0 || table.getColumnCount() <= 0 || // this check prevents us from painting the entire table // when the clip doesn't intersect our bounds at all !bounds.intersects(clip)) { paintDropLines(g); return; } boolean ltr = table.getComponentOrientation().isLeftToRight(); Point upperLeft = clip.getLocation(); Point lowerRight = new Point(clip.x + clip.width - 1, clip.y + clip.height - 1); int rMin = table.rowAtPoint(upperLeft); int rMax = table.rowAtPoint(lowerRight); // This should never happen (as long as our bounds intersect the clip, // which is why we bail above if that is the case). if (rMin == -1) { rMin = 0; } // If the table does not have enough rows to fill the view we'll get -1. // (We could also get -1 if our bounds don't intersect the clip, // which is why we bail above if that is the case). // Replace this with the index of the last row. if (rMax == -1) { rMax = table.getRowCount()-1; } int cMin = table.columnAtPoint(ltr ? upperLeft : lowerRight); int cMax = table.columnAtPoint(ltr ? lowerRight : upperLeft); // This should never happen. if (cMin == -1) { cMin = 0; } // If the table does not have enough columns to fill the view we'll get -1. // Replace this with the index of the last column. if (cMax == -1) { cMax = table.getColumnCount()-1; } // Paint the grid. paintGrid(g, rMin, rMax, cMin, cMax); // Paint the cells. paintCells(g, rMin, rMax, cMin, cMax); paintDropLines(g); } private void paintDropLines(Graphics g) { JTable.DropLocation loc = table.getDropLocation(); if (loc == null) { return; } Color color = UIManager.getColor("Table.dropLineColor"); Color shortColor = UIManager.getColor("Table.dropLineShortColor"); if (color == null && shortColor == null) { return; } Rectangle rect; rect = getHDropLineRect(loc); if (rect != null) { int x = rect.x; int w = rect.width; if (color != null) { extendRect(rect, true); g.setColor(color); g.fillRect(rect.x, rect.y, rect.width, rect.height); } if (!loc.isInsertColumn() && shortColor != null) { g.setColor(shortColor); g.fillRect(x, rect.y, w, rect.height); } } rect = getVDropLineRect(loc); if (rect != null) { int y = rect.y; int h = rect.height; if (color != null) { extendRect(rect, false); g.setColor(color); g.fillRect(rect.x, rect.y, rect.width, rect.height); } if (!loc.isInsertRow() && shortColor != null) { g.setColor(shortColor); g.fillRect(rect.x, y, rect.width, h); } } } private Rectangle getHDropLineRect(JTable.DropLocation loc) { if (!loc.isInsertRow()) { return null; } int row = loc.getRow(); int col = loc.getColumn(); if (col >= table.getColumnCount()) { col--; } Rectangle rect = table.getCellRect(row, col, true); if (row >= table.getRowCount()) { row--; Rectangle prevRect = table.getCellRect(row, col, true); rect.y = prevRect.y + prevRect.height; } if (rect.y == 0) { rect.y = -1; } else { rect.y -= 2; } rect.height = 3; return rect; } private Rectangle getVDropLineRect(JTable.DropLocation loc) { if (!loc.isInsertColumn()) { return null; } boolean ltr = table.getComponentOrientation().isLeftToRight(); int col = loc.getColumn(); Rectangle rect = table.getCellRect(loc.getRow(), col, true); if (col >= table.getColumnCount()) { col--; rect = table.getCellRect(loc.getRow(), col, true); if (ltr) { rect.x = rect.x + rect.width; } } else if (!ltr) { rect.x = rect.x + rect.width; } if (rect.x == 0) { rect.x = -1; } else { rect.x -= 2; } rect.width = 3; return rect; } private Rectangle extendRect(Rectangle rect, boolean horizontal) { if (rect == null) { return rect; } if (horizontal) { rect.x = 0; rect.width = table.getWidth(); } else { rect.y = 0; if (table.getRowCount() != 0) { Rectangle lastRect = table.getCellRect(table.getRowCount() - 1, 0, true); rect.height = lastRect.y + lastRect.height; } else { rect.height = table.getHeight(); } } return rect; } /* * Paints the grid lines within <I>aRect</I>, using the grid * color set with <I>setGridColor</I>. Paints vertical lines * if <code>getShowVerticalLines()</code> returns true and paints * horizontal lines if <code>getShowHorizontalLines()</code> * returns true. */ private void paintGrid(Graphics g, int rMin, int rMax, int cMin, int cMax) { g.setColor(table.getGridColor()); Rectangle minCell = table.getCellRect(rMin, cMin, true); Rectangle maxCell = table.getCellRect(rMax, cMax, true); Rectangle damagedArea = minCell.union( maxCell ); if (table.getShowHorizontalLines()) { int tableWidth = damagedArea.x + damagedArea.width; int y = damagedArea.y; for (int row = rMin; row <= rMax; row++) { y += table.getRowHeight(row); g.drawLine(damagedArea.x, y - 1, tableWidth - 1, y - 1); } } if (table.getShowVerticalLines()) { TableColumnModel cm = table.getColumnModel(); int tableHeight = damagedArea.y + damagedArea.height; int x; if (table.getComponentOrientation().isLeftToRight()) { x = damagedArea.x; for (int column = cMin; column <= cMax; column++) { int w = cm.getColumn(column).getWidth(); x += w; g.drawLine(x - 1, 0, x - 1, tableHeight - 1); } } else { x = damagedArea.x; for (int column = cMax; column >= cMin; column--) { int w = cm.getColumn(column).getWidth(); x += w; g.drawLine(x - 1, 0, x - 1, tableHeight - 1); } } } } private int viewIndexForColumn(TableColumn aColumn) { TableColumnModel cm = table.getColumnModel(); for (int column = 0; column < cm.getColumnCount(); column++) { if (cm.getColumn(column) == aColumn) { return column; } } return -1; } private void paintCells(Graphics g, int rMin, int rMax, int cMin, int cMax) { JTableHeader header = table.getTableHeader(); TableColumn draggedColumn = (header == null) ? null : header.getDraggedColumn(); TableColumnModel cm = table.getColumnModel(); int columnMargin = cm.getColumnMargin(); Rectangle cellRect; TableColumn aColumn; int columnWidth; if (table.getComponentOrientation().isLeftToRight()) { for(int row = rMin; row <= rMax; row++) { cellRect = table.getCellRect(row, cMin, false); for(int column = cMin; column <= cMax; column++) { aColumn = cm.getColumn(column); columnWidth = aColumn.getWidth(); cellRect.width = columnWidth - columnMargin; if (aColumn != draggedColumn) { paintCell(g, cellRect, row, column); } cellRect.x += columnWidth; } } } else { for(int row = rMin; row <= rMax; row++) { cellRect = table.getCellRect(row, cMin, false); aColumn = cm.getColumn(cMin); if (aColumn != draggedColumn) { columnWidth = aColumn.getWidth(); cellRect.width = columnWidth - columnMargin; paintCell(g, cellRect, row, cMin); } for(int column = cMin+1; column <= cMax; column++) { aColumn = cm.getColumn(column); columnWidth = aColumn.getWidth(); cellRect.width = columnWidth - columnMargin; cellRect.x -= columnWidth; if (aColumn != draggedColumn) { paintCell(g, cellRect, row, column); } } } } // Paint the dragged column if we are dragging. if (draggedColumn != null) { paintDraggedArea(g, rMin, rMax, draggedColumn, header.getDraggedDistance()); } // Remove any renderers that may be left in the rendererPane. rendererPane.removeAll(); } private void paintDraggedArea(Graphics g, int rMin, int rMax, TableColumn draggedColumn, int distance) { int draggedColumnIndex = viewIndexForColumn(draggedColumn); Rectangle minCell = table.getCellRect(rMin, draggedColumnIndex, true); Rectangle maxCell = table.getCellRect(rMax, draggedColumnIndex, true); Rectangle vacatedColumnRect = minCell.union(maxCell); // Paint a gray well in place of the moving column. g.setColor(table.getParent().getBackground()); g.fillRect(vacatedColumnRect.x, vacatedColumnRect.y, vacatedColumnRect.width, vacatedColumnRect.height); // Move to the where the cell has been dragged. vacatedColumnRect.x += distance; // Fill the background. g.setColor(table.getBackground()); g.fillRect(vacatedColumnRect.x, vacatedColumnRect.y, vacatedColumnRect.width, vacatedColumnRect.height); // Paint the vertical grid lines if necessary. if (table.getShowVerticalLines()) { g.setColor(table.getGridColor()); int x1 = vacatedColumnRect.x; int y1 = vacatedColumnRect.y; int x2 = x1 + vacatedColumnRect.width - 1; int y2 = y1 + vacatedColumnRect.height - 1; // Left g.drawLine(x1-1, y1, x1-1, y2); // Right g.drawLine(x2, y1, x2, y2); } for(int row = rMin; row <= rMax; row++) { // Render the cell value Rectangle r = table.getCellRect(row, draggedColumnIndex, false); r.x += distance; paintCell(g, r, row, draggedColumnIndex); // Paint the (lower) horizontal grid line if necessary. if (table.getShowHorizontalLines()) { g.setColor(table.getGridColor()); Rectangle rcr = table.getCellRect(row, draggedColumnIndex, true); rcr.x += distance; int x1 = rcr.x; int y1 = rcr.y; int x2 = x1 + rcr.width - 1; int y2 = y1 + rcr.height - 1; g.drawLine(x1, y2, x2, y2); } } } private void paintCell(Graphics g, Rectangle cellRect, int row, int column) { if (table.isEditing() && table.getEditingRow()==row && table.getEditingColumn()==column) { Component component = table.getEditorComponent(); component.setBounds(cellRect); component.validate(); } else { TableCellRenderer renderer = table.getCellRenderer(row, column); Component component = table.prepareRenderer(renderer, row, column); rendererPane.paintComponent(g, component, table, cellRect.x, cellRect.y, cellRect.width, cellRect.height, true); } } private static int getAdjustedLead(JTable table, boolean row, ListSelectionModel model) { int index = model.getLeadSelectionIndex(); int compare = row ? table.getRowCount() : table.getColumnCount(); return index < compare ? index : -1; } private static int getAdjustedLead(JTable table, boolean row) { return row ? getAdjustedLead(table, row, table.getSelectionModel()) : getAdjustedLead(table, row, table.getColumnModel().getSelectionModel()); } private static final TransferHandler defaultTransferHandler = new TableTransferHandler(); static class TableTransferHandler extends TransferHandler implements UIResource { /** {@collect.stats} * Create a Transferable to use as the source for a data transfer. * * @param c The component holding the data to be transfered. This * argument is provided to enable sharing of TransferHandlers by * multiple components. * @return The representation of the data to be transfered. * */ protected Transferable createTransferable(JComponent c) { if (c instanceof JTable) { JTable table = (JTable) c; int[] rows; int[] cols; if (!table.getRowSelectionAllowed() && !table.getColumnSelectionAllowed()) { return null; } if (!table.getRowSelectionAllowed()) { int rowCount = table.getRowCount(); rows = new int[rowCount]; for (int counter = 0; counter < rowCount; counter++) { rows[counter] = counter; } } else { rows = table.getSelectedRows(); } if (!table.getColumnSelectionAllowed()) { int colCount = table.getColumnCount(); cols = new int[colCount]; for (int counter = 0; counter < colCount; counter++) { cols[counter] = counter; } } else { cols = table.getSelectedColumns(); } if (rows == null || cols == null || rows.length == 0 || cols.length == 0) { return null; } StringBuffer plainBuf = new StringBuffer(); StringBuffer htmlBuf = new StringBuffer(); htmlBuf.append("<html>\n<body>\n<table>\n"); for (int row = 0; row < rows.length; row++) { htmlBuf.append("<tr>\n"); for (int col = 0; col < cols.length; col++) { Object obj = table.getValueAt(rows[row], cols[col]); String val = ((obj == null) ? "" : obj.toString()); plainBuf.append(val + "\t"); htmlBuf.append(" <td>" + val + "</td>\n"); } // we want a newline at the end of each line and not a tab plainBuf.deleteCharAt(plainBuf.length() - 1).append("\n"); htmlBuf.append("</tr>\n"); } // remove the last newline plainBuf.deleteCharAt(plainBuf.length() - 1); htmlBuf.append("</table>\n</body>\n</html>"); return new BasicTransferable(plainBuf.toString(), htmlBuf.toString()); } return null; } public int getSourceActions(JComponent c) { return COPY; } } } // End of Class BasicTableUI
Java
/* * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.swing.*; import javax.swing.filechooser.*; import javax.swing.filechooser.FileFilter; import javax.swing.event.*; import javax.swing.plaf.*; import java.awt.*; import java.awt.event.*; import java.awt.datatransfer.*; import java.beans.*; import java.io.*; import java.util.*; import java.util.regex.*; import sun.awt.shell.ShellFolder; import sun.swing.*; import sun.swing.SwingUtilities2; /** {@collect.stats} * Basic L&F implementation of a FileChooser. * * @author Jeff Dinkins */ public class BasicFileChooserUI extends FileChooserUI { /* FileView icons */ protected Icon directoryIcon = null; protected Icon fileIcon = null; protected Icon computerIcon = null; protected Icon hardDriveIcon = null; protected Icon floppyDriveIcon = null; protected Icon newFolderIcon = null; protected Icon upFolderIcon = null; protected Icon homeFolderIcon = null; protected Icon listViewIcon = null; protected Icon detailsViewIcon = null; protected int saveButtonMnemonic = 0; protected int openButtonMnemonic = 0; protected int cancelButtonMnemonic = 0; protected int updateButtonMnemonic = 0; protected int helpButtonMnemonic = 0; /** {@collect.stats} * The mnemonic keycode used for the approve button when a directory * is selected and the current selection mode is FILES_ONLY. * * @since 1.4 */ protected int directoryOpenButtonMnemonic = 0; protected String saveButtonText = null; protected String openButtonText = null; protected String cancelButtonText = null; protected String updateButtonText = null; protected String helpButtonText = null; /** {@collect.stats} * The label text displayed on the approve button when a directory * is selected and the current selection mode is FILES_ONLY. * * @since 1.4 */ protected String directoryOpenButtonText = null; private String openDialogTitleText = null; private String saveDialogTitleText = null; protected String saveButtonToolTipText = null; protected String openButtonToolTipText = null; protected String cancelButtonToolTipText = null; protected String updateButtonToolTipText = null; protected String helpButtonToolTipText = null; /** {@collect.stats} * The tooltip text displayed on the approve button when a directory * is selected and the current selection mode is FILES_ONLY. * * @since 1.4 */ protected String directoryOpenButtonToolTipText = null; // Some generic FileChooser functions private Action approveSelectionAction = new ApproveSelectionAction(); private Action cancelSelectionAction = new CancelSelectionAction(); private Action updateAction = new UpdateAction(); private Action newFolderAction; private Action goHomeAction = new GoHomeAction(); private Action changeToParentDirectoryAction = new ChangeToParentDirectoryAction(); private String newFolderErrorSeparator = null; private String newFolderErrorText = null; private String fileDescriptionText = null; private String directoryDescriptionText = null; private JFileChooser filechooser = null; private boolean directorySelected = false; private File directory = null; private PropertyChangeListener propertyChangeListener = null; private AcceptAllFileFilter acceptAllFileFilter = new AcceptAllFileFilter(); private FileFilter actualFileFilter = null; private GlobFilter globFilter = null; private BasicDirectoryModel model = null; private BasicFileView fileView = new BasicFileView(); private boolean usesSingleFilePane; private boolean readOnly; // The accessoryPanel is a container to place the JFileChooser accessory component private JPanel accessoryPanel = null; private Handler handler; public BasicFileChooserUI(JFileChooser b) { } public void installUI(JComponent c) { accessoryPanel = new JPanel(new BorderLayout()); filechooser = (JFileChooser) c; createModel(); clearIconCache(); installDefaults(filechooser); installComponents(filechooser); installListeners(filechooser); filechooser.applyComponentOrientation(filechooser.getComponentOrientation()); } public void uninstallUI(JComponent c) { uninstallListeners((JFileChooser) filechooser); uninstallComponents((JFileChooser) filechooser); uninstallDefaults((JFileChooser) filechooser); if(accessoryPanel != null) { accessoryPanel.removeAll(); } accessoryPanel = null; getFileChooser().removeAll(); handler = null; } public void installComponents(JFileChooser fc) { } public void uninstallComponents(JFileChooser fc) { } protected void installListeners(JFileChooser fc) { propertyChangeListener = createPropertyChangeListener(fc); if(propertyChangeListener != null) { fc.addPropertyChangeListener(propertyChangeListener); } fc.addPropertyChangeListener(getModel()); InputMap inputMap = getInputMap(JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); SwingUtilities.replaceUIInputMap(fc, JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, inputMap); ActionMap actionMap = getActionMap(); SwingUtilities.replaceUIActionMap(fc, actionMap); } InputMap getInputMap(int condition) { if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) { return (InputMap)DefaultLookup.get(getFileChooser(), this, "FileChooser.ancestorInputMap"); } return null; } ActionMap getActionMap() { return createActionMap(); } ActionMap createActionMap() { ActionMap map = new ActionMapUIResource(); Action refreshAction = new UIAction(FilePane.ACTION_REFRESH) { public void actionPerformed(ActionEvent evt) { getFileChooser().rescanCurrentDirectory(); } }; map.put(FilePane.ACTION_APPROVE_SELECTION, getApproveSelectionAction()); map.put(FilePane.ACTION_CANCEL, getCancelSelectionAction()); map.put(FilePane.ACTION_REFRESH, refreshAction); map.put(FilePane.ACTION_CHANGE_TO_PARENT_DIRECTORY, getChangeToParentDirectoryAction()); return map; } protected void uninstallListeners(JFileChooser fc) { if(propertyChangeListener != null) { fc.removePropertyChangeListener(propertyChangeListener); } fc.removePropertyChangeListener(getModel()); SwingUtilities.replaceUIInputMap(fc, JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null); SwingUtilities.replaceUIActionMap(fc, null); } protected void installDefaults(JFileChooser fc) { installIcons(fc); installStrings(fc); usesSingleFilePane = UIManager.getBoolean("FileChooser.usesSingleFilePane"); readOnly = UIManager.getBoolean("FileChooser.readOnly"); TransferHandler th = fc.getTransferHandler(); if (th == null || th instanceof UIResource) { fc.setTransferHandler(defaultTransferHandler); } LookAndFeel.installProperty(fc, "opaque", Boolean.FALSE); } protected void installIcons(JFileChooser fc) { directoryIcon = UIManager.getIcon("FileView.directoryIcon"); fileIcon = UIManager.getIcon("FileView.fileIcon"); computerIcon = UIManager.getIcon("FileView.computerIcon"); hardDriveIcon = UIManager.getIcon("FileView.hardDriveIcon"); floppyDriveIcon = UIManager.getIcon("FileView.floppyDriveIcon"); newFolderIcon = UIManager.getIcon("FileChooser.newFolderIcon"); upFolderIcon = UIManager.getIcon("FileChooser.upFolderIcon"); homeFolderIcon = UIManager.getIcon("FileChooser.homeFolderIcon"); detailsViewIcon = UIManager.getIcon("FileChooser.detailsViewIcon"); listViewIcon = UIManager.getIcon("FileChooser.listViewIcon"); } protected void installStrings(JFileChooser fc) { Locale l = fc.getLocale(); newFolderErrorText = UIManager.getString("FileChooser.newFolderErrorText",l); newFolderErrorSeparator = UIManager.getString("FileChooser.newFolderErrorSeparator",l); fileDescriptionText = UIManager.getString("FileChooser.fileDescriptionText",l); directoryDescriptionText = UIManager.getString("FileChooser.directoryDescriptionText",l); saveButtonText = UIManager.getString("FileChooser.saveButtonText",l); openButtonText = UIManager.getString("FileChooser.openButtonText",l); saveDialogTitleText = UIManager.getString("FileChooser.saveDialogTitleText",l); openDialogTitleText = UIManager.getString("FileChooser.openDialogTitleText",l); cancelButtonText = UIManager.getString("FileChooser.cancelButtonText",l); updateButtonText = UIManager.getString("FileChooser.updateButtonText",l); helpButtonText = UIManager.getString("FileChooser.helpButtonText",l); directoryOpenButtonText = UIManager.getString("FileChooser.directoryOpenButtonText",l); saveButtonMnemonic = getMnemonic("FileChooser.saveButtonMnemonic", l); openButtonMnemonic = getMnemonic("FileChooser.openButtonMnemonic", l); cancelButtonMnemonic = getMnemonic("FileChooser.cancelButtonMnemonic", l); updateButtonMnemonic = getMnemonic("FileChooser.updateButtonMnemonic", l); helpButtonMnemonic = getMnemonic("FileChooser.helpButtonMnemonic", l); directoryOpenButtonMnemonic = getMnemonic("FileChooser.directoryOpenButtonMnemonic", l); saveButtonToolTipText = UIManager.getString("FileChooser.saveButtonToolTipText",l); openButtonToolTipText = UIManager.getString("FileChooser.openButtonToolTipText",l); cancelButtonToolTipText = UIManager.getString("FileChooser.cancelButtonToolTipText",l); updateButtonToolTipText = UIManager.getString("FileChooser.updateButtonToolTipText",l); helpButtonToolTipText = UIManager.getString("FileChooser.helpButtonToolTipText",l); directoryOpenButtonToolTipText = UIManager.getString("FileChooser.directoryOpenButtonToolTipText",l); } protected void uninstallDefaults(JFileChooser fc) { uninstallIcons(fc); uninstallStrings(fc); if (fc.getTransferHandler() instanceof UIResource) { fc.setTransferHandler(null); } } protected void uninstallIcons(JFileChooser fc) { directoryIcon = null; fileIcon = null; computerIcon = null; hardDriveIcon = null; floppyDriveIcon = null; newFolderIcon = null; upFolderIcon = null; homeFolderIcon = null; detailsViewIcon = null; listViewIcon = null; } protected void uninstallStrings(JFileChooser fc) { saveButtonText = null; openButtonText = null; cancelButtonText = null; updateButtonText = null; helpButtonText = null; directoryOpenButtonText = null; saveButtonToolTipText = null; openButtonToolTipText = null; cancelButtonToolTipText = null; updateButtonToolTipText = null; helpButtonToolTipText = null; directoryOpenButtonToolTipText = null; } protected void createModel() { if (model != null) { model.invalidateFileCache(); } model = new BasicDirectoryModel(getFileChooser()); } public BasicDirectoryModel getModel() { return model; } public PropertyChangeListener createPropertyChangeListener(JFileChooser fc) { return null; } public String getFileName() { return null; } public String getDirectoryName() { return null; } public void setFileName(String filename) { } public void setDirectoryName(String dirname) { } public void rescanCurrentDirectory(JFileChooser fc) { } public void ensureFileIsVisible(JFileChooser fc, File f) { } public JFileChooser getFileChooser() { return filechooser; } public JPanel getAccessoryPanel() { return accessoryPanel; } protected JButton getApproveButton(JFileChooser fc) { return null; } public String getApproveButtonToolTipText(JFileChooser fc) { String tooltipText = fc.getApproveButtonToolTipText(); if(tooltipText != null) { return tooltipText; } if(fc.getDialogType() == JFileChooser.OPEN_DIALOG) { return openButtonToolTipText; } else if(fc.getDialogType() == JFileChooser.SAVE_DIALOG) { return saveButtonToolTipText; } return null; } public void clearIconCache() { fileView.clearIconCache(); } // ******************************************** // ************ Create Listeners ************** // ******************************************** private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } protected MouseListener createDoubleClickListener(JFileChooser fc, JList list) { return new Handler(list); } public ListSelectionListener createListSelectionListener(JFileChooser fc) { return getHandler(); } private class Handler implements MouseListener, ListSelectionListener { JList list; Handler() { } Handler(JList list) { this.list = list; } public void mouseClicked(MouseEvent evt) { // Note: we can't depend on evt.getSource() because of backward // compatability if (list != null && SwingUtilities.isLeftMouseButton(evt) && (evt.getClickCount()%2 == 0)) { int index = SwingUtilities2.loc2IndexFileList(list, evt.getPoint()); if (index >= 0) { File f = (File)list.getModel().getElementAt(index); try { // Strip trailing ".." f = ShellFolder.getNormalizedFile(f); } catch (IOException ex) { // That's ok, we'll use f as is } if(getFileChooser().isTraversable(f)) { list.clearSelection(); changeDirectory(f); } else { getFileChooser().approveSelection(); } } } } public void mouseEntered(MouseEvent evt) { if (list != null) { TransferHandler th1 = getFileChooser().getTransferHandler(); TransferHandler th2 = list.getTransferHandler(); if (th1 != th2) { list.setTransferHandler(th1); } if (getFileChooser().getDragEnabled() != list.getDragEnabled()) { list.setDragEnabled(getFileChooser().getDragEnabled()); } } } public void mouseExited(MouseEvent evt) { } public void mousePressed(MouseEvent evt) { } public void mouseReleased(MouseEvent evt) { } public void valueChanged(ListSelectionEvent evt) { if(!evt.getValueIsAdjusting()) { JFileChooser chooser = getFileChooser(); FileSystemView fsv = chooser.getFileSystemView(); JList list = (JList)evt.getSource(); int fsm = chooser.getFileSelectionMode(); boolean useSetDirectory = usesSingleFilePane && (fsm == JFileChooser.FILES_ONLY); if (chooser.isMultiSelectionEnabled()) { File[] files = null; Object[] objects = list.getSelectedValues(); if (objects != null) { if (objects.length == 1 && ((File)objects[0]).isDirectory() && chooser.isTraversable(((File)objects[0])) && (useSetDirectory || !fsv.isFileSystem(((File)objects[0])))) { setDirectorySelected(true); setDirectory(((File)objects[0])); } else { ArrayList fList = new ArrayList(objects.length); for (int i = 0; i < objects.length; i++) { File f = (File)objects[i]; boolean isDir = f.isDirectory(); if ((chooser.isFileSelectionEnabled() && !isDir) || (chooser.isDirectorySelectionEnabled() && fsv.isFileSystem(f) && isDir)) { fList.add(f); } } if (fList.size() > 0) { files = (File[])fList.toArray(new File[fList.size()]); } setDirectorySelected(false); } } chooser.setSelectedFiles(files); } else { File file = (File)list.getSelectedValue(); if (file != null && file.isDirectory() && chooser.isTraversable(file) && (useSetDirectory || !fsv.isFileSystem(file))) { setDirectorySelected(true); setDirectory(file); if (usesSingleFilePane) { chooser.setSelectedFile(null); } } else { setDirectorySelected(false); if (file != null) { chooser.setSelectedFile(file); } } } } } } protected class DoubleClickListener extends MouseAdapter { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. Handler handler; public DoubleClickListener(JList list) { handler = new Handler(list); } /** {@collect.stats} * The JList used for representing the files is created by subclasses, but the * selection is monitored in this class. The TransferHandler installed in the * JFileChooser is also installed in the file list as it is used as the actual * transfer source. The list is updated on a mouse enter to reflect the current * data transfer state of the file chooser. */ public void mouseEntered(MouseEvent e) { handler.mouseEntered(e); } public void mouseClicked(MouseEvent e) { handler.mouseClicked(e); } } protected class SelectionListener implements ListSelectionListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void valueChanged(ListSelectionEvent e) { getHandler().valueChanged(e); } } /** {@collect.stats} * Property to remember whether a directory is currently selected in the UI. * * @return <code>true</code> iff a directory is currently selected. * @since 1.4 */ protected boolean isDirectorySelected() { return directorySelected; } /** {@collect.stats} * Property to remember whether a directory is currently selected in the UI. * This is normally called by the UI on a selection event. * * @param b iff a directory is currently selected. * @since 1.4 */ protected void setDirectorySelected(boolean b) { directorySelected = b; } /** {@collect.stats} * Property to remember the directory that is currently selected in the UI. * * @return the value of the <code>directory</code> property * @see #setDirectory * @since 1.4 */ protected File getDirectory() { return directory; } /** {@collect.stats} * Property to remember the directory that is currently selected in the UI. * This is normally called by the UI on a selection event. * * @param f the <code>File</code> object representing the directory that is * currently selected * @since 1.4 */ protected void setDirectory(File f) { directory = f; } /** {@collect.stats} * Returns the mnemonic for the given key. */ private int getMnemonic(String key, Locale l) { return SwingUtilities2.getUIDefaultsInt(key, l); } // ******************************************************* // ************ FileChooser UI PLAF methods ************** // ******************************************************* /** {@collect.stats} * Returns the default accept all file filter */ public FileFilter getAcceptAllFileFilter(JFileChooser fc) { return acceptAllFileFilter; } public FileView getFileView(JFileChooser fc) { return fileView; } /** {@collect.stats} * Returns the title of this dialog */ public String getDialogTitle(JFileChooser fc) { String dialogTitle = fc.getDialogTitle(); if (dialogTitle != null) { return dialogTitle; } else if (fc.getDialogType() == JFileChooser.OPEN_DIALOG) { return openDialogTitleText; } else if (fc.getDialogType() == JFileChooser.SAVE_DIALOG) { return saveDialogTitleText; } else { return getApproveButtonText(fc); } } public int getApproveButtonMnemonic(JFileChooser fc) { int mnemonic = fc.getApproveButtonMnemonic(); if (mnemonic > 0) { return mnemonic; } else if (fc.getDialogType() == JFileChooser.OPEN_DIALOG) { return openButtonMnemonic; } else if (fc.getDialogType() == JFileChooser.SAVE_DIALOG) { return saveButtonMnemonic; } else { return mnemonic; } } public String getApproveButtonText(JFileChooser fc) { String buttonText = fc.getApproveButtonText(); if (buttonText != null) { return buttonText; } else if (fc.getDialogType() == JFileChooser.OPEN_DIALOG) { return openButtonText; } else if (fc.getDialogType() == JFileChooser.SAVE_DIALOG) { return saveButtonText; } else { return null; } } // ***************************** // ***** Directory Actions ***** // ***************************** public Action getNewFolderAction() { if (newFolderAction == null) { newFolderAction = new NewFolderAction(); // Note: Don't return null for readOnly, it might // break older apps. if (readOnly) { newFolderAction.setEnabled(false); } } return newFolderAction; } public Action getGoHomeAction() { return goHomeAction; } public Action getChangeToParentDirectoryAction() { return changeToParentDirectoryAction; } public Action getApproveSelectionAction() { return approveSelectionAction; } public Action getCancelSelectionAction() { return cancelSelectionAction; } public Action getUpdateAction() { return updateAction; } /** {@collect.stats} * Creates a new folder. */ protected class NewFolderAction extends AbstractAction { protected NewFolderAction() { super(FilePane.ACTION_NEW_FOLDER); } public void actionPerformed(ActionEvent e) { if (readOnly) { return; } JFileChooser fc = getFileChooser(); File currentDirectory = fc.getCurrentDirectory(); File newFolder = null; try { newFolder = fc.getFileSystemView().createNewFolder(currentDirectory); if (fc.isMultiSelectionEnabled()) { fc.setSelectedFiles(new File[] { newFolder }); } else { fc.setSelectedFile(newFolder); } } catch (IOException exc) { JOptionPane.showMessageDialog( fc, newFolderErrorText + newFolderErrorSeparator + exc, newFolderErrorText, JOptionPane.ERROR_MESSAGE); return; } fc.rescanCurrentDirectory(); } } /** {@collect.stats} * Acts on the "home" key event or equivalent event. */ protected class GoHomeAction extends AbstractAction { protected GoHomeAction() { super("Go Home"); } public void actionPerformed(ActionEvent e) { JFileChooser fc = getFileChooser(); changeDirectory(fc.getFileSystemView().getHomeDirectory()); } } protected class ChangeToParentDirectoryAction extends AbstractAction { protected ChangeToParentDirectoryAction() { super("Go Up"); putValue(Action.ACTION_COMMAND_KEY, FilePane.ACTION_CHANGE_TO_PARENT_DIRECTORY); } public void actionPerformed(ActionEvent e) { Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (focusOwner == null || !(focusOwner instanceof javax.swing.text.JTextComponent)) { getFileChooser().changeToParentDirectory(); } } } /** {@collect.stats} * Responds to an Open or Save request */ protected class ApproveSelectionAction extends AbstractAction { protected ApproveSelectionAction() { super(FilePane.ACTION_APPROVE_SELECTION); } public void actionPerformed(ActionEvent e) { if (isDirectorySelected()) { File dir = getDirectory(); if (dir != null) { try { // Strip trailing ".." dir = ShellFolder.getNormalizedFile(dir); } catch (IOException ex) { // Ok, use f as is } changeDirectory(dir); return; } } JFileChooser chooser = getFileChooser(); String filename = getFileName(); FileSystemView fs = chooser.getFileSystemView(); File dir = chooser.getCurrentDirectory(); if (filename != null) { // Remove whitespace from beginning and end of filename filename = filename.trim(); } if (filename == null || filename.equals("")) { // no file selected, multiple selection off, therefore cancel the approve action resetGlobFilter(); return; } File selectedFile = null; File[] selectedFiles = null; if (filename != null && !filename.equals("")) { // Unix: Resolve '~' to user's home directory if (File.separatorChar == '/') { if (filename.startsWith("~/")) { filename = System.getProperty("user.home") + filename.substring(1); } else if (filename.equals("~")) { filename = System.getProperty("user.home"); } } if (chooser.isMultiSelectionEnabled() && filename.startsWith("\"")) { ArrayList fList = new ArrayList(); filename = filename.substring(1); if (filename.endsWith("\"")) { filename = filename.substring(0, filename.length()-1); } File[] children = null; int childIndex = 0; do { String str; int i = filename.indexOf("\" \""); if (i > 0) { str = filename.substring(0, i); filename = filename.substring(i+3); } else { str = filename; filename = ""; } File file = fs.createFileObject(str); if (!file.isAbsolute()) { if (children == null) { children = fs.getFiles(dir, false); Arrays.sort(children); } for (int k = 0; k < children.length; k++) { int l = (childIndex + k) % children.length; if (children[l].getName().equals(str)) { file = children[l]; childIndex = l + 1; break; } } } fList.add(file); } while (filename.length() > 0); if (fList.size() > 0) { selectedFiles = (File[])fList.toArray(new File[fList.size()]); } resetGlobFilter(); } else { selectedFile = fs.createFileObject(filename); if(!selectedFile.isAbsolute()) { selectedFile = fs.getChild(dir, filename); } // check for wildcard pattern FileFilter currentFilter = chooser.getFileFilter(); if (!selectedFile.exists() && isGlobPattern(filename)) { changeDirectory(selectedFile.getParentFile()); if (globFilter == null) { globFilter = new GlobFilter(); } try { globFilter.setPattern(selectedFile.getName()); if (!(currentFilter instanceof GlobFilter)) { actualFileFilter = currentFilter; } chooser.setFileFilter(null); chooser.setFileFilter(globFilter); return; } catch (PatternSyntaxException pse) { // Not a valid glob pattern. Abandon filter. } } resetGlobFilter(); // Check for directory change action boolean isDir = (selectedFile != null && selectedFile.isDirectory()); boolean isTrav = (selectedFile != null && chooser.isTraversable(selectedFile)); boolean isDirSelEnabled = chooser.isDirectorySelectionEnabled(); boolean isFileSelEnabled = chooser.isFileSelectionEnabled(); boolean isCtrl = (e != null && (e.getModifiers() & ActionEvent.CTRL_MASK) != 0); if (isDir && isTrav && (isCtrl || !isDirSelEnabled)) { changeDirectory(selectedFile); return; } else if ((isDir || !isFileSelEnabled) && (!isDir || !isDirSelEnabled) && (!isDirSelEnabled || selectedFile.exists())) { selectedFile = null; } } } if (selectedFiles != null || selectedFile != null) { if (selectedFiles != null || chooser.isMultiSelectionEnabled()) { if (selectedFiles == null) { selectedFiles = new File[] { selectedFile }; } chooser.setSelectedFiles(selectedFiles); // Do it again. This is a fix for bug 4949273 to force the // selected value in case the ListSelectionModel clears it // for non-existing file names. chooser.setSelectedFiles(selectedFiles); } else { chooser.setSelectedFile(selectedFile); } chooser.approveSelection(); } else { if (chooser.isMultiSelectionEnabled()) { chooser.setSelectedFiles(null); } else { chooser.setSelectedFile(null); } chooser.cancelSelection(); } } } private void resetGlobFilter() { if (actualFileFilter != null) { JFileChooser chooser = getFileChooser(); FileFilter currentFilter = chooser.getFileFilter(); if (currentFilter != null && currentFilter.equals(globFilter)) { chooser.setFileFilter(actualFileFilter); chooser.removeChoosableFileFilter(globFilter); } actualFileFilter = null; } } private static boolean isGlobPattern(String filename) { return ((File.separatorChar == '\\' && (filename.indexOf('*') >= 0 || filename.indexOf('?') >= 0)) || (File.separatorChar == '/' && (filename.indexOf('*') >= 0 || filename.indexOf('?') >= 0 || filename.indexOf('[') >= 0))); } /* A file filter which accepts file patterns containing * the special wildcards *? on Windows and *?[] on Unix. */ class GlobFilter extends FileFilter { Pattern pattern; String globPattern; public void setPattern(String globPattern) { char[] gPat = globPattern.toCharArray(); char[] rPat = new char[gPat.length * 2]; boolean isWin32 = (File.separatorChar == '\\'); boolean inBrackets = false; int j = 0; this.globPattern = globPattern; if (isWin32) { // On windows, a pattern ending with *.* is equal to ending with * int len = gPat.length; if (globPattern.endsWith("*.*")) { len -= 2; } for (int i = 0; i < len; i++) { switch(gPat[i]) { case '*': rPat[j++] = '.'; rPat[j++] = '*'; break; case '?': rPat[j++] = '.'; break; case '\\': rPat[j++] = '\\'; rPat[j++] = '\\'; break; default: if ("+()^$.{}[]".indexOf(gPat[i]) >= 0) { rPat[j++] = '\\'; } rPat[j++] = gPat[i]; break; } } } else { for (int i = 0; i < gPat.length; i++) { switch(gPat[i]) { case '*': if (!inBrackets) { rPat[j++] = '.'; } rPat[j++] = '*'; break; case '?': rPat[j++] = inBrackets ? '?' : '.'; break; case '[': inBrackets = true; rPat[j++] = gPat[i]; if (i < gPat.length - 1) { switch (gPat[i+1]) { case '!': case '^': rPat[j++] = '^'; i++; break; case ']': rPat[j++] = gPat[++i]; break; } } break; case ']': rPat[j++] = gPat[i]; inBrackets = false; break; case '\\': if (i == 0 && gPat.length > 1 && gPat[1] == '~') { rPat[j++] = gPat[++i]; } else { rPat[j++] = '\\'; if (i < gPat.length - 1 && "*?[]".indexOf(gPat[i+1]) >= 0) { rPat[j++] = gPat[++i]; } else { rPat[j++] = '\\'; } } break; default: //if ("+()|^$.{}<>".indexOf(gPat[i]) >= 0) { if (!Character.isLetterOrDigit(gPat[i])) { rPat[j++] = '\\'; } rPat[j++] = gPat[i]; break; } } } this.pattern = Pattern.compile(new String(rPat, 0, j), Pattern.CASE_INSENSITIVE); } public boolean accept(File f) { if (f == null) { return false; } if (f.isDirectory()) { return true; } return pattern.matcher(f.getName()).matches(); } public String getDescription() { return globPattern; } } /** {@collect.stats} * Responds to a cancel request. */ protected class CancelSelectionAction extends AbstractAction { public void actionPerformed(ActionEvent e) { getFileChooser().cancelSelection(); } } /** {@collect.stats} * Rescans the files in the current directory */ protected class UpdateAction extends AbstractAction { public void actionPerformed(ActionEvent e) { JFileChooser fc = getFileChooser(); fc.setCurrentDirectory(fc.getFileSystemView().createFileObject(getDirectoryName())); fc.rescanCurrentDirectory(); } } private void changeDirectory(File dir) { JFileChooser fc = getFileChooser(); // Traverse shortcuts on Windows if (dir != null && File.separatorChar == '\\' && dir.getPath().endsWith(".lnk")) { try { File linkedTo = ShellFolder.getShellFolder(dir).getLinkLocation(); if (linkedTo != null && fc.isTraversable(linkedTo)) { dir = linkedTo; } else { return; } } catch (FileNotFoundException ex) { return; } } fc.setCurrentDirectory(dir); if (fc.getFileSelectionMode() == JFileChooser.FILES_AND_DIRECTORIES && fc.getFileSystemView().isFileSystem(dir)) { setFileName(dir.getAbsolutePath()); } } // ***************************************** // ***** default AcceptAll file filter ***** // ***************************************** protected class AcceptAllFileFilter extends FileFilter { public AcceptAllFileFilter() { } public boolean accept(File f) { return true; } public String getDescription() { return UIManager.getString("FileChooser.acceptAllFileFilterText"); } } // *********************** // * FileView operations * // *********************** protected class BasicFileView extends FileView { /* FileView type descriptions */ // PENDING(jeff) - pass in the icon cache size protected Hashtable<File,Icon> iconCache = new Hashtable<File,Icon>(); public BasicFileView() { } public void clearIconCache() { iconCache = new Hashtable<File,Icon>(); } public String getName(File f) { // Note: Returns display name rather than file name String fileName = null; if(f != null) { fileName = getFileChooser().getFileSystemView().getSystemDisplayName(f); } return fileName; } public String getDescription(File f) { return f.getName(); } public String getTypeDescription(File f) { String type = getFileChooser().getFileSystemView().getSystemTypeDescription(f); if (type == null) { if (f.isDirectory()) { type = directoryDescriptionText; } else { type = fileDescriptionText; } } return type; } public Icon getCachedIcon(File f) { return (Icon) iconCache.get(f); } public void cacheIcon(File f, Icon i) { if(f == null || i == null) { return; } iconCache.put(f, i); } public Icon getIcon(File f) { Icon icon = getCachedIcon(f); if(icon != null) { return icon; } icon = fileIcon; if (f != null) { FileSystemView fsv = getFileChooser().getFileSystemView(); if (fsv.isFloppyDrive(f)) { icon = floppyDriveIcon; } else if (fsv.isDrive(f)) { icon = hardDriveIcon; } else if (fsv.isComputerNode(f)) { icon = computerIcon; } else if (f.isDirectory()) { icon = directoryIcon; } } cacheIcon(f, icon); return icon; } public Boolean isHidden(File f) { String name = f.getName(); if(name != null && name.charAt(0) == '.') { return Boolean.TRUE; } else { return Boolean.FALSE; } } } private static final TransferHandler defaultTransferHandler = new FileTransferHandler(); /** {@collect.stats} * Data transfer support for the file chooser. Since files are currently presented * as a list, the list support is reused with the added flavor of DataFlavor.javaFileListFlavor */ static class FileTransferHandler extends TransferHandler implements UIResource { /** {@collect.stats} * Create a Transferable to use as the source for a data transfer. * * @param c The component holding the data to be transfered. This * argument is provided to enable sharing of TransferHandlers by * multiple components. * @return The representation of the data to be transfered. * */ protected Transferable createTransferable(JComponent c) { Object[] values = null; if (c instanceof JList) { values = ((JList)c).getSelectedValues(); } else if (c instanceof JTable) { JTable table = (JTable)c; int[] rows = table.getSelectedRows(); if (rows != null) { values = new Object[rows.length]; for (int i=0; i<rows.length; i++) { values[i] = table.getValueAt(rows[i], 0); } } } if (values == null || values.length == 0) { return null; } StringBuffer plainBuf = new StringBuffer(); StringBuffer htmlBuf = new StringBuffer(); htmlBuf.append("<html>\n<body>\n<ul>\n"); for (int i = 0; i < values.length; i++) { Object obj = values[i]; String val = ((obj == null) ? "" : obj.toString()); plainBuf.append(val + "\n"); htmlBuf.append(" <li>" + val + "\n"); } // remove the last newline plainBuf.deleteCharAt(plainBuf.length() - 1); htmlBuf.append("</ul>\n</body>\n</html>"); return new FileTransferable(plainBuf.toString(), htmlBuf.toString(), values); } public int getSourceActions(JComponent c) { return COPY; } static class FileTransferable extends BasicTransferable { Object[] fileData; FileTransferable(String plainData, String htmlData, Object[] fileData) { super(plainData, htmlData); this.fileData = fileData; } /** {@collect.stats} * Best format of the file chooser is DataFlavor.javaFileListFlavor. */ protected DataFlavor[] getRicherFlavors() { DataFlavor[] flavors = new DataFlavor[1]; flavors[0] = DataFlavor.javaFileListFlavor; return flavors; } /** {@collect.stats} * The only richer format supported is the file list flavor */ protected Object getRicherData(DataFlavor flavor) { if (DataFlavor.javaFileListFlavor.equals(flavor)) { ArrayList files = new ArrayList(); for (int i = 0; i < fileData.length; i++) { files.add(fileData[i]); } return files; } return null; } } } }
Java
/* * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.Component; import java.awt.Container; import java.awt.Adjustable; import java.awt.event.*; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Point; import java.awt.Insets; import java.awt.Color; import java.awt.IllegalComponentStateException; import java.awt.Polygon; import java.beans.*; import java.util.Dictionary; import java.util.Enumeration; import javax.swing.border.AbstractBorder; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.*; import sun.swing.DefaultLookup; import sun.swing.UIAction; /** {@collect.stats} * A Basic L&F implementation of SliderUI. * * @author Tom Santos */ public class BasicSliderUI extends SliderUI{ // Old actions forward to an instance of this. private static final Actions SHARED_ACTION = new Actions(); public static final int POSITIVE_SCROLL = +1; public static final int NEGATIVE_SCROLL = -1; public static final int MIN_SCROLL = -2; public static final int MAX_SCROLL = +2; protected Timer scrollTimer; protected JSlider slider; protected Insets focusInsets = null; protected Insets insetCache = null; protected boolean leftToRightCache = true; protected Rectangle focusRect = null; protected Rectangle contentRect = null; protected Rectangle labelRect = null; protected Rectangle tickRect = null; protected Rectangle trackRect = null; protected Rectangle thumbRect = null; protected int trackBuffer = 0; // The distance that the track is from the side of the control private transient boolean isDragging; protected TrackListener trackListener; protected ChangeListener changeListener; protected ComponentListener componentListener; protected FocusListener focusListener; protected ScrollListener scrollListener; protected PropertyChangeListener propertyChangeListener; private Handler handler; private int lastValue; // Colors private Color shadowColor; private Color highlightColor; private Color focusColor; /** {@collect.stats} * Whther or not sameLabelBaselines is up to date. */ private boolean checkedLabelBaselines; /** {@collect.stats} * Whether or not all the entries in the labeltable have the same * baseline. */ private boolean sameLabelBaselines; protected Color getShadowColor() { return shadowColor; } protected Color getHighlightColor() { return highlightColor; } protected Color getFocusColor() { return focusColor; } /** {@collect.stats} * Returns true if the user is dragging the slider. * * @return true if the user is dragging the slider * @since 1.5 */ protected boolean isDragging() { return isDragging; } ///////////////////////////////////////////////////////////////////////////// // ComponentUI Interface Implementation methods ///////////////////////////////////////////////////////////////////////////// public static ComponentUI createUI(JComponent b) { return new BasicSliderUI((JSlider)b); } public BasicSliderUI(JSlider b) { } public void installUI(JComponent c) { slider = (JSlider) c; checkedLabelBaselines = false; slider.setEnabled(slider.isEnabled()); LookAndFeel.installProperty(slider, "opaque", Boolean.TRUE); isDragging = false; trackListener = createTrackListener( slider ); changeListener = createChangeListener( slider ); componentListener = createComponentListener( slider ); focusListener = createFocusListener( slider ); scrollListener = createScrollListener( slider ); propertyChangeListener = createPropertyChangeListener( slider ); installDefaults( slider ); installListeners( slider ); installKeyboardActions( slider ); scrollTimer = new Timer( 100, scrollListener ); scrollTimer.setInitialDelay( 300 ); insetCache = slider.getInsets(); leftToRightCache = BasicGraphicsUtils.isLeftToRight(slider); focusRect = new Rectangle(); contentRect = new Rectangle(); labelRect = new Rectangle(); tickRect = new Rectangle(); trackRect = new Rectangle(); thumbRect = new Rectangle(); lastValue = slider.getValue(); calculateGeometry(); // This figures out where the labels, ticks, track, and thumb are. } public void uninstallUI(JComponent c) { if ( c != slider ) throw new IllegalComponentStateException( this + " was asked to deinstall() " + c + " when it only knows about " + slider + "."); LookAndFeel.uninstallBorder(slider); scrollTimer.stop(); scrollTimer = null; uninstallListeners( slider ); uninstallKeyboardActions(slider); focusInsets = null; insetCache = null; leftToRightCache = true; focusRect = null; contentRect = null; labelRect = null; tickRect = null; trackRect = null; thumbRect = null; trackListener = null; changeListener = null; componentListener = null; focusListener = null; scrollListener = null; propertyChangeListener = null; slider = null; } protected void installDefaults( JSlider slider ) { LookAndFeel.installBorder(slider, "Slider.border"); LookAndFeel.installColorsAndFont(slider, "Slider.background", "Slider.foreground", "Slider.font"); highlightColor = UIManager.getColor("Slider.highlight"); shadowColor = UIManager.getColor("Slider.shadow"); focusColor = UIManager.getColor("Slider.focus"); focusInsets = (Insets)UIManager.get( "Slider.focusInsets" ); // use default if missing so that BasicSliderUI can be used in other // LAFs like Nimbus if (focusInsets == null) focusInsets = new InsetsUIResource(2,2,2,2); } protected TrackListener createTrackListener(JSlider slider) { return new TrackListener(); } protected ChangeListener createChangeListener(JSlider slider) { return getHandler(); } protected ComponentListener createComponentListener(JSlider slider) { return getHandler(); } protected FocusListener createFocusListener(JSlider slider) { return getHandler(); } protected ScrollListener createScrollListener( JSlider slider ) { return new ScrollListener(); } protected PropertyChangeListener createPropertyChangeListener( JSlider slider) { return getHandler(); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } protected void installListeners( JSlider slider ) { slider.addMouseListener(trackListener); slider.addMouseMotionListener(trackListener); slider.addFocusListener(focusListener); slider.addComponentListener(componentListener); slider.addPropertyChangeListener( propertyChangeListener ); slider.getModel().addChangeListener(changeListener); } protected void uninstallListeners( JSlider slider ) { slider.removeMouseListener(trackListener); slider.removeMouseMotionListener(trackListener); slider.removeFocusListener(focusListener); slider.removeComponentListener(componentListener); slider.removePropertyChangeListener( propertyChangeListener ); slider.getModel().removeChangeListener(changeListener); handler = null; } protected void installKeyboardActions( JSlider slider ) { InputMap km = getInputMap(JComponent.WHEN_FOCUSED, slider); SwingUtilities.replaceUIInputMap(slider, JComponent.WHEN_FOCUSED, km); LazyActionMap.installLazyActionMap(slider, BasicSliderUI.class, "Slider.actionMap"); } InputMap getInputMap(int condition, JSlider slider) { if (condition == JComponent.WHEN_FOCUSED) { InputMap keyMap = (InputMap)DefaultLookup.get(slider, this, "Slider.focusInputMap"); InputMap rtlKeyMap; if (slider.getComponentOrientation().isLeftToRight() || ((rtlKeyMap = (InputMap)DefaultLookup.get(slider, this, "Slider.focusInputMap.RightToLeft")) == null)) { return keyMap; } else { rtlKeyMap.setParent(keyMap); return rtlKeyMap; } } return null; } /** {@collect.stats} * Populates ComboBox's actions. */ static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.POSITIVE_UNIT_INCREMENT)); map.put(new Actions(Actions.POSITIVE_BLOCK_INCREMENT)); map.put(new Actions(Actions.NEGATIVE_UNIT_INCREMENT)); map.put(new Actions(Actions.NEGATIVE_BLOCK_INCREMENT)); map.put(new Actions(Actions.MIN_SCROLL_INCREMENT)); map.put(new Actions(Actions.MAX_SCROLL_INCREMENT)); } protected void uninstallKeyboardActions( JSlider slider ) { SwingUtilities.replaceUIActionMap(slider, null); SwingUtilities.replaceUIInputMap(slider, JComponent.WHEN_FOCUSED, null); } /** {@collect.stats} * Returns the baseline. * * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public int getBaseline(JComponent c, int width, int height) { super.getBaseline(c, width, height); if (slider.getPaintLabels() && labelsHaveSameBaselines()) { FontMetrics metrics = slider.getFontMetrics(slider.getFont()); Insets insets = slider.getInsets(); Dimension thumbSize = getThumbSize(); if (slider.getOrientation() == JSlider.HORIZONTAL) { int tickLength = getTickLength(); int contentHeight = height - insets.top - insets.bottom - focusInsets.top - focusInsets.bottom; int thumbHeight = thumbSize.height; int centerSpacing = thumbHeight; if (slider.getPaintTicks()) { centerSpacing += tickLength; } // Assume uniform labels. centerSpacing += getHeightOfTallestLabel(); int trackY = insets.top + focusInsets.top + (contentHeight - centerSpacing - 1) / 2; int trackHeight = thumbHeight; int tickY = trackY + trackHeight; int tickHeight = tickLength; if (!slider.getPaintTicks()) { tickHeight = 0; } int labelY = tickY + tickHeight; return labelY + metrics.getAscent(); } else { // vertical boolean inverted = slider.getInverted(); Integer value = inverted ? getLowestValue() : getHighestValue(); if (value != null) { int thumbHeight = thumbSize.height; int trackBuffer = Math.max(metrics.getHeight() / 2, thumbHeight / 2); int contentY = focusInsets.top + insets.top; int trackY = contentY + trackBuffer; int trackHeight = height - focusInsets.top - focusInsets.bottom - insets.top - insets.bottom - trackBuffer - trackBuffer; int yPosition = yPositionForValue(value, trackY, trackHeight); return yPosition - metrics.getHeight() / 2 + metrics.getAscent(); } } } return 0; } /** {@collect.stats} * Returns an enum indicating how the baseline of the component * changes as the size changes. * * @throws NullPointerException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public Component.BaselineResizeBehavior getBaselineResizeBehavior( JComponent c) { super.getBaselineResizeBehavior(c); // NOTE: BasicSpinner really provides for CENTER_OFFSET, but // the default min/pref size is smaller than it should be // so that getBaseline() doesn't implement the contract // for CENTER_OFFSET as defined in Component. return Component.BaselineResizeBehavior.OTHER; } /** {@collect.stats} * Returns true if all the labels from the label table have the same * baseline. * * @return true if all the labels from the label table have the * same baseline * @since 1.6 */ protected boolean labelsHaveSameBaselines() { if (!checkedLabelBaselines) { checkedLabelBaselines = true; Dictionary dictionary = slider.getLabelTable(); if (dictionary != null) { sameLabelBaselines = true; Enumeration elements = dictionary.elements(); int baseline = -1; while (elements.hasMoreElements()) { Component label = (Component)elements.nextElement(); Dimension pref = label.getPreferredSize(); int labelBaseline = label.getBaseline(pref.width, pref.height); if (labelBaseline >= 0) { if (baseline == -1) { baseline = labelBaseline; } else if (baseline != labelBaseline) { sameLabelBaselines = false; break; } } else { sameLabelBaselines = false; break; } } } else { sameLabelBaselines = false; } } return sameLabelBaselines; } public Dimension getPreferredHorizontalSize() { Dimension horizDim = (Dimension)DefaultLookup.get(slider, this, "Slider.horizontalSize"); if (horizDim == null) { horizDim = new Dimension(200, 21); } return horizDim; } public Dimension getPreferredVerticalSize() { Dimension vertDim = (Dimension)DefaultLookup.get(slider, this, "Slider.verticalSize"); if (vertDim == null) { vertDim = new Dimension(21, 200); } return vertDim; } public Dimension getMinimumHorizontalSize() { Dimension minHorizDim = (Dimension)DefaultLookup.get(slider, this, "Slider.minimumHorizontalSize"); if (minHorizDim == null) { minHorizDim = new Dimension(36, 21); } return minHorizDim; } public Dimension getMinimumVerticalSize() { Dimension minVertDim = (Dimension)DefaultLookup.get(slider, this, "Slider.minimumVerticalSize"); if (minVertDim == null) { minVertDim = new Dimension(21, 36); } return minVertDim; } public Dimension getPreferredSize(JComponent c) { recalculateIfInsetsChanged(); Dimension d; if ( slider.getOrientation() == JSlider.VERTICAL ) { d = new Dimension(getPreferredVerticalSize()); d.width = insetCache.left + insetCache.right; d.width += focusInsets.left + focusInsets.right; d.width += trackRect.width + tickRect.width + labelRect.width; } else { d = new Dimension(getPreferredHorizontalSize()); d.height = insetCache.top + insetCache.bottom; d.height += focusInsets.top + focusInsets.bottom; d.height += trackRect.height + tickRect.height + labelRect.height; } return d; } public Dimension getMinimumSize(JComponent c) { recalculateIfInsetsChanged(); Dimension d; if ( slider.getOrientation() == JSlider.VERTICAL ) { d = new Dimension(getMinimumVerticalSize()); d.width = insetCache.left + insetCache.right; d.width += focusInsets.left + focusInsets.right; d.width += trackRect.width + tickRect.width + labelRect.width; } else { d = new Dimension(getMinimumHorizontalSize()); d.height = insetCache.top + insetCache.bottom; d.height += focusInsets.top + focusInsets.bottom; d.height += trackRect.height + tickRect.height + labelRect.height; } return d; } public Dimension getMaximumSize(JComponent c) { Dimension d = getPreferredSize(c); if ( slider.getOrientation() == JSlider.VERTICAL ) { d.height = Short.MAX_VALUE; } else { d.width = Short.MAX_VALUE; } return d; } protected void calculateGeometry() { calculateFocusRect(); calculateContentRect(); calculateThumbSize(); calculateTrackBuffer(); calculateTrackRect(); calculateTickRect(); calculateLabelRect(); calculateThumbLocation(); } protected void calculateFocusRect() { focusRect.x = insetCache.left; focusRect.y = insetCache.top; focusRect.width = slider.getWidth() - (insetCache.left + insetCache.right); focusRect.height = slider.getHeight() - (insetCache.top + insetCache.bottom); } protected void calculateThumbSize() { Dimension size = getThumbSize(); thumbRect.setSize( size.width, size.height ); } protected void calculateContentRect() { contentRect.x = focusRect.x + focusInsets.left; contentRect.y = focusRect.y + focusInsets.top; contentRect.width = focusRect.width - (focusInsets.left + focusInsets.right); contentRect.height = focusRect.height - (focusInsets.top + focusInsets.bottom); } protected void calculateThumbLocation() { if ( slider.getSnapToTicks() ) { int sliderValue = slider.getValue(); int snappedValue = sliderValue; int majorTickSpacing = slider.getMajorTickSpacing(); int minorTickSpacing = slider.getMinorTickSpacing(); int tickSpacing = 0; if ( minorTickSpacing > 0 ) { tickSpacing = minorTickSpacing; } else if ( majorTickSpacing > 0 ) { tickSpacing = majorTickSpacing; } if ( tickSpacing != 0 ) { // If it's not on a tick, change the value if ( (sliderValue - slider.getMinimum()) % tickSpacing != 0 ) { float temp = (float)(sliderValue - slider.getMinimum()) / (float)tickSpacing; int whichTick = Math.round( temp ); // This is the fix for the bug #6401380 if (temp - (int)temp == .5 && sliderValue < lastValue) { whichTick --; } snappedValue = slider.getMinimum() + (whichTick * tickSpacing); } if( snappedValue != sliderValue ) { slider.setValue( snappedValue ); } } } if ( slider.getOrientation() == JSlider.HORIZONTAL ) { int valuePosition = xPositionForValue(slider.getValue()); thumbRect.x = valuePosition - (thumbRect.width / 2); thumbRect.y = trackRect.y; } else { int valuePosition = yPositionForValue(slider.getValue()); thumbRect.x = trackRect.x; thumbRect.y = valuePosition - (thumbRect.height / 2); } } protected void calculateTrackBuffer() { if ( slider.getPaintLabels() && slider.getLabelTable() != null ) { Component highLabel = getHighestValueLabel(); Component lowLabel = getLowestValueLabel(); if ( slider.getOrientation() == JSlider.HORIZONTAL ) { trackBuffer = Math.max( highLabel.getBounds().width, lowLabel.getBounds().width ) / 2; trackBuffer = Math.max( trackBuffer, thumbRect.width / 2 ); } else { trackBuffer = Math.max( highLabel.getBounds().height, lowLabel.getBounds().height ) / 2; trackBuffer = Math.max( trackBuffer, thumbRect.height / 2 ); } } else { if ( slider.getOrientation() == JSlider.HORIZONTAL ) { trackBuffer = thumbRect.width / 2; } else { trackBuffer = thumbRect.height / 2; } } } protected void calculateTrackRect() { int centerSpacing = 0; // used to center sliders added using BorderLayout.CENTER (bug 4275631) if ( slider.getOrientation() == JSlider.HORIZONTAL ) { centerSpacing = thumbRect.height; if ( slider.getPaintTicks() ) centerSpacing += getTickLength(); if ( slider.getPaintLabels() ) centerSpacing += getHeightOfTallestLabel(); trackRect.x = contentRect.x + trackBuffer; trackRect.y = contentRect.y + (contentRect.height - centerSpacing - 1)/2; trackRect.width = contentRect.width - (trackBuffer * 2); trackRect.height = thumbRect.height; } else { centerSpacing = thumbRect.width; if (BasicGraphicsUtils.isLeftToRight(slider)) { if ( slider.getPaintTicks() ) centerSpacing += getTickLength(); if ( slider.getPaintLabels() ) centerSpacing += getWidthOfWidestLabel(); } else { if ( slider.getPaintTicks() ) centerSpacing -= getTickLength(); if ( slider.getPaintLabels() ) centerSpacing -= getWidthOfWidestLabel(); } trackRect.x = contentRect.x + (contentRect.width - centerSpacing - 1)/2; trackRect.y = contentRect.y + trackBuffer; trackRect.width = thumbRect.width; trackRect.height = contentRect.height - (trackBuffer * 2); } } /** {@collect.stats} * Gets the height of the tick area for horizontal sliders and the width of the * tick area for vertical sliders. BasicSliderUI uses the returned value to * determine the tick area rectangle. If you want to give your ticks some room, * make this larger than you need and paint your ticks away from the sides in paintTicks(). */ protected int getTickLength() { return 8; } protected void calculateTickRect() { if ( slider.getOrientation() == JSlider.HORIZONTAL ) { tickRect.x = trackRect.x; tickRect.y = trackRect.y + trackRect.height; tickRect.width = trackRect.width; tickRect.height = (slider.getPaintTicks()) ? getTickLength() : 0; } else { tickRect.width = (slider.getPaintTicks()) ? getTickLength() : 0; if(BasicGraphicsUtils.isLeftToRight(slider)) { tickRect.x = trackRect.x + trackRect.width; } else { tickRect.x = trackRect.x - tickRect.width; } tickRect.y = trackRect.y; tickRect.height = trackRect.height; } } protected void calculateLabelRect() { if ( slider.getPaintLabels() ) { if ( slider.getOrientation() == JSlider.HORIZONTAL ) { labelRect.x = tickRect.x - trackBuffer; labelRect.y = tickRect.y + tickRect.height; labelRect.width = tickRect.width + (trackBuffer * 2); labelRect.height = getHeightOfTallestLabel(); } else { if(BasicGraphicsUtils.isLeftToRight(slider)) { labelRect.x = tickRect.x + tickRect.width; labelRect.width = getWidthOfWidestLabel(); } else { labelRect.width = getWidthOfWidestLabel(); labelRect.x = tickRect.x - labelRect.width; } labelRect.y = tickRect.y - trackBuffer; labelRect.height = tickRect.height + (trackBuffer * 2); } } else { if ( slider.getOrientation() == JSlider.HORIZONTAL ) { labelRect.x = tickRect.x; labelRect.y = tickRect.y + tickRect.height; labelRect.width = tickRect.width; labelRect.height = 0; } else { if(BasicGraphicsUtils.isLeftToRight(slider)) { labelRect.x = tickRect.x + tickRect.width; } else { labelRect.x = tickRect.x; } labelRect.y = tickRect.y; labelRect.width = 0; labelRect.height = tickRect.height; } } } protected Dimension getThumbSize() { Dimension size = new Dimension(); if ( slider.getOrientation() == JSlider.VERTICAL ) { size.width = 20; size.height = 11; } else { size.width = 11; size.height = 20; } return size; } public class PropertyChangeHandler implements PropertyChangeListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void propertyChange( PropertyChangeEvent e ) { getHandler().propertyChange(e); } } protected int getWidthOfWidestLabel() { Dictionary dictionary = slider.getLabelTable(); int widest = 0; if ( dictionary != null ) { Enumeration keys = dictionary.keys(); while ( keys.hasMoreElements() ) { Component label = (Component)dictionary.get( keys.nextElement() ); widest = Math.max( label.getPreferredSize().width, widest ); } } return widest; } protected int getHeightOfTallestLabel() { Dictionary dictionary = slider.getLabelTable(); int tallest = 0; if ( dictionary != null ) { Enumeration keys = dictionary.keys(); while ( keys.hasMoreElements() ) { Component label = (Component)dictionary.get( keys.nextElement() ); tallest = Math.max( label.getPreferredSize().height, tallest ); } } return tallest; } protected int getWidthOfHighValueLabel() { Component label = getHighestValueLabel(); int width = 0; if ( label != null ) { width = label.getPreferredSize().width; } return width; } protected int getWidthOfLowValueLabel() { Component label = getLowestValueLabel(); int width = 0; if ( label != null ) { width = label.getPreferredSize().width; } return width; } protected int getHeightOfHighValueLabel() { Component label = getHighestValueLabel(); int height = 0; if ( label != null ) { height = label.getPreferredSize().height; } return height; } protected int getHeightOfLowValueLabel() { Component label = getLowestValueLabel(); int height = 0; if ( label != null ) { height = label.getPreferredSize().height; } return height; } protected boolean drawInverted() { if (slider.getOrientation()==JSlider.HORIZONTAL) { if(BasicGraphicsUtils.isLeftToRight(slider)) { return slider.getInverted(); } else { return !slider.getInverted(); } } else { return slider.getInverted(); } } /** {@collect.stats} * Returns the biggest value that has an entry in the label table. * * @return biggest value that has an entry in the label table, or * null. * @since 1.6 */ protected Integer getHighestValue() { Dictionary dictionary = slider.getLabelTable(); if (dictionary != null) { Enumeration keys = dictionary.keys(); int max = slider.getMinimum() - 1; while (keys.hasMoreElements()) { max = Math.max(max, ((Integer)keys.nextElement()).intValue()); } if (max == slider.getMinimum() - 1) { return null; } return max; } return null; } /** {@collect.stats} * Returns the smallest value that has an entry in the label table. * * @return smallest value that has an entry in the label table, or * null. * @since 1.6 */ protected Integer getLowestValue() { Dictionary dictionary = slider.getLabelTable(); if (dictionary != null) { Enumeration keys = dictionary.keys(); int min = slider.getMaximum() + 1; while (keys.hasMoreElements()) { min = Math.min(min, ((Integer)keys.nextElement()).intValue()); } if (min == slider.getMaximum() + 1) { return null; } return min; } return null; } /** {@collect.stats} * Returns the label that corresponds to the highest slider value in the label table. * @see JSlider#setLabelTable */ protected Component getLowestValueLabel() { Integer min = getLowestValue(); if (min != null) { return (Component)slider.getLabelTable().get(min); } return null; } /** {@collect.stats} * Returns the label that corresponds to the lowest slider value in the label table. * @see JSlider#setLabelTable */ protected Component getHighestValueLabel() { Integer max = getHighestValue(); if (max != null) { return (Component)slider.getLabelTable().get(max); } return null; } public void paint( Graphics g, JComponent c ) { recalculateIfInsetsChanged(); recalculateIfOrientationChanged(); Rectangle clip = g.getClipBounds(); if ( !clip.intersects(trackRect) && slider.getPaintTrack()) calculateGeometry(); if ( slider.getPaintTrack() && clip.intersects( trackRect ) ) { paintTrack( g ); } if ( slider.getPaintTicks() && clip.intersects( tickRect ) ) { paintTicks( g ); } if ( slider.getPaintLabels() && clip.intersects( labelRect ) ) { paintLabels( g ); } if ( slider.hasFocus() && clip.intersects( focusRect ) ) { paintFocus( g ); } if ( clip.intersects( thumbRect ) ) { paintThumb( g ); } } protected void recalculateIfInsetsChanged() { Insets newInsets = slider.getInsets(); if ( !newInsets.equals( insetCache ) ) { insetCache = newInsets; calculateGeometry(); } } protected void recalculateIfOrientationChanged() { boolean ltr = BasicGraphicsUtils.isLeftToRight(slider); if ( ltr!=leftToRightCache ) { leftToRightCache = ltr; calculateGeometry(); } } public void paintFocus(Graphics g) { g.setColor( getFocusColor() ); BasicGraphicsUtils.drawDashedRect( g, focusRect.x, focusRect.y, focusRect.width, focusRect.height ); } public void paintTrack(Graphics g) { Rectangle trackBounds = trackRect; if ( slider.getOrientation() == JSlider.HORIZONTAL ) { int cy = (trackBounds.height / 2) - 2; int cw = trackBounds.width; g.translate(trackBounds.x, trackBounds.y + cy); g.setColor(getShadowColor()); g.drawLine(0, 0, cw - 1, 0); g.drawLine(0, 1, 0, 2); g.setColor(getHighlightColor()); g.drawLine(0, 3, cw, 3); g.drawLine(cw, 0, cw, 3); g.setColor(Color.black); g.drawLine(1, 1, cw-2, 1); g.translate(-trackBounds.x, -(trackBounds.y + cy)); } else { int cx = (trackBounds.width / 2) - 2; int ch = trackBounds.height; g.translate(trackBounds.x + cx, trackBounds.y); g.setColor(getShadowColor()); g.drawLine(0, 0, 0, ch - 1); g.drawLine(1, 0, 2, 0); g.setColor(getHighlightColor()); g.drawLine(3, 0, 3, ch); g.drawLine(0, ch, 3, ch); g.setColor(Color.black); g.drawLine(1, 1, 1, ch-2); g.translate(-(trackBounds.x + cx), -trackBounds.y); } } public void paintTicks(Graphics g) { Rectangle tickBounds = tickRect; int i; int maj, min, max; int w = tickBounds.width; int h = tickBounds.height; int centerEffect, tickHeight; g.setColor(DefaultLookup.getColor(slider, this, "Slider.tickColor", Color.black)); maj = slider.getMajorTickSpacing(); min = slider.getMinorTickSpacing(); if ( slider.getOrientation() == JSlider.HORIZONTAL ) { g.translate( 0, tickBounds.y); int value = slider.getMinimum(); int xPos = 0; if ( slider.getMinorTickSpacing() > 0 ) { while ( value <= slider.getMaximum() ) { xPos = xPositionForValue( value ); paintMinorTickForHorizSlider( g, tickBounds, xPos ); value += slider.getMinorTickSpacing(); } } if ( slider.getMajorTickSpacing() > 0 ) { value = slider.getMinimum(); while ( value <= slider.getMaximum() ) { xPos = xPositionForValue( value ); paintMajorTickForHorizSlider( g, tickBounds, xPos ); value += slider.getMajorTickSpacing(); } } g.translate( 0, -tickBounds.y); } else { g.translate(tickBounds.x, 0); int value = slider.getMinimum(); int yPos = 0; if ( slider.getMinorTickSpacing() > 0 ) { int offset = 0; if(!BasicGraphicsUtils.isLeftToRight(slider)) { offset = tickBounds.width - tickBounds.width / 2; g.translate(offset, 0); } while ( value <= slider.getMaximum() ) { yPos = yPositionForValue( value ); paintMinorTickForVertSlider( g, tickBounds, yPos ); value += slider.getMinorTickSpacing(); } if(!BasicGraphicsUtils.isLeftToRight(slider)) { g.translate(-offset, 0); } } if ( slider.getMajorTickSpacing() > 0 ) { value = slider.getMinimum(); if(!BasicGraphicsUtils.isLeftToRight(slider)) { g.translate(2, 0); } while ( value <= slider.getMaximum() ) { yPos = yPositionForValue( value ); paintMajorTickForVertSlider( g, tickBounds, yPos ); value += slider.getMajorTickSpacing(); } if(!BasicGraphicsUtils.isLeftToRight(slider)) { g.translate(-2, 0); } } g.translate(-tickBounds.x, 0); } } protected void paintMinorTickForHorizSlider( Graphics g, Rectangle tickBounds, int x ) { g.drawLine( x, 0, x, tickBounds.height / 2 - 1 ); } protected void paintMajorTickForHorizSlider( Graphics g, Rectangle tickBounds, int x ) { g.drawLine( x, 0, x, tickBounds.height - 2 ); } protected void paintMinorTickForVertSlider( Graphics g, Rectangle tickBounds, int y ) { g.drawLine( 0, y, tickBounds.width / 2 - 1, y ); } protected void paintMajorTickForVertSlider( Graphics g, Rectangle tickBounds, int y ) { g.drawLine( 0, y, tickBounds.width - 2, y ); } public void paintLabels( Graphics g ) { Rectangle labelBounds = labelRect; Dictionary dictionary = slider.getLabelTable(); if ( dictionary != null ) { Enumeration keys = dictionary.keys(); int minValue = slider.getMinimum(); int maxValue = slider.getMaximum(); boolean enabled = slider.isEnabled(); while ( keys.hasMoreElements() ) { Integer key = (Integer)keys.nextElement(); int value = key.intValue(); if (value >= minValue && value <= maxValue) { Component label = (Component)dictionary.get( key ); if (label instanceof JComponent) { ((JComponent)label).setEnabled(enabled); } if ( slider.getOrientation() == JSlider.HORIZONTAL ) { g.translate( 0, labelBounds.y ); paintHorizontalLabel( g, value, label ); g.translate( 0, -labelBounds.y ); } else { int offset = 0; if (!BasicGraphicsUtils.isLeftToRight(slider)) { offset = labelBounds.width - label.getPreferredSize().width; } g.translate( labelBounds.x + offset, 0 ); paintVerticalLabel( g, value, label ); g.translate( -labelBounds.x - offset, 0 ); } } } } } /** {@collect.stats} * Called for every label in the label table. Used to draw the labels for horizontal sliders. * The graphics have been translated to labelRect.y already. * @see JSlider#setLabelTable */ protected void paintHorizontalLabel( Graphics g, int value, Component label ) { int labelCenter = xPositionForValue( value ); int labelLeft = labelCenter - (label.getPreferredSize().width / 2); g.translate( labelLeft, 0 ); label.paint( g ); g.translate( -labelLeft, 0 ); } /** {@collect.stats} * Called for every label in the label table. Used to draw the labels for vertical sliders. * The graphics have been translated to labelRect.x already. * @see JSlider#setLabelTable */ protected void paintVerticalLabel( Graphics g, int value, Component label ) { int labelCenter = yPositionForValue( value ); int labelTop = labelCenter - (label.getPreferredSize().height / 2); g.translate( 0, labelTop ); label.paint( g ); g.translate( 0, -labelTop ); } public void paintThumb(Graphics g) { Rectangle knobBounds = thumbRect; int w = knobBounds.width; int h = knobBounds.height; g.translate(knobBounds.x, knobBounds.y); if ( slider.isEnabled() ) { g.setColor(slider.getBackground()); } else { g.setColor(slider.getBackground().darker()); } Boolean paintThumbArrowShape = (Boolean)slider.getClientProperty("Slider.paintThumbArrowShape"); if ((!slider.getPaintTicks() && paintThumbArrowShape == null) || paintThumbArrowShape == Boolean.FALSE) { // "plain" version g.fillRect(0, 0, w, h); g.setColor(Color.black); g.drawLine(0, h-1, w-1, h-1); g.drawLine(w-1, 0, w-1, h-1); g.setColor(highlightColor); g.drawLine(0, 0, 0, h-2); g.drawLine(1, 0, w-2, 0); g.setColor(shadowColor); g.drawLine(1, h-2, w-2, h-2); g.drawLine(w-2, 1, w-2, h-3); } else if ( slider.getOrientation() == JSlider.HORIZONTAL ) { int cw = w / 2; g.fillRect(1, 1, w-3, h-1-cw); Polygon p = new Polygon(); p.addPoint(1, h-cw); p.addPoint(cw-1, h-1); p.addPoint(w-2, h-1-cw); g.fillPolygon(p); g.setColor(highlightColor); g.drawLine(0, 0, w-2, 0); g.drawLine(0, 1, 0, h-1-cw); g.drawLine(0, h-cw, cw-1, h-1); g.setColor(Color.black); g.drawLine(w-1, 0, w-1, h-2-cw); g.drawLine(w-1, h-1-cw, w-1-cw, h-1); g.setColor(shadowColor); g.drawLine(w-2, 1, w-2, h-2-cw); g.drawLine(w-2, h-1-cw, w-1-cw, h-2); } else { // vertical int cw = h / 2; if(BasicGraphicsUtils.isLeftToRight(slider)) { g.fillRect(1, 1, w-1-cw, h-3); Polygon p = new Polygon(); p.addPoint(w-cw-1, 0); p.addPoint(w-1, cw); p.addPoint(w-1-cw, h-2); g.fillPolygon(p); g.setColor(highlightColor); g.drawLine(0, 0, 0, h - 2); // left g.drawLine(1, 0, w-1-cw, 0); // top g.drawLine(w-cw-1, 0, w-1, cw); // top slant g.setColor(Color.black); g.drawLine(0, h-1, w-2-cw, h-1); // bottom g.drawLine(w-1-cw, h-1, w-1, h-1-cw); // bottom slant g.setColor(shadowColor); g.drawLine(1, h-2, w-2-cw, h-2 ); // bottom g.drawLine(w-1-cw, h-2, w-2, h-cw-1 ); // bottom slant } else { g.fillRect(5, 1, w-1-cw, h-3); Polygon p = new Polygon(); p.addPoint(cw, 0); p.addPoint(0, cw); p.addPoint(cw, h-2); g.fillPolygon(p); g.setColor(highlightColor); g.drawLine(cw-1, 0, w-2, 0); // top g.drawLine(0, cw, cw, 0); // top slant g.setColor(Color.black); g.drawLine(0, h-1-cw, cw, h-1 ); // bottom slant g.drawLine(cw, h-1, w-1, h-1); // bottom g.setColor(shadowColor); g.drawLine(cw, h-2, w-2, h-2 ); // bottom g.drawLine(w-1, 1, w-1, h-2 ); // right } } g.translate(-knobBounds.x, -knobBounds.y); } // Used exclusively by setThumbLocation() private static Rectangle unionRect = new Rectangle(); public void setThumbLocation(int x, int y) { unionRect.setBounds( thumbRect ); thumbRect.setLocation( x, y ); SwingUtilities.computeUnion( thumbRect.x, thumbRect.y, thumbRect.width, thumbRect.height, unionRect ); slider.repaint( unionRect.x, unionRect.y, unionRect.width, unionRect.height ); } public void scrollByBlock(int direction) { synchronized(slider) { int oldValue = slider.getValue(); int blockIncrement = (slider.getMaximum() - slider.getMinimum()) / 10; if (blockIncrement <= 0 && slider.getMaximum() > slider.getMinimum()) { blockIncrement = 1; } int delta = blockIncrement * ((direction > 0) ? POSITIVE_SCROLL : NEGATIVE_SCROLL); slider.setValue(oldValue + delta); } } public void scrollByUnit(int direction) { synchronized(slider) { int oldValue = slider.getValue(); int delta = 1 * ((direction > 0) ? POSITIVE_SCROLL : NEGATIVE_SCROLL); slider.setValue(oldValue + delta); } } /** {@collect.stats} * This function is called when a mousePressed was detected in the track, not * in the thumb. The default behavior is to scroll by block. You can * override this method to stop it from scrolling or to add additional behavior. */ protected void scrollDueToClickInTrack( int dir ) { scrollByBlock( dir ); } protected int xPositionForValue( int value ) { int min = slider.getMinimum(); int max = slider.getMaximum(); int trackLength = trackRect.width; double valueRange = (double)max - (double)min; double pixelsPerValue = (double)trackLength / valueRange; int trackLeft = trackRect.x; int trackRight = trackRect.x + (trackRect.width - 1); int xPosition; if ( !drawInverted() ) { xPosition = trackLeft; xPosition += Math.round( pixelsPerValue * ((double)value - min) ); } else { xPosition = trackRight; xPosition -= Math.round( pixelsPerValue * ((double)value - min) ); } xPosition = Math.max( trackLeft, xPosition ); xPosition = Math.min( trackRight, xPosition ); return xPosition; } protected int yPositionForValue( int value ) { return yPositionForValue(value, trackRect.y, trackRect.height); } /** {@collect.stats} * Returns the y location for the specified value. No checking is * done on the arguments. In particular if <code>trackHeight</code> is * negative undefined results may occur. * * @param value the slider value to get the location for * @param trackY y-origin of the track * @param trackHeight the height of the track * @since 1.6 */ protected int yPositionForValue(int value, int trackY, int trackHeight) { int min = slider.getMinimum(); int max = slider.getMaximum(); double valueRange = (double)max - (double)min; double pixelsPerValue = (double)trackHeight / (double)valueRange; int trackBottom = trackY + (trackHeight - 1); int yPosition; if ( !drawInverted() ) { yPosition = trackY; yPosition += Math.round( pixelsPerValue * ((double)max - value ) ); } else { yPosition = trackY; yPosition += Math.round( pixelsPerValue * ((double)value - min) ); } yPosition = Math.max( trackY, yPosition ); yPosition = Math.min( trackBottom, yPosition ); return yPosition; } /** {@collect.stats} * Returns a value give a y position. If yPos is past the track at the top or the * bottom it will set the value to the min or max of the slider, depending if the * slider is inverted or not. */ public int valueForYPosition( int yPos ) { int value; final int minValue = slider.getMinimum(); final int maxValue = slider.getMaximum(); final int trackLength = trackRect.height; final int trackTop = trackRect.y; final int trackBottom = trackRect.y + (trackRect.height - 1); if ( yPos <= trackTop ) { value = drawInverted() ? minValue : maxValue; } else if ( yPos >= trackBottom ) { value = drawInverted() ? maxValue : minValue; } else { int distanceFromTrackTop = yPos - trackTop; double valueRange = (double)maxValue - (double)minValue; double valuePerPixel = valueRange / (double)trackLength; int valueFromTrackTop = (int)Math.round( distanceFromTrackTop * valuePerPixel ); value = drawInverted() ? minValue + valueFromTrackTop : maxValue - valueFromTrackTop; } return value; } /** {@collect.stats} * Returns a value give an x position. If xPos is past the track at the left or the * right it will set the value to the min or max of the slider, depending if the * slider is inverted or not. */ public int valueForXPosition( int xPos ) { int value; final int minValue = slider.getMinimum(); final int maxValue = slider.getMaximum(); final int trackLength = trackRect.width; final int trackLeft = trackRect.x; final int trackRight = trackRect.x + (trackRect.width - 1); if ( xPos <= trackLeft ) { value = drawInverted() ? maxValue : minValue; } else if ( xPos >= trackRight ) { value = drawInverted() ? minValue : maxValue; } else { int distanceFromTrackLeft = xPos - trackLeft; double valueRange = (double)maxValue - (double)minValue; double valuePerPixel = valueRange / (double)trackLength; int valueFromTrackLeft = (int)Math.round( distanceFromTrackLeft * valuePerPixel ); value = drawInverted() ? maxValue - valueFromTrackLeft : minValue + valueFromTrackLeft; } return value; } private class Handler implements ChangeListener, ComponentListener, FocusListener, PropertyChangeListener { // Change Handler public void stateChanged(ChangeEvent e) { if (!isDragging) { calculateThumbLocation(); slider.repaint(); } lastValue = slider.getValue(); } // Component Handler public void componentHidden(ComponentEvent e) { } public void componentMoved(ComponentEvent e) { } public void componentResized(ComponentEvent e) { calculateGeometry(); slider.repaint(); } public void componentShown(ComponentEvent e) { } // Focus Handler public void focusGained(FocusEvent e) { slider.repaint(); } public void focusLost(FocusEvent e) { slider.repaint(); } // Property Change Handler public void propertyChange(PropertyChangeEvent e) { String propertyName = e.getPropertyName(); if (propertyName == "orientation" || propertyName == "inverted" || propertyName == "labelTable" || propertyName == "majorTickSpacing" || propertyName == "minorTickSpacing" || propertyName == "paintTicks" || propertyName == "paintTrack" || propertyName == "font" || propertyName == "paintLabels") { checkedLabelBaselines = false; calculateGeometry(); slider.repaint(); } else if (propertyName == "componentOrientation") { calculateGeometry(); slider.repaint(); InputMap km = getInputMap(JComponent.WHEN_FOCUSED, slider); SwingUtilities.replaceUIInputMap(slider, JComponent.WHEN_FOCUSED, km); } else if (propertyName == "model") { ((BoundedRangeModel)e.getOldValue()).removeChangeListener( changeListener); ((BoundedRangeModel)e.getNewValue()).addChangeListener( changeListener); calculateThumbLocation(); slider.repaint(); } } } ///////////////////////////////////////////////////////////////////////// /// Model Listener Class ///////////////////////////////////////////////////////////////////////// /** {@collect.stats} * Data model listener. * * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of <Foo>. */ public class ChangeHandler implements ChangeListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void stateChanged(ChangeEvent e) { getHandler().stateChanged(e); } } ///////////////////////////////////////////////////////////////////////// /// Track Listener Class ///////////////////////////////////////////////////////////////////////// /** {@collect.stats} * Track mouse movements. * * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of <Foo>. */ public class TrackListener extends MouseInputAdapter { protected transient int offset; protected transient int currentMouseX, currentMouseY; public void mouseReleased(MouseEvent e) { if (!slider.isEnabled()) { return; } offset = 0; scrollTimer.stop(); // This is the way we have to determine snap-to-ticks. It's // hard to explain but since ChangeEvents don't give us any // idea what has changed we don't have a way to stop the thumb // bounds from being recalculated. Recalculating the thumb // bounds moves the thumb over the current value (i.e., snapping // to the ticks). if (slider.getSnapToTicks() /*|| slider.getSnapToValue()*/ ) { isDragging = false; slider.setValueIsAdjusting(false); } else { slider.setValueIsAdjusting(false); isDragging = false; } slider.repaint(); } /** {@collect.stats} * If the mouse is pressed above the "thumb" component * then reduce the scrollbars value by one page ("page up"), * otherwise increase it by one page. If there is no * thumb then page up if the mouse is in the upper half * of the track. */ public void mousePressed(MouseEvent e) { if (!slider.isEnabled()) { return; } // We should recalculate geometry just before // calculation of the thumb movement direction. // It is important for the case, when JSlider // is a cell editor in JTable. See 6348946. calculateGeometry(); currentMouseX = e.getX(); currentMouseY = e.getY(); if (slider.isRequestFocusEnabled()) { slider.requestFocus(); } // Clicked in the Thumb area? if (thumbRect.contains(currentMouseX, currentMouseY)) { switch (slider.getOrientation()) { case JSlider.VERTICAL: offset = currentMouseY - thumbRect.y; break; case JSlider.HORIZONTAL: offset = currentMouseX - thumbRect.x; break; } isDragging = true; return; } isDragging = false; slider.setValueIsAdjusting(true); Dimension sbSize = slider.getSize(); int direction = POSITIVE_SCROLL; switch (slider.getOrientation()) { case JSlider.VERTICAL: if ( thumbRect.isEmpty() ) { int scrollbarCenter = sbSize.height / 2; if ( !drawInverted() ) { direction = (currentMouseY < scrollbarCenter) ? POSITIVE_SCROLL : NEGATIVE_SCROLL; } else { direction = (currentMouseY < scrollbarCenter) ? NEGATIVE_SCROLL : POSITIVE_SCROLL; } } else { int thumbY = thumbRect.y; if ( !drawInverted() ) { direction = (currentMouseY < thumbY) ? POSITIVE_SCROLL : NEGATIVE_SCROLL; } else { direction = (currentMouseY < thumbY) ? NEGATIVE_SCROLL : POSITIVE_SCROLL; } } break; case JSlider.HORIZONTAL: if ( thumbRect.isEmpty() ) { int scrollbarCenter = sbSize.width / 2; if ( !drawInverted() ) { direction = (currentMouseX < scrollbarCenter) ? NEGATIVE_SCROLL : POSITIVE_SCROLL; } else { direction = (currentMouseX < scrollbarCenter) ? POSITIVE_SCROLL : NEGATIVE_SCROLL; } } else { int thumbX = thumbRect.x; if ( !drawInverted() ) { direction = (currentMouseX < thumbX) ? NEGATIVE_SCROLL : POSITIVE_SCROLL; } else { direction = (currentMouseX < thumbX) ? POSITIVE_SCROLL : NEGATIVE_SCROLL; } } break; } if (shouldScroll(direction)) { scrollDueToClickInTrack(direction); } if (shouldScroll(direction)) { scrollTimer.stop(); scrollListener.setDirection(direction); scrollTimer.start(); } } public boolean shouldScroll(int direction) { Rectangle r = thumbRect; if (slider.getOrientation() == JSlider.VERTICAL) { if (drawInverted() ? direction < 0 : direction > 0) { if (r.y <= currentMouseY) { return false; } } else if (r.y + r.height >= currentMouseY) { return false; } } else { if (drawInverted() ? direction < 0 : direction > 0) { if (r.x + r.width >= currentMouseX) { return false; } } else if (r.x <= currentMouseX) { return false; } } if (direction > 0 && slider.getValue() + slider.getExtent() >= slider.getMaximum()) { return false; } else if (direction < 0 && slider.getValue() <= slider.getMinimum()) { return false; } return true; } /** {@collect.stats} * Set the models value to the position of the top/left * of the thumb relative to the origin of the track. */ public void mouseDragged(MouseEvent e) { int thumbMiddle = 0; if (!slider.isEnabled()) { return; } currentMouseX = e.getX(); currentMouseY = e.getY(); if (!isDragging) { return; } slider.setValueIsAdjusting(true); switch (slider.getOrientation()) { case JSlider.VERTICAL: int halfThumbHeight = thumbRect.height / 2; int thumbTop = e.getY() - offset; int trackTop = trackRect.y; int trackBottom = trackRect.y + (trackRect.height - 1); int vMax = yPositionForValue(slider.getMaximum() - slider.getExtent()); if (drawInverted()) { trackBottom = vMax; } else { trackTop = vMax; } thumbTop = Math.max(thumbTop, trackTop - halfThumbHeight); thumbTop = Math.min(thumbTop, trackBottom - halfThumbHeight); setThumbLocation(thumbRect.x, thumbTop); thumbMiddle = thumbTop + halfThumbHeight; slider.setValue( valueForYPosition( thumbMiddle ) ); break; case JSlider.HORIZONTAL: int halfThumbWidth = thumbRect.width / 2; int thumbLeft = e.getX() - offset; int trackLeft = trackRect.x; int trackRight = trackRect.x + (trackRect.width - 1); int hMax = xPositionForValue(slider.getMaximum() - slider.getExtent()); if (drawInverted()) { trackLeft = hMax; } else { trackRight = hMax; } thumbLeft = Math.max(thumbLeft, trackLeft - halfThumbWidth); thumbLeft = Math.min(thumbLeft, trackRight - halfThumbWidth); setThumbLocation(thumbLeft, thumbRect.y); thumbMiddle = thumbLeft + halfThumbWidth; slider.setValue(valueForXPosition(thumbMiddle)); break; default: return; } } public void mouseMoved(MouseEvent e) { } } /** {@collect.stats} * Scroll-event listener. * * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of <Foo>. */ public class ScrollListener implements ActionListener { // changed this class to public to avoid bogus IllegalAccessException // bug in InternetExplorer browser. It was protected. Work around // for 4109432 int direction = POSITIVE_SCROLL; boolean useBlockIncrement; public ScrollListener() { direction = POSITIVE_SCROLL; useBlockIncrement = true; } public ScrollListener(int dir, boolean block) { direction = dir; useBlockIncrement = block; } public void setDirection(int direction) { this.direction = direction; } public void setScrollByBlock(boolean block) { this.useBlockIncrement = block; } public void actionPerformed(ActionEvent e) { if (useBlockIncrement) { scrollByBlock(direction); } else { scrollByUnit(direction); } if (!trackListener.shouldScroll(direction)) { ((Timer)e.getSource()).stop(); } } } /** {@collect.stats} * Listener for resizing events. * <p> * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of <Foo>. */ public class ComponentHandler extends ComponentAdapter { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void componentResized(ComponentEvent e) { getHandler().componentResized(e); } }; /** {@collect.stats} * Focus-change listener. * <p> * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of <Foo>. */ public class FocusHandler implements FocusListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void focusGained(FocusEvent e) { getHandler().focusGained(e); } public void focusLost(FocusEvent e) { getHandler().focusLost(e); } } /** {@collect.stats} * As of Java 2 platform v1.3 this undocumented class is no longer used. * The recommended approach to creating bindings is to use a * combination of an <code>ActionMap</code>, to contain the action, * and an <code>InputMap</code> to contain the mapping from KeyStroke * to action description. The InputMap is is usually described in the * LookAndFeel tables. * <p> * Please refer to the key bindings specification for further details. * <p> * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of <Foo>. */ public class ActionScroller extends AbstractAction { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Actions. If you need to add // new functionality add it to the Actions, but make sure this // class calls into the Actions. int dir; boolean block; JSlider slider; public ActionScroller( JSlider slider, int dir, boolean block) { this.dir = dir; this.block = block; this.slider = slider; } public void actionPerformed(ActionEvent e) { SHARED_ACTION.scroll(slider, BasicSliderUI.this, dir, block); } public boolean isEnabled() { boolean b = true; if (slider != null) { b = slider.isEnabled(); } return b; } }; /** {@collect.stats} * A static version of the above. */ static class SharedActionScroller extends AbstractAction { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Actions. If you need to add // new functionality add it to the Actions, but make sure this // class calls into the Actions. int dir; boolean block; public SharedActionScroller(int dir, boolean block) { this.dir = dir; this.block = block; } public void actionPerformed(ActionEvent evt) { JSlider slider = (JSlider)evt.getSource(); BasicSliderUI ui = (BasicSliderUI)BasicLookAndFeel.getUIOfType( slider.getUI(), BasicSliderUI.class); if (ui == null) { return; } SHARED_ACTION.scroll(slider, ui, dir, block); } } private static class Actions extends UIAction { public static final String POSITIVE_UNIT_INCREMENT = "positiveUnitIncrement"; public static final String POSITIVE_BLOCK_INCREMENT = "positiveBlockIncrement"; public static final String NEGATIVE_UNIT_INCREMENT = "negativeUnitIncrement"; public static final String NEGATIVE_BLOCK_INCREMENT = "negativeBlockIncrement"; public static final String MIN_SCROLL_INCREMENT = "minScroll"; public static final String MAX_SCROLL_INCREMENT = "maxScroll"; Actions() { super(null); } public Actions(String name) { super(name); } public void actionPerformed(ActionEvent evt) { JSlider slider = (JSlider)evt.getSource(); BasicSliderUI ui = (BasicSliderUI)BasicLookAndFeel.getUIOfType( slider.getUI(), BasicSliderUI.class); String name = getName(); if (ui == null) { return; } if (POSITIVE_UNIT_INCREMENT == name) { scroll(slider, ui, POSITIVE_SCROLL, false); } else if (NEGATIVE_UNIT_INCREMENT == name) { scroll(slider, ui, NEGATIVE_SCROLL, false); } else if (POSITIVE_BLOCK_INCREMENT == name) { scroll(slider, ui, POSITIVE_SCROLL, true); } else if (NEGATIVE_BLOCK_INCREMENT == name) { scroll(slider, ui, NEGATIVE_SCROLL, true); } else if (MIN_SCROLL_INCREMENT == name) { scroll(slider, ui, MIN_SCROLL, false); } else if (MAX_SCROLL_INCREMENT == name) { scroll(slider, ui, MAX_SCROLL, false); } } private void scroll(JSlider slider, BasicSliderUI ui, int direction, boolean isBlock) { boolean invert = slider.getInverted(); if (direction == NEGATIVE_SCROLL || direction == POSITIVE_SCROLL) { if (invert) { direction = (direction == POSITIVE_SCROLL) ? NEGATIVE_SCROLL : POSITIVE_SCROLL; } if (isBlock) { ui.scrollByBlock(direction); } else { ui.scrollByUnit(direction); } } else { // MIN or MAX if (invert) { direction = (direction == MIN_SCROLL) ? MAX_SCROLL : MIN_SCROLL; } slider.setValue((direction == MIN_SCROLL) ? slider.getMinimum() : slider.getMaximum()); } } } }
Java
/* * Copyright (c) 1998, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.swing.*; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.Rectangle; import javax.swing.JToolBar; import javax.swing.plaf.*; import javax.swing.plaf.basic.BasicSeparatorUI; /** {@collect.stats} * A Basic L&F implementation of ToolBarSeparatorUI. This implementation * is a "combined" view/controller. * <p> * * @author Jeff Shapiro */ public class BasicToolBarSeparatorUI extends BasicSeparatorUI { public static ComponentUI createUI( JComponent c ) { return new BasicToolBarSeparatorUI(); } protected void installDefaults( JSeparator s ) { Dimension size = ( (JToolBar.Separator)s ).getSeparatorSize(); if ( size == null || size instanceof UIResource ) { JToolBar.Separator sep = (JToolBar.Separator)s; size = (Dimension)(UIManager.get("ToolBar.separatorSize")); if (size != null) { if (sep.getOrientation() == JSeparator.HORIZONTAL) { size = new Dimension(size.height, size.width); } sep.setSeparatorSize(size); } } } public void paint( Graphics g, JComponent c ) { } public Dimension getPreferredSize( JComponent c ) { Dimension size = ( (JToolBar.Separator)c ).getSeparatorSize(); if ( size != null ) { return size.getSize(); } else { return null; } } }
Java
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import sun.awt.AppContext; import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.plaf.*; import java.io.Serializable; /** {@collect.stats} * CheckboxUI implementation for BasicCheckboxUI * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Jeff Dinkins */ public class BasicCheckBoxUI extends BasicRadioButtonUI { private static final Object BASIC_CHECK_BOX_UI_KEY = new Object(); private final static String propertyPrefix = "CheckBox" + "."; // ******************************** // Create PLAF // ******************************** public static ComponentUI createUI(JComponent b) { AppContext appContext = AppContext.getAppContext(); BasicCheckBoxUI checkboxUI = (BasicCheckBoxUI) appContext.get(BASIC_CHECK_BOX_UI_KEY); if (checkboxUI == null) { checkboxUI = new BasicCheckBoxUI(); appContext.put(BASIC_CHECK_BOX_UI_KEY, checkboxUI); } return checkboxUI; } public String getPropertyPrefix() { return propertyPrefix; } }
Java
/* * Copyright (c) 1998, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.swing.*; import javax.swing.plaf.UIResource; import java.awt.Container; import java.awt.Dimension; /** {@collect.stats} * The default layout manager for Popup menus and menubars. This * class is an extension of BoxLayout which adds the UIResource tag * so that plauggable L&Fs can distinguish it from user-installed * layout managers on menus. * * @author Georges Saab */ public class DefaultMenuLayout extends BoxLayout implements UIResource { public DefaultMenuLayout(Container target, int axis) { super(target, axis); } public Dimension preferredLayoutSize(Container target) { if (target instanceof JPopupMenu) { JPopupMenu popupMenu = (JPopupMenu) target; sun.swing.MenuItemLayoutHelper.clearUsedClientProperties(popupMenu); if (popupMenu.getComponentCount() == 0) { return new Dimension(0, 0); } } // Make BoxLayout recalculate cached preferred sizes super.invalidateLayout(target); return super.preferredLayoutSize(target); } }
Java
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.plaf.*; import javax.swing.border.*; import java.io.Serializable; /** {@collect.stats} * BasicCheckboxMenuItem implementation * * @author Georges Saab * @author David Karlton * @author Arnaud Weber */ public class BasicCheckBoxMenuItemUI extends BasicMenuItemUI { public static ComponentUI createUI(JComponent c) { return new BasicCheckBoxMenuItemUI(); } protected String getPropertyPrefix() { return "CheckBoxMenuItem"; } public void processMouseEvent(JMenuItem item,MouseEvent e,MenuElement path[],MenuSelectionManager manager) { Point p = e.getPoint(); if(p.x >= 0 && p.x < item.getWidth() && p.y >= 0 && p.y < item.getHeight()) { if(e.getID() == MouseEvent.MOUSE_RELEASED) { manager.clearSelectedPath(); item.doClick(0); } else manager.setSelectedPath(path); } else if(item.getModel().isArmed()) { MenuElement newPath[] = new MenuElement[path.length-1]; int i,c; for(i=0,c=path.length-1;i<c;i++) newPath[i] = path[i]; manager.setSelectedPath(newPath); } } }
Java
/* * Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.plaf.*; import java.awt.*; import java.awt.event.*; /** {@collect.stats} * BasicPanel implementation * * @author Steve Wilson */ public class BasicPanelUI extends PanelUI { // Shared UI object private static PanelUI panelUI; public static ComponentUI createUI(JComponent c) { if(panelUI == null) { panelUI = new BasicPanelUI(); } return panelUI; } public void installUI(JComponent c) { JPanel p = (JPanel)c; super.installUI(p); installDefaults(p); } public void uninstallUI(JComponent c) { JPanel p = (JPanel)c; uninstallDefaults(p); super.uninstallUI(c); } protected void installDefaults(JPanel p) { LookAndFeel.installColorsAndFont(p, "Panel.background", "Panel.foreground", "Panel.font"); LookAndFeel.installBorder(p,"Panel.border"); LookAndFeel.installProperty(p, "opaque", Boolean.TRUE); } protected void uninstallDefaults(JPanel p) { LookAndFeel.uninstallBorder(p); } /** {@collect.stats} * Returns the baseline. * * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public int getBaseline(JComponent c, int width, int height) { super.getBaseline(c, width, height); Border border = c.getBorder(); if (border instanceof AbstractBorder) { return ((AbstractBorder)border).getBaseline(c, width, height); } return -1; } /** {@collect.stats} * Returns an enum indicating how the baseline of the component * changes as the size changes. * * @throws NullPointerException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public Component.BaselineResizeBehavior getBaselineResizeBehavior( JComponent c) { super.getBaselineResizeBehavior(c); Border border = c.getBorder(); if (border instanceof AbstractBorder) { return ((AbstractBorder)border).getBaselineResizeBehavior(c); } return Component.BaselineResizeBehavior.OTHER; } }
Java
/* * Copyright (c) 2002, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.lang.reflect.*; import javax.swing.*; import javax.swing.plaf.*; /** {@collect.stats} * An ActionMap that populates its contents as necessary. The * contents are populated by invoking the <code>loadActionMap</code> * method on the passed in Object. * * @author Scott Violet */ class LazyActionMap extends ActionMapUIResource { /** {@collect.stats} * Object to invoke <code>loadActionMap</code> on. This may be * a Class object. */ private transient Object _loader; /** {@collect.stats} * Installs an ActionMap that will be populated by invoking the * <code>loadActionMap</code> method on the specified Class * when necessary. * <p> * This should be used if the ActionMap can be shared. * * @param c JComponent to install the ActionMap on. * @param loaderClass Class object that gets loadActionMap invoked * on. * @param defaultsKey Key to use to defaults table to check for * existing map and what resulting Map will be registered on. */ static void installLazyActionMap(JComponent c, Class loaderClass, String defaultsKey) { ActionMap map = (ActionMap)UIManager.get(defaultsKey); if (map == null) { map = new LazyActionMap(loaderClass); UIManager.getLookAndFeelDefaults().put(defaultsKey, map); } SwingUtilities.replaceUIActionMap(c, map); } /** {@collect.stats} * Returns an ActionMap that will be populated by invoking the * <code>loadActionMap</code> method on the specified Class * when necessary. * <p> * This should be used if the ActionMap can be shared. * * @param c JComponent to install the ActionMap on. * @param loaderClass Class object that gets loadActionMap invoked * on. * @param defaultsKey Key to use to defaults table to check for * existing map and what resulting Map will be registered on. */ static ActionMap getActionMap(Class loaderClass, String defaultsKey) { ActionMap map = (ActionMap)UIManager.get(defaultsKey); if (map == null) { map = new LazyActionMap(loaderClass); UIManager.getLookAndFeelDefaults().put(defaultsKey, map); } return map; } private LazyActionMap(Class loader) { _loader = loader; } public void put(Action action) { put(action.getValue(Action.NAME), action); } public void put(Object key, Action action) { loadIfNecessary(); super.put(key, action); } public Action get(Object key) { loadIfNecessary(); return super.get(key); } public void remove(Object key) { loadIfNecessary(); super.remove(key); } public void clear() { loadIfNecessary(); super.clear(); } public Object[] keys() { loadIfNecessary(); return super.keys(); } public int size() { loadIfNecessary(); return super.size(); } public Object[] allKeys() { loadIfNecessary(); return super.allKeys(); } public void setParent(ActionMap map) { loadIfNecessary(); super.setParent(map); } private void loadIfNecessary() { if (_loader != null) { Object loader = _loader; _loader = null; Class klass = (Class)loader; try { Method method = klass.getDeclaredMethod("loadActionMap", new Class[] { LazyActionMap.class }); method.invoke(klass, new Object[] { this }); } catch (NoSuchMethodException nsme) { assert false : "LazyActionMap unable to load actions " + klass; } catch (IllegalAccessException iae) { assert false : "LazyActionMap unable to load actions " + iae; } catch (InvocationTargetException ite) { assert false : "LazyActionMap unable to load actions " + ite; } catch (IllegalArgumentException iae) { assert false : "LazyActionMap unable to load actions " + iae; } } } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.swing.*; import javax.swing.border.Border; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; import java.awt.*; import java.awt.event.*; import java.lang.reflect.Method; /** {@collect.stats} * The default editor for editable combo boxes. The editor is implemented as a JTextField. * * @author Arnaud Weber * @author Mark Davidson */ public class BasicComboBoxEditor implements ComboBoxEditor,FocusListener { protected JTextField editor; private Object oldValue; public BasicComboBoxEditor() { editor = createEditorComponent(); } public Component getEditorComponent() { return editor; } /** {@collect.stats} * Creates the internal editor component. Override this to provide * a custom implementation. * * @return a new editor component * @since 1.6 */ protected JTextField createEditorComponent() { JTextField editor = new BorderlessTextField("",9); editor.setBorder(null); return editor; } /** {@collect.stats} * Sets the item that should be edited. * * @param anObject the displayed value of the editor */ public void setItem(Object anObject) { if ( anObject != null ) { editor.setText(anObject.toString()); oldValue = anObject; } else { editor.setText(""); } } public Object getItem() { Object newValue = editor.getText(); if (oldValue != null && !(oldValue instanceof String)) { // The original value is not a string. Should return the value in it's // original type. if (newValue.equals(oldValue.toString())) { return oldValue; } else { // Must take the value from the editor and get the value and cast it to the new type. Class cls = oldValue.getClass(); try { Method method = cls.getMethod("valueOf", new Class[]{String.class}); newValue = method.invoke(oldValue, new Object[] { editor.getText()}); } catch (Exception ex) { // Fail silently and return the newValue (a String object) } } } return newValue; } public void selectAll() { editor.selectAll(); editor.requestFocus(); } // This used to do something but now it doesn't. It couldn't be // removed because it would be an API change to do so. public void focusGained(FocusEvent e) {} // This used to do something but now it doesn't. It couldn't be // removed because it would be an API change to do so. public void focusLost(FocusEvent e) {} public void addActionListener(ActionListener l) { editor.addActionListener(l); } public void removeActionListener(ActionListener l) { editor.removeActionListener(l); } static class BorderlessTextField extends JTextField { public BorderlessTextField(String value,int n) { super(value,n); } // workaround for 4530952 public void setText(String s) { if (getText().equals(s)) { return; } super.setText(s); } public void setBorder(Border b) { if (!(b instanceof UIResource)) { super.setBorder(b); } } } /** {@collect.stats} * A subclass of BasicComboBoxEditor that implements UIResource. * BasicComboBoxEditor doesn't implement UIResource * directly so that applications can safely override the * cellRenderer property with BasicListCellRenderer subclasses. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. */ public static class UIResource extends BasicComboBoxEditor implements javax.swing.plaf.UIResource { } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.util.*; import java.awt.*; import java.awt.event.*; import java.awt.datatransfer.*; import java.awt.im.InputContext; import java.beans.*; import java.io.*; import javax.swing.*; import javax.swing.plaf.*; import javax.swing.text.*; import javax.swing.event.*; import javax.swing.border.Border; import javax.swing.plaf.UIResource; import sun.swing.DefaultLookup; import sun.awt.AppContext; import javax.swing.plaf.basic.DragRecognitionSupport.BeforeDrag; /** {@collect.stats} * <p> * Basis of a text components look-and-feel. This provides the * basic editor view and controller services that may be useful * when creating a look-and-feel for an extension of * <code>JTextComponent</code>. * <p> * Most state is held in the associated <code>JTextComponent</code> * as bound properties, and the UI installs default values for the * various properties. This default will install something for * all of the properties. Typically, a LAF implementation will * do more however. At a minimum, a LAF would generally install * key bindings. * <p> * This class also provides some concurrency support if the * <code>Document</code> associated with the JTextComponent is a subclass of * <code>AbstractDocument</code>. Access to the View (or View hierarchy) is * serialized between any thread mutating the model and the Swing * event thread (which is expected to render, do model/view coordinate * translation, etc). <em>Any access to the root view should first * acquire a read-lock on the AbstractDocument and release that lock * in a finally block.</em> * <p> * An important method to define is the {@link #getPropertyPrefix} method * which is used as the basis of the keys used to fetch defaults * from the UIManager. The string should reflect the type of * TextUI (eg. TextField, TextArea, etc) without the particular * LAF part of the name (eg Metal, Motif, etc). * <p> * To build a view of the model, one of the following strategies * can be employed. * <ol> * <li> * One strategy is to simply redefine the * ViewFactory interface in the UI. By default, this UI itself acts * as the factory for View implementations. This is useful * for simple factories. To do this reimplement the * {@link #create} method. * <li> * A common strategy for creating more complex types of documents * is to have the EditorKit implementation return a factory. Since * the EditorKit ties all of the pieces necessary to maintain a type * of document, the factory is typically an important part of that * and should be produced by the EditorKit implementation. * </ol> * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Timothy Prinzing * @author Shannon Hickey (drag and drop) */ public abstract class BasicTextUI extends TextUI implements ViewFactory { /** {@collect.stats} * Creates a new UI. */ public BasicTextUI() { painted = false; } /** {@collect.stats} * Creates the object to use for a caret. By default an * instance of BasicCaret is created. This method * can be redefined to provide something else that implements * the InputPosition interface or a subclass of JCaret. * * @return the caret object */ protected Caret createCaret() { return new BasicCaret(); } /** {@collect.stats} * Creates the object to use for adding highlights. By default * an instance of BasicHighlighter is created. This method * can be redefined to provide something else that implements * the Highlighter interface or a subclass of DefaultHighlighter. * * @return the highlighter */ protected Highlighter createHighlighter() { return new BasicHighlighter(); } /** {@collect.stats} * Fetches the name of the keymap that will be installed/used * by default for this UI. This is implemented to create a * name based upon the classname. The name is the the name * of the class with the package prefix removed. * * @return the name */ protected String getKeymapName() { String nm = getClass().getName(); int index = nm.lastIndexOf('.'); if (index >= 0) { nm = nm.substring(index+1, nm.length()); } return nm; } /** {@collect.stats} * Creates the keymap to use for the text component, and installs * any necessary bindings into it. By default, the keymap is * shared between all instances of this type of TextUI. The * keymap has the name defined by the getKeymapName method. If the * keymap is not found, then DEFAULT_KEYMAP from JTextComponent is used. * <p> * The set of bindings used to create the keymap is fetched * from the UIManager using a key formed by combining the * {@link #getPropertyPrefix} method * and the string <code>.keyBindings</code>. The type is expected * to be <code>JTextComponent.KeyBinding[]</code>. * * @return the keymap * @see #getKeymapName * @see javax.swing.text.JTextComponent */ protected Keymap createKeymap() { String nm = getKeymapName(); Keymap map = JTextComponent.getKeymap(nm); if (map == null) { Keymap parent = JTextComponent.getKeymap(JTextComponent.DEFAULT_KEYMAP); map = JTextComponent.addKeymap(nm, parent); String prefix = getPropertyPrefix(); Object o = DefaultLookup.get(editor, this, prefix + ".keyBindings"); if ((o != null) && (o instanceof JTextComponent.KeyBinding[])) { JTextComponent.KeyBinding[] bindings = (JTextComponent.KeyBinding[]) o; JTextComponent.loadKeymap(map, bindings, getComponent().getActions()); } } return map; } /** {@collect.stats} * This method gets called when a bound property is changed * on the associated JTextComponent. This is a hook * which UI implementations may change to reflect how the * UI displays bound properties of JTextComponent subclasses. * This is implemented to do nothing (i.e. the response to * properties in JTextComponent itself are handled prior * to calling this method). * * This implementation updates the background of the text * component if the editable and/or enabled state changes. * * @param evt the property change event */ protected void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("editable") || evt.getPropertyName().equals("enabled")) { updateBackground((JTextComponent)evt.getSource()); } } /** {@collect.stats} * Updates the background of the text component based on whether the * text component is editable and/or enabled. * * @param c the JTextComponent that needs its background color updated */ private void updateBackground(JTextComponent c) { // This is a temporary workaround. // This code does not correctly deal with Synth (Synth doesn't use // properties like this), nor does it deal with the situation where // the developer grabs the color from a JLabel and sets it as // the background for a JTextArea in all look and feels. The problem // scenario results if the Color obtained for the Label and TextArea // is ==, which is the case for the windows look and feel. // Until an appropriate solution is found, the code is being // reverted to what it was before the original fix. if (this instanceof sun.swing.plaf.synth.SynthUI || (c instanceof JTextArea)) { return; } Color background = c.getBackground(); if (background instanceof UIResource) { String prefix = getPropertyPrefix(); Color disabledBG = DefaultLookup.getColor(c, this, prefix + ".disabledBackground", null); Color inactiveBG = DefaultLookup.getColor(c, this, prefix + ".inactiveBackground", null); Color bg = DefaultLookup.getColor(c, this, prefix + ".background", null); /* In an ideal situation, the following check would not be necessary * and we would replace the color any time the previous color was a * UIResouce. However, it turns out that there is existing code that * uses the following inadvisable pattern to turn a text area into * what appears to be a multi-line label: * * JLabel label = new JLabel(); * JTextArea area = new JTextArea(); * area.setBackground(label.getBackground()); * area.setEditable(false); * * JLabel's default background is a UIResource. As such, just * checking for UIResource would have us always changing the * background away from what the developer wanted. * * Therefore, for JTextArea/JEditorPane, we'll additionally check * that the color we're about to replace matches one that was * installed by us from the UIDefaults. */ if ((c instanceof JTextArea || c instanceof JEditorPane) && background != disabledBG && background != inactiveBG && background != bg) { return; } Color newColor = null; if (!c.isEnabled()) { newColor = disabledBG; } if (newColor == null && !c.isEditable()) { newColor = inactiveBG; } if (newColor == null) { newColor = bg; } if (newColor != null && newColor != background) { c.setBackground(newColor); } } } /** {@collect.stats} * Gets the name used as a key to look up properties through the * UIManager. This is used as a prefix to all the standard * text properties. * * @return the name */ protected abstract String getPropertyPrefix(); /** {@collect.stats} * Initializes component properties, e.g. font, foreground, * background, caret color, selection color, selected text color, * disabled text color, and border color. The font, foreground, and * background properties are only set if their current value is either null * or a UIResource, other properties are set if the current * value is null. * * @see #uninstallDefaults * @see #installUI */ protected void installDefaults() { String prefix = getPropertyPrefix(); Font f = editor.getFont(); if ((f == null) || (f instanceof UIResource)) { editor.setFont(UIManager.getFont(prefix + ".font")); } Color bg = editor.getBackground(); if ((bg == null) || (bg instanceof UIResource)) { editor.setBackground(UIManager.getColor(prefix + ".background")); } Color fg = editor.getForeground(); if ((fg == null) || (fg instanceof UIResource)) { editor.setForeground(UIManager.getColor(prefix + ".foreground")); } Color color = editor.getCaretColor(); if ((color == null) || (color instanceof UIResource)) { editor.setCaretColor(UIManager.getColor(prefix + ".caretForeground")); } Color s = editor.getSelectionColor(); if ((s == null) || (s instanceof UIResource)) { editor.setSelectionColor(UIManager.getColor(prefix + ".selectionBackground")); } Color sfg = editor.getSelectedTextColor(); if ((sfg == null) || (sfg instanceof UIResource)) { editor.setSelectedTextColor(UIManager.getColor(prefix + ".selectionForeground")); } Color dfg = editor.getDisabledTextColor(); if ((dfg == null) || (dfg instanceof UIResource)) { editor.setDisabledTextColor(UIManager.getColor(prefix + ".inactiveForeground")); } Border b = editor.getBorder(); if ((b == null) || (b instanceof UIResource)) { editor.setBorder(UIManager.getBorder(prefix + ".border")); } Insets margin = editor.getMargin(); if (margin == null || margin instanceof UIResource) { editor.setMargin(UIManager.getInsets(prefix + ".margin")); } updateCursor(); } private void installDefaults2() { editor.addMouseListener(dragListener); editor.addMouseMotionListener(dragListener); String prefix = getPropertyPrefix(); Caret caret = editor.getCaret(); if (caret == null || caret instanceof UIResource) { caret = createCaret(); editor.setCaret(caret); int rate = DefaultLookup.getInt(getComponent(), this, prefix + ".caretBlinkRate", 500); caret.setBlinkRate(rate); } Highlighter highlighter = editor.getHighlighter(); if (highlighter == null || highlighter instanceof UIResource) { editor.setHighlighter(createHighlighter()); } TransferHandler th = editor.getTransferHandler(); if (th == null || th instanceof UIResource) { editor.setTransferHandler(getTransferHandler()); } } /** {@collect.stats} * Sets the component properties that haven't been explicitly overridden to * null. A property is considered overridden if its current value * is not a UIResource. * * @see #installDefaults * @see #uninstallUI */ protected void uninstallDefaults() { editor.removeMouseListener(dragListener); editor.removeMouseMotionListener(dragListener); if (editor.getCaretColor() instanceof UIResource) { editor.setCaretColor(null); } if (editor.getSelectionColor() instanceof UIResource) { editor.setSelectionColor(null); } if (editor.getDisabledTextColor() instanceof UIResource) { editor.setDisabledTextColor(null); } if (editor.getSelectedTextColor() instanceof UIResource) { editor.setSelectedTextColor(null); } if (editor.getBorder() instanceof UIResource) { editor.setBorder(null); } if (editor.getMargin() instanceof UIResource) { editor.setMargin(null); } if (editor.getCaret() instanceof UIResource) { editor.setCaret(null); } if (editor.getHighlighter() instanceof UIResource) { editor.setHighlighter(null); } if (editor.getTransferHandler() instanceof UIResource) { editor.setTransferHandler(null); } if (editor.getCursor() instanceof UIResource) { editor.setCursor(null); } } /** {@collect.stats} * Installs listeners for the UI. */ protected void installListeners() { } /** {@collect.stats} * Uninstalls listeners for the UI. */ protected void uninstallListeners() { } protected void installKeyboardActions() { // backward compatibility support... keymaps for the UI // are now installed in the more friendly input map. editor.setKeymap(createKeymap()); InputMap km = getInputMap(); if (km != null) { SwingUtilities.replaceUIInputMap(editor, JComponent.WHEN_FOCUSED, km); } ActionMap map = getActionMap(); if (map != null) { SwingUtilities.replaceUIActionMap(editor, map); } updateFocusAcceleratorBinding(false); } /** {@collect.stats} * Get the InputMap to use for the UI. */ InputMap getInputMap() { InputMap map = new InputMapUIResource(); InputMap shared = (InputMap)DefaultLookup.get(editor, this, getPropertyPrefix() + ".focusInputMap"); if (shared != null) { map.setParent(shared); } return map; } /** {@collect.stats} * Invoked when the focus accelerator changes, this will update the * key bindings as necessary. */ void updateFocusAcceleratorBinding(boolean changed) { char accelerator = editor.getFocusAccelerator(); if (changed || accelerator != '\0') { InputMap km = SwingUtilities.getUIInputMap (editor, JComponent.WHEN_IN_FOCUSED_WINDOW); if (km == null && accelerator != '\0') { km = new ComponentInputMapUIResource(editor); SwingUtilities.replaceUIInputMap(editor, JComponent. WHEN_IN_FOCUSED_WINDOW, km); ActionMap am = getActionMap(); SwingUtilities.replaceUIActionMap(editor, am); } if (km != null) { km.clear(); if (accelerator != '\0') { km.put(KeyStroke.getKeyStroke(accelerator, ActionEvent.ALT_MASK), "requestFocus"); } } } } /** {@collect.stats} * Invoked when editable property is changed. * * removing 'TAB' and 'SHIFT-TAB' from traversalKeysSet in case * editor is editable * adding 'TAB' and 'SHIFT-TAB' to traversalKeysSet in case * editor is non editable */ void updateFocusTraversalKeys() { /* * Fix for 4514331 Non-editable JTextArea and similar * should allow Tab to keyboard - accessibility */ EditorKit editorKit = getEditorKit(editor); if ( editorKit != null && editorKit instanceof DefaultEditorKit) { Set storedForwardTraversalKeys = editor. getFocusTraversalKeys(KeyboardFocusManager. FORWARD_TRAVERSAL_KEYS); Set storedBackwardTraversalKeys = editor. getFocusTraversalKeys(KeyboardFocusManager. BACKWARD_TRAVERSAL_KEYS); Set forwardTraversalKeys = new HashSet(storedForwardTraversalKeys); Set backwardTraversalKeys = new HashSet(storedBackwardTraversalKeys); if (editor.isEditable()) { forwardTraversalKeys. remove(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)); backwardTraversalKeys. remove(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK)); } else { forwardTraversalKeys.add(KeyStroke. getKeyStroke(KeyEvent.VK_TAB, 0)); backwardTraversalKeys. add(KeyStroke. getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK)); } LookAndFeel.installProperty(editor, "focusTraversalKeysForward", forwardTraversalKeys); LookAndFeel.installProperty(editor, "focusTraversalKeysBackward", backwardTraversalKeys); } } /** {@collect.stats} * As needed updates cursor for the target editor. */ private void updateCursor() { if ((! editor.isCursorSet()) || editor.getCursor() instanceof UIResource) { Cursor cursor = (editor.isEditable()) ? textCursor : null; editor.setCursor(cursor); } } /** {@collect.stats} * Returns the <code>TransferHandler</code> that will be installed if * their isn't one installed on the <code>JTextComponent</code>. */ TransferHandler getTransferHandler() { return defaultTransferHandler; } /** {@collect.stats} * Fetch an action map to use. */ ActionMap getActionMap() { String mapName = getPropertyPrefix() + ".actionMap"; ActionMap map = (ActionMap)UIManager.get(mapName); if (map == null) { map = createActionMap(); if (map != null) { UIManager.getLookAndFeelDefaults().put(mapName, map); } } ActionMap componentMap = new ActionMapUIResource(); componentMap.put("requestFocus", new FocusAction()); /* * fix for bug 4515750 * JTextField & non-editable JTextArea bind return key - default btn not accessible * * Wrap the return action so that it is only enabled when the * component is editable. This allows the default button to be * processed when the text component has focus and isn't editable. * */ if (getEditorKit(editor) instanceof DefaultEditorKit) { if (map != null) { Object obj = map.get(DefaultEditorKit.insertBreakAction); if (obj != null && obj instanceof DefaultEditorKit.InsertBreakAction) { Action action = new TextActionWrapper((TextAction)obj); componentMap.put(action.getValue(Action.NAME),action); } } } if (map != null) { componentMap.setParent(map); } return componentMap; } /** {@collect.stats} * Create a default action map. This is basically the * set of actions found exported by the component. */ ActionMap createActionMap() { ActionMap map = new ActionMapUIResource(); Action[] actions = editor.getActions(); //System.out.println("building map for UI: " + getPropertyPrefix()); int n = actions.length; for (int i = 0; i < n; i++) { Action a = actions[i]; map.put(a.getValue(Action.NAME), a); //System.out.println(" " + a.getValue(Action.NAME)); } map.put(TransferHandler.getCutAction().getValue(Action.NAME), TransferHandler.getCutAction()); map.put(TransferHandler.getCopyAction().getValue(Action.NAME), TransferHandler.getCopyAction()); map.put(TransferHandler.getPasteAction().getValue(Action.NAME), TransferHandler.getPasteAction()); return map; } protected void uninstallKeyboardActions() { editor.setKeymap(null); SwingUtilities.replaceUIInputMap(editor, JComponent. WHEN_IN_FOCUSED_WINDOW, null); SwingUtilities.replaceUIActionMap(editor, null); } /** {@collect.stats} * Paints a background for the view. This will only be * called if isOpaque() on the associated component is * true. The default is to paint the background color * of the component. * * @param g the graphics context */ protected void paintBackground(Graphics g) { g.setColor(editor.getBackground()); g.fillRect(0, 0, editor.getWidth(), editor.getHeight()); } /** {@collect.stats} * Fetches the text component associated with this * UI implementation. This will be null until * the ui has been installed. * * @return the editor component */ protected final JTextComponent getComponent() { return editor; } /** {@collect.stats} * Flags model changes. * This is called whenever the model has changed. * It is implemented to rebuild the view hierarchy * to represent the default root element of the * associated model. */ protected void modelChanged() { // create a view hierarchy ViewFactory f = rootView.getViewFactory(); Document doc = editor.getDocument(); Element elem = doc.getDefaultRootElement(); setView(f.create(elem)); } /** {@collect.stats} * Sets the current root of the view hierarchy and calls invalidate(). * If there were any child components, they will be removed (i.e. * there are assumed to have come from components embedded in views). * * @param v the root view */ protected final void setView(View v) { rootView.setView(v); painted = false; editor.revalidate(); editor.repaint(); } /** {@collect.stats} * Paints the interface safely with a guarantee that * the model won't change from the view of this thread. * This does the following things, rendering from * back to front. * <ol> * <li> * If the component is marked as opaque, the background * is painted in the current background color of the * component. * <li> * The highlights (if any) are painted. * <li> * The view hierarchy is painted. * <li> * The caret is painted. * </ol> * * @param g the graphics context */ protected void paintSafely(Graphics g) { painted = true; Highlighter highlighter = editor.getHighlighter(); Caret caret = editor.getCaret(); // paint the background if (editor.isOpaque()) { paintBackground(g); } // paint the highlights if (highlighter != null) { highlighter.paint(g); } // paint the view hierarchy Rectangle alloc = getVisibleEditorRect(); if (alloc != null) { rootView.paint(g, alloc); } // paint the caret if (caret != null) { caret.paint(g); } if (dropCaret != null) { dropCaret.paint(g); } } // --- ComponentUI methods -------------------------------------------- /** {@collect.stats} * Installs the UI for a component. This does the following * things. * <ol> * <li> * Set the associated component to opaque (can be changed * easily by a subclass or on JTextComponent directly), * which is the most common case. This will cause the * component's background color to be painted. * <li> * Install the default caret and highlighter into the * associated component. * <li> * Attach to the editor and model. If there is no * model, a default one is created. * <li> * create the view factory and the view hierarchy used * to represent the model. * </ol> * * @param c the editor component * @see ComponentUI#installUI */ public void installUI(JComponent c) { if (c instanceof JTextComponent) { editor = (JTextComponent) c; // install defaults installDefaults(); installDefaults2(); // This is a workaround as these should not override what synth has // set them to if (!(this instanceof sun.swing.plaf.synth.SynthUI)){ // common case is background painted... this can // easily be changed by subclasses or from outside // of the component. LookAndFeel.installProperty(editor, "opaque", Boolean.TRUE); LookAndFeel.installProperty(editor, "autoscrolls", Boolean.TRUE); } // attach to the model and editor editor.addPropertyChangeListener(updateHandler); Document doc = editor.getDocument(); if (doc == null) { // no model, create a default one. This will // fire a notification to the updateHandler // which takes care of the rest. editor.setDocument(getEditorKit(editor).createDefaultDocument()); } else { doc.addDocumentListener(updateHandler); modelChanged(); } // install keymap installListeners(); installKeyboardActions(); LayoutManager oldLayout = editor.getLayout(); if ((oldLayout == null) || (oldLayout instanceof UIResource)) { // by default, use default LayoutManger implementation that // will position the components associated with a View object. editor.setLayout(updateHandler); } updateBackground(editor); } else { throw new Error("TextUI needs JTextComponent"); } } /** {@collect.stats} * Deinstalls the UI for a component. This removes the listeners, * uninstalls the highlighter, removes views, and nulls out the keymap. * * @param c the editor component * @see ComponentUI#uninstallUI */ public void uninstallUI(JComponent c) { // detach from the model editor.removePropertyChangeListener(updateHandler); editor.getDocument().removeDocumentListener(updateHandler); // view part painted = false; uninstallDefaults(); rootView.setView(null); c.removeAll(); LayoutManager lm = c.getLayout(); if (lm instanceof UIResource) { c.setLayout(null); } // controller part uninstallKeyboardActions(); uninstallListeners(); editor = null; } /** {@collect.stats} * Superclass paints background in an uncontrollable way * (i.e. one might want an image tiled into the background). * To prevent this from happening twice, this method is * reimplemented to simply paint. * <p> * <em>NOTE:</em> Superclass is also not thread-safe in * it's rendering of the background, although that's not * an issue with the default rendering. */ public void update(Graphics g, JComponent c) { paint(g, c); } /** {@collect.stats} * Paints the interface. This is routed to the * paintSafely method under the guarantee that * the model won't change from the view of this thread * while it's rendering (if the associated model is * derived from AbstractDocument). This enables the * model to potentially be updated asynchronously. * * @param g the graphics context * @param c the editor component */ public final void paint(Graphics g, JComponent c) { if ((rootView.getViewCount() > 0) && (rootView.getView(0) != null)) { Document doc = editor.getDocument(); if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readLock(); } try { paintSafely(g); } finally { if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readUnlock(); } } } } /** {@collect.stats} * Gets the preferred size for the editor component. If the component * has been given a size prior to receiving this request, it will * set the size of the view hierarchy to reflect the size of the component * before requesting the preferred size of the view hierarchy. This * allows formatted views to format to the current component size before * answering the request. Other views don't care about currently formatted * size and give the same answer either way. * * @param c the editor component * @return the size */ public Dimension getPreferredSize(JComponent c) { Document doc = editor.getDocument(); Insets i = c.getInsets(); Dimension d = c.getSize(); if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readLock(); } try { if ((d.width > (i.left + i.right)) && (d.height > (i.top + i.bottom))) { rootView.setSize(d.width - i.left - i.right, d.height - i.top - i.bottom); } else if (d.width == 0 && d.height == 0) { // Probably haven't been layed out yet, force some sort of // initial sizing. rootView.setSize(Integer.MAX_VALUE, Integer.MAX_VALUE); } d.width = (int) Math.min((long) rootView.getPreferredSpan(View.X_AXIS) + (long) i.left + (long) i.right, Integer.MAX_VALUE); d.height = (int) Math.min((long) rootView.getPreferredSpan(View.Y_AXIS) + (long) i.top + (long) i.bottom, Integer.MAX_VALUE); } finally { if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readUnlock(); } } return d; } /** {@collect.stats} * Gets the minimum size for the editor component. * * @param c the editor component * @return the size */ public Dimension getMinimumSize(JComponent c) { Document doc = editor.getDocument(); Insets i = c.getInsets(); Dimension d = new Dimension(); if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readLock(); } try { d.width = (int) rootView.getMinimumSpan(View.X_AXIS) + i.left + i.right; d.height = (int) rootView.getMinimumSpan(View.Y_AXIS) + i.top + i.bottom; } finally { if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readUnlock(); } } return d; } /** {@collect.stats} * Gets the maximum size for the editor component. * * @param c the editor component * @return the size */ public Dimension getMaximumSize(JComponent c) { Document doc = editor.getDocument(); Insets i = c.getInsets(); Dimension d = new Dimension(); if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readLock(); } try { d.width = (int) Math.min((long) rootView.getMaximumSpan(View.X_AXIS) + (long) i.left + (long) i.right, Integer.MAX_VALUE); d.height = (int) Math.min((long) rootView.getMaximumSpan(View.Y_AXIS) + (long) i.top + (long) i.bottom, Integer.MAX_VALUE); } finally { if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readUnlock(); } } return d; } // ---- TextUI methods ------------------------------------------- /** {@collect.stats} * Gets the allocation to give the root View. Due * to an unfortunate set of historical events this * method is inappropriately named. The Rectangle * returned has nothing to do with visibility. * The component must have a non-zero positive size for * this translation to be computed. * * @return the bounding box for the root view */ protected Rectangle getVisibleEditorRect() { Rectangle alloc = editor.getBounds(); if ((alloc.width > 0) && (alloc.height > 0)) { alloc.x = alloc.y = 0; Insets insets = editor.getInsets(); alloc.x += insets.left; alloc.y += insets.top; alloc.width -= insets.left + insets.right; alloc.height -= insets.top + insets.bottom; return alloc; } return null; } /** {@collect.stats} * Converts the given location in the model to a place in * the view coordinate system. * The component must have a non-zero positive size for * this translation to be computed. * * @param tc the text component for which this UI is installed * @param pos the local location in the model to translate >= 0 * @return the coordinates as a rectangle, null if the model is not painted * @exception BadLocationException if the given position does not * represent a valid location in the associated document * @see TextUI#modelToView */ public Rectangle modelToView(JTextComponent tc, int pos) throws BadLocationException { return modelToView(tc, pos, Position.Bias.Forward); } /** {@collect.stats} * Converts the given location in the model to a place in * the view coordinate system. * The component must have a non-zero positive size for * this translation to be computed. * * @param tc the text component for which this UI is installed * @param pos the local location in the model to translate >= 0 * @return the coordinates as a rectangle, null if the model is not painted * @exception BadLocationException if the given position does not * represent a valid location in the associated document * @see TextUI#modelToView */ public Rectangle modelToView(JTextComponent tc, int pos, Position.Bias bias) throws BadLocationException { Document doc = editor.getDocument(); if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readLock(); } try { Rectangle alloc = getVisibleEditorRect(); if (alloc != null) { rootView.setSize(alloc.width, alloc.height); Shape s = rootView.modelToView(pos, alloc, bias); if (s != null) { return s.getBounds(); } } } finally { if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readUnlock(); } } return null; } /** {@collect.stats} * Converts the given place in the view coordinate system * to the nearest representative location in the model. * The component must have a non-zero positive size for * this translation to be computed. * * @param tc the text component for which this UI is installed * @param pt the location in the view to translate. This * should be in the same coordinate system as the mouse events. * @return the offset from the start of the document >= 0, * -1 if not painted * @see TextUI#viewToModel */ public int viewToModel(JTextComponent tc, Point pt) { return viewToModel(tc, pt, discardBias); } /** {@collect.stats} * Converts the given place in the view coordinate system * to the nearest representative location in the model. * The component must have a non-zero positive size for * this translation to be computed. * * @param tc the text component for which this UI is installed * @param pt the location in the view to translate. This * should be in the same coordinate system as the mouse events. * @return the offset from the start of the document >= 0, * -1 if the component doesn't yet have a positive size. * @see TextUI#viewToModel */ public int viewToModel(JTextComponent tc, Point pt, Position.Bias[] biasReturn) { int offs = -1; Document doc = editor.getDocument(); if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readLock(); } try { Rectangle alloc = getVisibleEditorRect(); if (alloc != null) { rootView.setSize(alloc.width, alloc.height); offs = rootView.viewToModel(pt.x, pt.y, alloc, biasReturn); } } finally { if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readUnlock(); } } return offs; } /** {@collect.stats} * {@inheritDoc} */ public int getNextVisualPositionFrom(JTextComponent t, int pos, Position.Bias b, int direction, Position.Bias[] biasRet) throws BadLocationException{ Document doc = editor.getDocument(); if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readLock(); } try { if (painted) { Rectangle alloc = getVisibleEditorRect(); if (alloc != null) { rootView.setSize(alloc.width, alloc.height); } return rootView.getNextVisualPositionFrom(pos, b, alloc, direction, biasRet); } } finally { if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readUnlock(); } } return -1; } /** {@collect.stats} * Causes the portion of the view responsible for the * given part of the model to be repainted. Does nothing if * the view is not currently painted. * * @param tc the text component for which this UI is installed * @param p0 the beginning of the range >= 0 * @param p1 the end of the range >= p0 * @see TextUI#damageRange */ public void damageRange(JTextComponent tc, int p0, int p1) { damageRange(tc, p0, p1, Position.Bias.Forward, Position.Bias.Backward); } /** {@collect.stats} * Causes the portion of the view responsible for the * given part of the model to be repainted. * * @param p0 the beginning of the range >= 0 * @param p1 the end of the range >= p0 */ public void damageRange(JTextComponent t, int p0, int p1, Position.Bias p0Bias, Position.Bias p1Bias) { if (painted) { Rectangle alloc = getVisibleEditorRect(); if (alloc != null) { Document doc = t.getDocument(); if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readLock(); } try { rootView.setSize(alloc.width, alloc.height); Shape toDamage = rootView.modelToView(p0, p0Bias, p1, p1Bias, alloc); Rectangle rect = (toDamage instanceof Rectangle) ? (Rectangle)toDamage : toDamage.getBounds(); editor.repaint(rect.x, rect.y, rect.width, rect.height); } catch (BadLocationException e) { } finally { if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readUnlock(); } } } } } /** {@collect.stats} * Fetches the EditorKit for the UI. * * @param tc the text component for which this UI is installed * @return the editor capabilities * @see TextUI#getEditorKit */ public EditorKit getEditorKit(JTextComponent tc) { return defaultKit; } /** {@collect.stats} * Fetches a View with the allocation of the associated * text component (i.e. the root of the hierarchy) that * can be traversed to determine how the model is being * represented spatially. * <p> * <font color=red><b>NOTE:</b>The View hierarchy can * be traversed from the root view, and other things * can be done as well. Things done in this way cannot * be protected like simple method calls through the TextUI. * Therefore, proper operation in the presence of concurrency * must be arranged by any logic that calls this method! * </font> * * @param tc the text component for which this UI is installed * @return the view * @see TextUI#getRootView */ public View getRootView(JTextComponent tc) { return rootView; } /** {@collect.stats} * Returns the string to be used as the tooltip at the passed in location. * This forwards the method onto the root View. * * @see javax.swing.text.JTextComponent#getToolTipText * @see javax.swing.text.View#getToolTipText * @since 1.4 */ public String getToolTipText(JTextComponent t, Point pt) { if (!painted) { return null; } Document doc = editor.getDocument(); String tt = null; Rectangle alloc = getVisibleEditorRect(); if (alloc != null) { if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readLock(); } try { tt = rootView.getToolTipText(pt.x, pt.y, alloc); } finally { if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readUnlock(); } } } return tt; } // --- ViewFactory methods ------------------------------ /** {@collect.stats} * Creates a view for an element. * If a subclass wishes to directly implement the factory * producing the view(s), it should reimplement this * method. By default it simply returns null indicating * it is unable to represent the element. * * @param elem the element * @return the view */ public View create(Element elem) { return null; } /** {@collect.stats} * Creates a view for an element. * If a subclass wishes to directly implement the factory * producing the view(s), it should reimplement this * method. By default it simply returns null indicating * it is unable to represent the part of the element. * * @param elem the element * @param p0 the starting offset >= 0 * @param p1 the ending offset >= p0 * @return the view */ public View create(Element elem, int p0, int p1) { return null; } public static class BasicCaret extends DefaultCaret implements UIResource {} public static class BasicHighlighter extends DefaultHighlighter implements UIResource {} static class BasicCursor extends Cursor implements UIResource { BasicCursor(int type) { super(type); } BasicCursor(String name) { super(name); } } private static BasicCursor textCursor = new BasicCursor(Cursor.TEXT_CURSOR); // ----- member variables --------------------------------------- private static final EditorKit defaultKit = new DefaultEditorKit(); transient JTextComponent editor; transient boolean painted; transient RootView rootView = new RootView(); transient UpdateHandler updateHandler = new UpdateHandler(); private static final TransferHandler defaultTransferHandler = new TextTransferHandler(); private final DragListener dragListener = getDragListener(); private static final Position.Bias[] discardBias = new Position.Bias[1]; private DefaultCaret dropCaret; /** {@collect.stats} * Root view that acts as a gateway between the component * and the View hierarchy. */ class RootView extends View { RootView() { super(null); } void setView(View v) { View oldView = view; view = null; if (oldView != null) { // get rid of back reference so that the old // hierarchy can be garbage collected. oldView.setParent(null); } if (v != null) { v.setParent(this); } view = v; } /** {@collect.stats} * Fetches the attributes to use when rendering. At the root * level there are no attributes. If an attribute is resolved * up the view hierarchy this is the end of the line. */ public AttributeSet getAttributes() { return null; } /** {@collect.stats} * Determines the preferred span for this view along an axis. * * @param axis may be either X_AXIS or Y_AXIS * @return the span the view would like to be rendered into. * Typically the view is told to render into the span * that is returned, although there is no guarantee. * The parent may choose to resize or break the view. */ public float getPreferredSpan(int axis) { if (view != null) { return view.getPreferredSpan(axis); } return 10; } /** {@collect.stats} * Determines the minimum span for this view along an axis. * * @param axis may be either X_AXIS or Y_AXIS * @return the span the view would like to be rendered into. * Typically the view is told to render into the span * that is returned, although there is no guarantee. * The parent may choose to resize or break the view. */ public float getMinimumSpan(int axis) { if (view != null) { return view.getMinimumSpan(axis); } return 10; } /** {@collect.stats} * Determines the maximum span for this view along an axis. * * @param axis may be either X_AXIS or Y_AXIS * @return the span the view would like to be rendered into. * Typically the view is told to render into the span * that is returned, although there is no guarantee. * The parent may choose to resize or break the view. */ public float getMaximumSpan(int axis) { return Integer.MAX_VALUE; } /** {@collect.stats} * Specifies that a preference has changed. * Child views can call this on the parent to indicate that * the preference has changed. The root view routes this to * invalidate on the hosting component. * <p> * This can be called on a different thread from the * event dispatching thread and is basically unsafe to * propagate into the component. To make this safe, * the operation is transferred over to the event dispatching * thread for completion. It is a design goal that all view * methods be safe to call without concern for concurrency, * and this behavior helps make that true. * * @param child the child view * @param width true if the width preference has changed * @param height true if the height preference has changed */ public void preferenceChanged(View child, boolean width, boolean height) { editor.revalidate(); } /** {@collect.stats} * Determines the desired alignment for this view along an axis. * * @param axis may be either X_AXIS or Y_AXIS * @return the desired alignment, where 0.0 indicates the origin * and 1.0 the full span away from the origin */ public float getAlignment(int axis) { if (view != null) { return view.getAlignment(axis); } return 0; } /** {@collect.stats} * Renders the view. * * @param g the graphics context * @param allocation the region to render into */ public void paint(Graphics g, Shape allocation) { if (view != null) { Rectangle alloc = (allocation instanceof Rectangle) ? (Rectangle)allocation : allocation.getBounds(); setSize(alloc.width, alloc.height); view.paint(g, allocation); } } /** {@collect.stats} * Sets the view parent. * * @param parent the parent view */ public void setParent(View parent) { throw new Error("Can't set parent on root view"); } /** {@collect.stats} * Returns the number of views in this view. Since * this view simply wraps the root of the view hierarchy * it has exactly one child. * * @return the number of views * @see #getView */ public int getViewCount() { return 1; } /** {@collect.stats} * Gets the n-th view in this container. * * @param n the number of the view to get * @return the view */ public View getView(int n) { return view; } /** {@collect.stats} * Returns the child view index representing the given position in * the model. This is implemented to return the index of the only * child. * * @param pos the position >= 0 * @return index of the view representing the given position, or * -1 if no view represents that position * @since 1.3 */ public int getViewIndex(int pos, Position.Bias b) { return 0; } /** {@collect.stats} * Fetches the allocation for the given child view. * This enables finding out where various views * are located, without assuming the views store * their location. This returns the given allocation * since this view simply acts as a gateway between * the view hierarchy and the associated component. * * @param index the index of the child * @param a the allocation to this view. * @return the allocation to the child */ public Shape getChildAllocation(int index, Shape a) { return a; } /** {@collect.stats} * Provides a mapping from the document model coordinate space * to the coordinate space of the view mapped to it. * * @param pos the position to convert * @param a the allocated region to render into * @return the bounding box of the given position */ public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException { if (view != null) { return view.modelToView(pos, a, b); } return null; } /** {@collect.stats} * Provides a mapping from the document model coordinate space * to the coordinate space of the view mapped to it. * * @param p0 the position to convert >= 0 * @param b0 the bias toward the previous character or the * next character represented by p0, in case the * position is a boundary of two views. * @param p1 the position to convert >= 0 * @param b1 the bias toward the previous character or the * next character represented by p1, in case the * position is a boundary of two views. * @param a the allocated region to render into * @return the bounding box of the given position is returned * @exception BadLocationException if the given position does * not represent a valid location in the associated document * @exception IllegalArgumentException for an invalid bias argument * @see View#viewToModel */ public Shape modelToView(int p0, Position.Bias b0, int p1, Position.Bias b1, Shape a) throws BadLocationException { if (view != null) { return view.modelToView(p0, b0, p1, b1, a); } return null; } /** {@collect.stats} * Provides a mapping from the view coordinate space to the logical * coordinate space of the model. * * @param x x coordinate of the view location to convert * @param y y coordinate of the view location to convert * @param a the allocated region to render into * @return the location within the model that best represents the * given point in the view */ public int viewToModel(float x, float y, Shape a, Position.Bias[] bias) { if (view != null) { int retValue = view.viewToModel(x, y, a, bias); return retValue; } return -1; } /** {@collect.stats} * Provides a way to determine the next visually represented model * location that one might place a caret. Some views may not be visible, * they might not be in the same order found in the model, or they just * might not allow access to some of the locations in the model. * * @param pos the position to convert >= 0 * @param a the allocated region to render into * @param direction the direction from the current position that can * be thought of as the arrow keys typically found on a keyboard. * This may be SwingConstants.WEST, SwingConstants.EAST, * SwingConstants.NORTH, or SwingConstants.SOUTH. * @return the location within the model that best represents the next * location visual position. * @exception BadLocationException * @exception IllegalArgumentException for an invalid direction */ public int getNextVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) throws BadLocationException { if( view != null ) { int nextPos = view.getNextVisualPositionFrom(pos, b, a, direction, biasRet); if(nextPos != -1) { pos = nextPos; } else { biasRet[0] = b; } } return pos; } /** {@collect.stats} * Gives notification that something was inserted into the document * in a location that this view is responsible for. * * @param e the change information from the associated document * @param a the current allocation of the view * @param f the factory to use to rebuild if the view has children */ public void insertUpdate(DocumentEvent e, Shape a, ViewFactory f) { if (view != null) { view.insertUpdate(e, a, f); } } /** {@collect.stats} * Gives notification that something was removed from the document * in a location that this view is responsible for. * * @param e the change information from the associated document * @param a the current allocation of the view * @param f the factory to use to rebuild if the view has children */ public void removeUpdate(DocumentEvent e, Shape a, ViewFactory f) { if (view != null) { view.removeUpdate(e, a, f); } } /** {@collect.stats} * Gives notification from the document that attributes were changed * in a location that this view is responsible for. * * @param e the change information from the associated document * @param a the current allocation of the view * @param f the factory to use to rebuild if the view has children */ public void changedUpdate(DocumentEvent e, Shape a, ViewFactory f) { if (view != null) { view.changedUpdate(e, a, f); } } /** {@collect.stats} * Returns the document model underlying the view. * * @return the model */ public Document getDocument() { return editor.getDocument(); } /** {@collect.stats} * Returns the starting offset into the model for this view. * * @return the starting offset */ public int getStartOffset() { if (view != null) { return view.getStartOffset(); } return getElement().getStartOffset(); } /** {@collect.stats} * Returns the ending offset into the model for this view. * * @return the ending offset */ public int getEndOffset() { if (view != null) { return view.getEndOffset(); } return getElement().getEndOffset(); } /** {@collect.stats} * Gets the element that this view is mapped to. * * @return the view */ public Element getElement() { if (view != null) { return view.getElement(); } return editor.getDocument().getDefaultRootElement(); } /** {@collect.stats} * Breaks this view on the given axis at the given length. * * @param axis may be either X_AXIS or Y_AXIS * @param len specifies where a break is desired in the span * @param the current allocation of the view * @return the fragment of the view that represents the given span * if the view can be broken, otherwise null */ public View breakView(int axis, float len, Shape a) { throw new Error("Can't break root view"); } /** {@collect.stats} * Determines the resizability of the view along the * given axis. A value of 0 or less is not resizable. * * @param axis may be either X_AXIS or Y_AXIS * @return the weight */ public int getResizeWeight(int axis) { if (view != null) { return view.getResizeWeight(axis); } return 0; } /** {@collect.stats} * Sets the view size. * * @param width the width * @param height the height */ public void setSize(float width, float height) { if (view != null) { view.setSize(width, height); } } /** {@collect.stats} * Fetches the container hosting the view. This is useful for * things like scheduling a repaint, finding out the host * components font, etc. The default implementation * of this is to forward the query to the parent view. * * @return the container */ public Container getContainer() { return editor; } /** {@collect.stats} * Fetches the factory to be used for building the * various view fragments that make up the view that * represents the model. This is what determines * how the model will be represented. This is implemented * to fetch the factory provided by the associated * EditorKit unless that is null, in which case this * simply returns the BasicTextUI itself which allows * subclasses to implement a simple factory directly without * creating extra objects. * * @return the factory */ public ViewFactory getViewFactory() { EditorKit kit = getEditorKit(editor); ViewFactory f = kit.getViewFactory(); if (f != null) { return f; } return BasicTextUI.this; } private View view; } /** {@collect.stats} * Handles updates from various places. If the model is changed, * this class unregisters as a listener to the old model and * registers with the new model. If the document model changes, * the change is forwarded to the root view. If the focus * accelerator changes, a new keystroke is registered to request * focus. */ class UpdateHandler implements PropertyChangeListener, DocumentListener, LayoutManager2, UIResource { // --- PropertyChangeListener methods ----------------------- /** {@collect.stats} * This method gets called when a bound property is changed. * We are looking for document changes on the editor. */ public final void propertyChange(PropertyChangeEvent evt) { Object oldValue = evt.getOldValue(); Object newValue = evt.getNewValue(); String propertyName = evt.getPropertyName(); if ((oldValue instanceof Document) || (newValue instanceof Document)) { if (oldValue != null) { ((Document)oldValue).removeDocumentListener(this); i18nView = false; } if (newValue != null) { ((Document)newValue).addDocumentListener(this); if ("document" == propertyName) { setView(null); BasicTextUI.this.propertyChange(evt); modelChanged(); return; } } modelChanged(); } if ("focusAccelerator" == propertyName) { updateFocusAcceleratorBinding(true); } else if ("componentOrientation" == propertyName) { // Changes in ComponentOrientation require the views to be // rebuilt. modelChanged(); } else if ("font" == propertyName) { modelChanged(); } else if ("dropLocation" == propertyName) { dropIndexChanged(); } else if ("editable" == propertyName) { updateCursor(); modelChanged(); } BasicTextUI.this.propertyChange(evt); } private void dropIndexChanged() { if (editor.getDropMode() == DropMode.USE_SELECTION) { return; } JTextComponent.DropLocation dropLocation = editor.getDropLocation(); if (dropLocation == null) { if (dropCaret != null) { dropCaret.deinstall(editor); editor.repaint(dropCaret); dropCaret = null; } } else { if (dropCaret == null) { dropCaret = new BasicCaret(); dropCaret.install(editor); dropCaret.setVisible(true); } dropCaret.setDot(dropLocation.getIndex(), dropLocation.getBias()); } } // --- DocumentListener methods ----------------------- /** {@collect.stats} * The insert notification. Gets sent to the root of the view structure * that represents the portion of the model being represented by the * editor. The factory is added as an argument to the update so that * the views can update themselves in a dynamic (not hardcoded) way. * * @param e The change notification from the currently associated * document. * @see DocumentListener#insertUpdate */ public final void insertUpdate(DocumentEvent e) { Document doc = e.getDocument(); Object o = doc.getProperty("i18n"); if (o instanceof Boolean) { Boolean i18nFlag = (Boolean) o; if (i18nFlag.booleanValue() != i18nView) { // i18n flag changed, rebuild the view i18nView = i18nFlag.booleanValue(); modelChanged(); return; } } // normal insert update Rectangle alloc = (painted) ? getVisibleEditorRect() : null; rootView.insertUpdate(e, alloc, rootView.getViewFactory()); } /** {@collect.stats} * The remove notification. Gets sent to the root of the view structure * that represents the portion of the model being represented by the * editor. The factory is added as an argument to the update so that * the views can update themselves in a dynamic (not hardcoded) way. * * @param e The change notification from the currently associated * document. * @see DocumentListener#removeUpdate */ public final void removeUpdate(DocumentEvent e) { Rectangle alloc = (painted) ? getVisibleEditorRect() : null; rootView.removeUpdate(e, alloc, rootView.getViewFactory()); } /** {@collect.stats} * The change notification. Gets sent to the root of the view structure * that represents the portion of the model being represented by the * editor. The factory is added as an argument to the update so that * the views can update themselves in a dynamic (not hardcoded) way. * * @param e The change notification from the currently associated * document. * @see DocumentListener#changeUpdate */ public final void changedUpdate(DocumentEvent e) { Rectangle alloc = (painted) ? getVisibleEditorRect() : null; rootView.changedUpdate(e, alloc, rootView.getViewFactory()); } // --- LayoutManager2 methods -------------------------------- /** {@collect.stats} * Adds the specified component with the specified name to * the layout. * @param name the component name * @param comp the component to be added */ public void addLayoutComponent(String name, Component comp) { // not supported } /** {@collect.stats} * Removes the specified component from the layout. * @param comp the component to be removed */ public void removeLayoutComponent(Component comp) { if (constraints != null) { // remove the constraint record constraints.remove(comp); } } /** {@collect.stats} * Calculates the preferred size dimensions for the specified * panel given the components in the specified parent container. * @param parent the component to be laid out * * @see #minimumLayoutSize */ public Dimension preferredLayoutSize(Container parent) { // should not be called (JComponent uses UI instead) return null; } /** {@collect.stats} * Calculates the minimum size dimensions for the specified * panel given the components in the specified parent container. * @param parent the component to be laid out * @see #preferredLayoutSize */ public Dimension minimumLayoutSize(Container parent) { // should not be called (JComponent uses UI instead) return null; } /** {@collect.stats} * Lays out the container in the specified panel. This is * implemented to position all components that were added * with a View object as a constraint. The current allocation * of the associated View is used as the location of the * component. * <p> * A read-lock is acquired on the document to prevent the * view tree from being modified while the layout process * is active. * * @param parent the component which needs to be laid out */ public void layoutContainer(Container parent) { if ((constraints != null) && (! constraints.isEmpty())) { Rectangle alloc = getVisibleEditorRect(); if (alloc != null) { Document doc = editor.getDocument(); if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readLock(); } try { rootView.setSize(alloc.width, alloc.height); Enumeration components = constraints.keys(); while (components.hasMoreElements()) { Component comp = (Component) components.nextElement(); View v = (View) constraints.get(comp); Shape ca = calculateViewPosition(alloc, v); if (ca != null) { Rectangle compAlloc = (ca instanceof Rectangle) ? (Rectangle) ca : ca.getBounds(); comp.setBounds(compAlloc); } } } finally { if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readUnlock(); } } } } } /** {@collect.stats} * Find the Shape representing the given view. */ Shape calculateViewPosition(Shape alloc, View v) { int pos = v.getStartOffset(); View child = null; for (View parent = rootView; (parent != null) && (parent != v); parent = child) { int index = parent.getViewIndex(pos, Position.Bias.Forward); alloc = parent.getChildAllocation(index, alloc); child = parent.getView(index); } return (child != null) ? alloc : null; } /** {@collect.stats} * Adds the specified component to the layout, using the specified * constraint object. We only store those components that were added * with a constraint that is of type View. * * @param comp the component to be added * @param constraint where/how the component is added to the layout. */ public void addLayoutComponent(Component comp, Object constraint) { if (constraint instanceof View) { if (constraints == null) { constraints = new Hashtable(7); } constraints.put(comp, constraint); } } /** {@collect.stats} * Returns the maximum size of this component. * @see java.awt.Component#getMinimumSize() * @see java.awt.Component#getPreferredSize() * @see LayoutManager */ public Dimension maximumLayoutSize(Container target) { // should not be called (JComponent uses UI instead) return null; } /** {@collect.stats} * Returns the alignment along the x axis. This specifies how * the component would like to be aligned relative to other * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. */ public float getLayoutAlignmentX(Container target) { return 0.5f; } /** {@collect.stats} * Returns the alignment along the y axis. This specifies how * the component would like to be aligned relative to other * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. */ public float getLayoutAlignmentY(Container target) { return 0.5f; } /** {@collect.stats} * Invalidates the layout, indicating that if the layout manager * has cached information it should be discarded. */ public void invalidateLayout(Container target) { } /** {@collect.stats} * The "layout constraints" for the LayoutManager2 implementation. * These are View objects for those components that are represented * by a View in the View tree. */ private Hashtable constraints; private boolean i18nView = false; } /** {@collect.stats} * Wrapper for text actions to return isEnabled false in case editor is non editable */ class TextActionWrapper extends TextAction { public TextActionWrapper(TextAction action) { super((String)action.getValue(Action.NAME)); this.action = action; } /** {@collect.stats} * The operation to perform when this action is triggered. * * @param e the action event */ public void actionPerformed(ActionEvent e) { action.actionPerformed(e); } public boolean isEnabled() { return (editor == null || editor.isEditable()) ? action.isEnabled() : false; } TextAction action = null; } /** {@collect.stats} * Registered in the ActionMap. */ class FocusAction extends AbstractAction { public void actionPerformed(ActionEvent e) { editor.requestFocus(); } public boolean isEnabled() { return editor.isEditable(); } } private static DragListener getDragListener() { synchronized(DragListener.class) { DragListener listener = (DragListener)AppContext.getAppContext(). get(DragListener.class); if (listener == null) { listener = new DragListener(); AppContext.getAppContext().put(DragListener.class, listener); } return listener; } } /** {@collect.stats} * Listens for mouse events for the purposes of detecting drag gestures. * BasicTextUI will maintain one of these per AppContext. */ static class DragListener extends MouseInputAdapter implements BeforeDrag { private boolean dragStarted; public void dragStarting(MouseEvent me) { dragStarted = true; } public void mousePressed(MouseEvent e) { JTextComponent c = (JTextComponent)e.getSource(); if (c.getDragEnabled()) { dragStarted = false; if (isDragPossible(e) && DragRecognitionSupport.mousePressed(e)) { e.consume(); } } } public void mouseReleased(MouseEvent e) { JTextComponent c = (JTextComponent)e.getSource(); if (c.getDragEnabled()) { if (dragStarted) { e.consume(); } DragRecognitionSupport.mouseReleased(e); } } public void mouseDragged(MouseEvent e) { JTextComponent c = (JTextComponent)e.getSource(); if (c.getDragEnabled()) { if (dragStarted || DragRecognitionSupport.mouseDragged(e, this)) { e.consume(); } } } /** {@collect.stats} * Determines if the following are true: * <ul> * <li>the component is enabled * <li>the press event is located over a selection * </ul> */ protected boolean isDragPossible(MouseEvent e) { JTextComponent c = (JTextComponent)e.getSource(); if (c.isEnabled()) { Caret caret = c.getCaret(); int dot = caret.getDot(); int mark = caret.getMark(); if (dot != mark) { Point p = new Point(e.getX(), e.getY()); int pos = c.viewToModel(p); int p0 = Math.min(dot, mark); int p1 = Math.max(dot, mark); if ((pos >= p0) && (pos < p1)) { return true; } } } return false; } } static class TextTransferHandler extends TransferHandler implements UIResource { private JTextComponent exportComp; private boolean shouldRemove; private int p0; private int p1; /** {@collect.stats} * Whether or not this is a drop using * <code>DropMode.INSERT</code>. */ private boolean modeBetween = false; /** {@collect.stats} * Whether or not this is a drop. */ private boolean isDrop = false; /** {@collect.stats} * The drop action. */ private int dropAction = MOVE; /** {@collect.stats} * The drop bias. */ private Position.Bias dropBias; /** {@collect.stats} * Try to find a flavor that can be used to import a Transferable. * The set of usable flavors are tried in the following order: * <ol> * <li>First, an attempt is made to find a flavor matching the content type * of the EditorKit for the component. * <li>Second, an attempt to find a text/plain flavor is made. * <li>Third, an attempt to find a flavor representing a String reference * in the same VM is made. * <li>Lastly, DataFlavor.stringFlavor is searched for. * </ol> */ protected DataFlavor getImportFlavor(DataFlavor[] flavors, JTextComponent c) { DataFlavor plainFlavor = null; DataFlavor refFlavor = null; DataFlavor stringFlavor = null; if (c instanceof JEditorPane) { for (int i = 0; i < flavors.length; i++) { String mime = flavors[i].getMimeType(); if (mime.startsWith(((JEditorPane)c).getEditorKit().getContentType())) { return flavors[i]; } else if (plainFlavor == null && mime.startsWith("text/plain")) { plainFlavor = flavors[i]; } else if (refFlavor == null && mime.startsWith("application/x-java-jvm-local-objectref") && flavors[i].getRepresentationClass() == java.lang.String.class) { refFlavor = flavors[i]; } else if (stringFlavor == null && flavors[i].equals(DataFlavor.stringFlavor)) { stringFlavor = flavors[i]; } } if (plainFlavor != null) { return plainFlavor; } else if (refFlavor != null) { return refFlavor; } else if (stringFlavor != null) { return stringFlavor; } return null; } for (int i = 0; i < flavors.length; i++) { String mime = flavors[i].getMimeType(); if (mime.startsWith("text/plain")) { return flavors[i]; } else if (refFlavor == null && mime.startsWith("application/x-java-jvm-local-objectref") && flavors[i].getRepresentationClass() == java.lang.String.class) { refFlavor = flavors[i]; } else if (stringFlavor == null && flavors[i].equals(DataFlavor.stringFlavor)) { stringFlavor = flavors[i]; } } if (refFlavor != null) { return refFlavor; } else if (stringFlavor != null) { return stringFlavor; } return null; } /** {@collect.stats} * Import the given stream data into the text component. */ protected void handleReaderImport(Reader in, JTextComponent c, boolean useRead) throws BadLocationException, IOException { if (useRead) { int startPosition = c.getSelectionStart(); int endPosition = c.getSelectionEnd(); int length = endPosition - startPosition; EditorKit kit = c.getUI().getEditorKit(c); Document doc = c.getDocument(); if (length > 0) { doc.remove(startPosition, length); } kit.read(in, doc, startPosition); } else { char[] buff = new char[1024]; int nch; boolean lastWasCR = false; int last; StringBuffer sbuff = null; // Read in a block at a time, mapping \r\n to \n, as well as single // \r to \n. while ((nch = in.read(buff, 0, buff.length)) != -1) { if (sbuff == null) { sbuff = new StringBuffer(nch); } last = 0; for(int counter = 0; counter < nch; counter++) { switch(buff[counter]) { case '\r': if (lastWasCR) { if (counter == 0) { sbuff.append('\n'); } else { buff[counter - 1] = '\n'; } } else { lastWasCR = true; } break; case '\n': if (lastWasCR) { if (counter > (last + 1)) { sbuff.append(buff, last, counter - last - 1); } // else nothing to do, can skip \r, next write will // write \n lastWasCR = false; last = counter; } break; default: if (lastWasCR) { if (counter == 0) { sbuff.append('\n'); } else { buff[counter - 1] = '\n'; } lastWasCR = false; } break; } } if (last < nch) { if (lastWasCR) { if (last < (nch - 1)) { sbuff.append(buff, last, nch - last - 1); } } else { sbuff.append(buff, last, nch - last); } } } if (lastWasCR) { sbuff.append('\n'); } c.replaceSelection(sbuff != null ? sbuff.toString() : ""); } } // --- TransferHandler methods ------------------------------------ /** {@collect.stats} * This is the type of transfer actions supported by the source. Some models are * not mutable, so a transfer operation of COPY only should * be advertised in that case. * * @param c The component holding the data to be transfered. This * argument is provided to enable sharing of TransferHandlers by * multiple components. * @return This is implemented to return NONE if the component is a JPasswordField * since exporting data via user gestures is not allowed. If the text component is * editable, COPY_OR_MOVE is returned, otherwise just COPY is allowed. */ public int getSourceActions(JComponent c) { if (c instanceof JPasswordField && c.getClientProperty("JPasswordField.cutCopyAllowed") != Boolean.TRUE) { return NONE; } return ((JTextComponent)c).isEditable() ? COPY_OR_MOVE : COPY; } /** {@collect.stats} * Create a Transferable to use as the source for a data transfer. * * @param comp The component holding the data to be transfered. This * argument is provided to enable sharing of TransferHandlers by * multiple components. * @return The representation of the data to be transfered. * */ protected Transferable createTransferable(JComponent comp) { exportComp = (JTextComponent)comp; shouldRemove = true; p0 = exportComp.getSelectionStart(); p1 = exportComp.getSelectionEnd(); return (p0 != p1) ? (new TextTransferable(exportComp, p0, p1)) : null; } /** {@collect.stats} * This method is called after data has been exported. This method should remove * the data that was transfered if the action was MOVE. * * @param source The component that was the source of the data. * @param data The data that was transferred or possibly null * if the action is <code>NONE</code>. * @param action The actual action that was performed. */ protected void exportDone(JComponent source, Transferable data, int action) { // only remove the text if shouldRemove has not been set to // false by importData and only if the action is a move if (shouldRemove && action == MOVE) { TextTransferable t = (TextTransferable)data; t.removeText(); } exportComp = null; } public boolean importData(TransferSupport support) { isDrop = support.isDrop(); if (isDrop) { modeBetween = ((JTextComponent)support.getComponent()).getDropMode() == DropMode.INSERT; dropBias = ((JTextComponent.DropLocation)support.getDropLocation()).getBias(); dropAction = support.getDropAction(); } try { return super.importData(support); } finally { isDrop = false; modeBetween = false; dropBias = null; dropAction = MOVE; } } /** {@collect.stats} * This method causes a transfer to a component from a clipboard or a * DND drop operation. The Transferable represents the data to be * imported into the component. * * @param comp The component to receive the transfer. This * argument is provided to enable sharing of TransferHandlers by * multiple components. * @param t The data to import * @return true if the data was inserted into the component, false otherwise. */ public boolean importData(JComponent comp, Transferable t) { JTextComponent c = (JTextComponent)comp; int pos = modeBetween ? ((JTextComponent.DropLocation)c.getDropLocation()).getIndex() : c.getCaretPosition(); // if we are importing to the same component that we exported from // then don't actually do anything if the drop location is inside // the drag location and set shouldRemove to false so that exportDone // knows not to remove any data if (dropAction == MOVE && c == exportComp && pos >= p0 && pos <= p1) { shouldRemove = false; return true; } boolean imported = false; DataFlavor importFlavor = getImportFlavor(t.getTransferDataFlavors(), c); if (importFlavor != null) { try { boolean useRead = false; if (comp instanceof JEditorPane) { JEditorPane ep = (JEditorPane)comp; if (!ep.getContentType().startsWith("text/plain") && importFlavor.getMimeType().startsWith(ep.getContentType())) { useRead = true; } } InputContext ic = c.getInputContext(); if (ic != null) { ic.endComposition(); } Reader r = importFlavor.getReaderForText(t); if (modeBetween) { Caret caret = c.getCaret(); if (caret instanceof DefaultCaret) { ((DefaultCaret)caret).setDot(pos, dropBias); } else { c.setCaretPosition(pos); } } handleReaderImport(r, c, useRead); if (isDrop) { c.requestFocus(); Caret caret = c.getCaret(); if (caret instanceof DefaultCaret) { int newPos = caret.getDot(); Position.Bias newBias = ((DefaultCaret)caret).getDotBias(); ((DefaultCaret)caret).setDot(pos, dropBias); ((DefaultCaret)caret).moveDot(newPos, newBias); } else { c.select(pos, c.getCaretPosition()); } } imported = true; } catch (UnsupportedFlavorException ufe) { } catch (BadLocationException ble) { } catch (IOException ioe) { } } return imported; } /** {@collect.stats} * This method indicates if a component would accept an import of the given * set of data flavors prior to actually attempting to import it. * * @param comp The component to receive the transfer. This * argument is provided to enable sharing of TransferHandlers by * multiple components. * @param flavors The data formats available * @return true if the data can be inserted into the component, false otherwise. */ public boolean canImport(JComponent comp, DataFlavor[] flavors) { JTextComponent c = (JTextComponent)comp; if (!(c.isEditable() && c.isEnabled())) { return false; } return (getImportFlavor(flavors, c) != null); } /** {@collect.stats} * A possible implementation of the Transferable interface * for text components. For a JEditorPane with a rich set * of EditorKit implementations, conversions could be made * giving a wider set of formats. This is implemented to * offer up only the active content type and text/plain * (if that is not the active format) since that can be * extracted from other formats. */ static class TextTransferable extends BasicTransferable { TextTransferable(JTextComponent c, int start, int end) { super(null, null); this.c = c; Document doc = c.getDocument(); try { p0 = doc.createPosition(start); p1 = doc.createPosition(end); plainData = c.getSelectedText(); if (c instanceof JEditorPane) { JEditorPane ep = (JEditorPane)c; mimeType = ep.getContentType(); if (mimeType.startsWith("text/plain")) { return; } StringWriter sw = new StringWriter(p1.getOffset() - p0.getOffset()); ep.getEditorKit().write(sw, doc, p0.getOffset(), p1.getOffset() - p0.getOffset()); if (mimeType.startsWith("text/html")) { htmlData = sw.toString(); } else { richText = sw.toString(); } } } catch (BadLocationException ble) { } catch (IOException ioe) { } } void removeText() { if ((p0 != null) && (p1 != null) && (p0.getOffset() != p1.getOffset())) { try { Document doc = c.getDocument(); doc.remove(p0.getOffset(), p1.getOffset() - p0.getOffset()); } catch (BadLocationException e) { } } } // ---- EditorKit other than plain or HTML text ----------------------- /** {@collect.stats} * If the EditorKit is not for text/plain or text/html, that format * is supported through the "richer flavors" part of BasicTransferable. */ protected DataFlavor[] getRicherFlavors() { if (richText == null) { return null; } try { DataFlavor[] flavors = new DataFlavor[3]; flavors[0] = new DataFlavor(mimeType + ";class=java.lang.String"); flavors[1] = new DataFlavor(mimeType + ";class=java.io.Reader"); flavors[2] = new DataFlavor(mimeType + ";class=java.io.InputStream;charset=unicode"); return flavors; } catch (ClassNotFoundException cle) { // fall through to unsupported (should not happen) } return null; } /** {@collect.stats} * The only richer format supported is the file list flavor */ protected Object getRicherData(DataFlavor flavor) throws UnsupportedFlavorException { if (richText == null) { return null; } if (String.class.equals(flavor.getRepresentationClass())) { return richText; } else if (Reader.class.equals(flavor.getRepresentationClass())) { return new StringReader(richText); } else if (InputStream.class.equals(flavor.getRepresentationClass())) { return new StringBufferInputStream(richText); } throw new UnsupportedFlavorException(flavor); } Position p0; Position p1; String mimeType; String richText; JTextComponent c; } } }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import java.awt.event.*; import java.text.ParseException; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import javax.swing.plaf.*; import javax.swing.text.*; import java.beans.*; import java.text.*; import java.util.*; import sun.swing.DefaultLookup; /** {@collect.stats} * The default Spinner UI delegate. * * @author Hans Muller * @since 1.4 */ public class BasicSpinnerUI extends SpinnerUI { /** {@collect.stats} * The spinner that we're a UI delegate for. Initialized by * the <code>installUI</code> method, and reset to null * by <code>uninstallUI</code>. * * @see #installUI * @see #uninstallUI */ protected JSpinner spinner; private Handler handler; /** {@collect.stats} * The mouse/action listeners that are added to the spinner's * arrow buttons. These listeners are shared by all * spinner arrow buttons. * * @see #createNextButton * @see #createPreviousButton */ private static final ArrowButtonHandler nextButtonHandler = new ArrowButtonHandler("increment", true); private static final ArrowButtonHandler previousButtonHandler = new ArrowButtonHandler("decrement", false); private PropertyChangeListener propertyChangeListener; /** {@collect.stats} * Used by the default LayoutManager class - SpinnerLayout for * missing (null) editor/nextButton/previousButton children. */ private static final Dimension zeroSize = new Dimension(0, 0); /** {@collect.stats} * Returns a new instance of BasicSpinnerUI. SpinnerListUI * delegates are allocated one per JSpinner. * * @param c the JSpinner (not used) * @see ComponentUI#createUI * @return a new BasicSpinnerUI object */ public static ComponentUI createUI(JComponent c) { return new BasicSpinnerUI(); } private void maybeAdd(Component c, String s) { if (c != null) { spinner.add(c, s); } } /** {@collect.stats} * Calls <code>installDefaults</code>, <code>installListeners</code>, * and then adds the components returned by <code>createNextButton</code>, * <code>createPreviousButton</code>, and <code>createEditor</code>. * * @param c the JSpinner * @see #installDefaults * @see #installListeners * @see #createNextButton * @see #createPreviousButton * @see #createEditor */ public void installUI(JComponent c) { this.spinner = (JSpinner)c; installDefaults(); installListeners(); maybeAdd(createNextButton(), "Next"); maybeAdd(createPreviousButton(), "Previous"); maybeAdd(createEditor(), "Editor"); updateEnabledState(); installKeyboardActions(); } /** {@collect.stats} * Calls <code>uninstallDefaults</code>, <code>uninstallListeners</code>, * and then removes all of the spinners children. * * @param c the JSpinner (not used) */ public void uninstallUI(JComponent c) { uninstallDefaults(); uninstallListeners(); this.spinner = null; c.removeAll(); } /** {@collect.stats} * Initializes <code>PropertyChangeListener</code> with * a shared object that delegates interesting PropertyChangeEvents * to protected methods. * <p> * This method is called by <code>installUI</code>. * * @see #replaceEditor * @see #uninstallListeners */ protected void installListeners() { propertyChangeListener = createPropertyChangeListener(); spinner.addPropertyChangeListener(propertyChangeListener); if (DefaultLookup.getBoolean(spinner, this, "Spinner.disableOnBoundaryValues", false)) { spinner.addChangeListener(getHandler()); } JComponent editor = spinner.getEditor(); if (editor != null && editor instanceof JSpinner.DefaultEditor) { JTextField tf = ((JSpinner.DefaultEditor)editor).getTextField(); if (tf != null) { tf.addFocusListener(nextButtonHandler); tf.addFocusListener(previousButtonHandler); } } } /** {@collect.stats} * Removes the <code>PropertyChangeListener</code> added * by installListeners. * <p> * This method is called by <code>uninstallUI</code>. * * @see #installListeners */ protected void uninstallListeners() { spinner.removePropertyChangeListener(propertyChangeListener); spinner.removeChangeListener(handler); JComponent editor = spinner.getEditor(); removeEditorBorderListener(editor); if (editor instanceof JSpinner.DefaultEditor) { JTextField tf = ((JSpinner.DefaultEditor)editor).getTextField(); if (tf != null) { tf.removeFocusListener(nextButtonHandler); tf.removeFocusListener(previousButtonHandler); } } propertyChangeListener = null; handler = null; } /** {@collect.stats} * Initialize the <code>JSpinner</code> <code>border</code>, * <code>foreground</code>, and <code>background</code>, properties * based on the corresponding "Spinner.*" properties from defaults table. * The <code>JSpinners</code> layout is set to the value returned by * <code>createLayout</code>. This method is called by <code>installUI</code>. * * @see #uninstallDefaults * @see #installUI * @see #createLayout * @see LookAndFeel#installBorder * @see LookAndFeel#installColors */ protected void installDefaults() { spinner.setLayout(createLayout()); LookAndFeel.installBorder(spinner, "Spinner.border"); LookAndFeel.installColorsAndFont(spinner, "Spinner.background", "Spinner.foreground", "Spinner.font"); LookAndFeel.installProperty(spinner, "opaque", Boolean.TRUE); } /** {@collect.stats} * Sets the <code>JSpinner's</code> layout manager to null. This * method is called by <code>uninstallUI</code>. * * @see #installDefaults * @see #uninstallUI */ protected void uninstallDefaults() { spinner.setLayout(null); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } /** {@collect.stats} * Installs the necessary listeners on the next button, <code>c</code>, * to update the <code>JSpinner</code> in response to a user gesture. * * @param c Component to install the listeners on * @throws NullPointerException if <code>c</code> is null. * @see #createNextButton * @since 1.5 */ protected void installNextButtonListeners(Component c) { installButtonListeners(c, nextButtonHandler); } /** {@collect.stats} * Installs the necessary listeners on the previous button, <code>c</code>, * to update the <code>JSpinner</code> in response to a user gesture. * * @param c Component to install the listeners on. * @throws NullPointerException if <code>c</code> is null. * @see #createPreviousButton * @since 1.5 */ protected void installPreviousButtonListeners(Component c) { installButtonListeners(c, previousButtonHandler); } private void installButtonListeners(Component c, ArrowButtonHandler handler) { if (c instanceof JButton) { ((JButton)c).addActionListener(handler); } c.addMouseListener(handler); } /** {@collect.stats} * Create a <code>LayoutManager</code> that manages the <code>editor</code>, * <code>nextButton</code>, and <code>previousButton</code> * children of the JSpinner. These three children must be * added with a constraint that identifies their role: * "Editor", "Next", and "Previous". The default layout manager * can handle the absence of any of these children. * * @return a LayoutManager for the editor, next button, and previous button. * @see #createNextButton * @see #createPreviousButton * @see #createEditor */ protected LayoutManager createLayout() { return getHandler(); } /** {@collect.stats} * Create a <code>PropertyChangeListener</code> that can be * added to the JSpinner itself. Typically, this listener * will call replaceEditor when the "editor" property changes, * since it's the <code>SpinnerUI's</code> responsibility to * add the editor to the JSpinner (and remove the old one). * This method is called by <code>installListeners</code>. * * @return A PropertyChangeListener for the JSpinner itself * @see #installListeners */ protected PropertyChangeListener createPropertyChangeListener() { return getHandler(); } /** {@collect.stats} * Create a component that will replace the spinner models value * with the object returned by <code>spinner.getPreviousValue</code>. * By default the <code>previousButton</code> is a JButton. This * method invokes <code>installPreviousButtonListeners</code> to * install the necessary listeners to update the <code>JSpinner</code>'s * model in response to a user gesture. If a previousButton isn't needed * (in a subclass) then override this method to return null. * * @return a component that will replace the spinners model with the * next value in the sequence, or null * @see #installUI * @see #createNextButton * @see #installPreviousButtonListeners */ protected Component createPreviousButton() { Component c = createArrowButton(SwingConstants.SOUTH); c.setName("Spinner.previousButton"); installPreviousButtonListeners(c); return c; } /** {@collect.stats} * Create a component that will replace the spinner models value * with the object returned by <code>spinner.getNextValue</code>. * By default the <code>nextButton</code> is a JButton * who's <code>ActionListener</code> updates it's <code>JSpinner</code> * ancestors model. If a nextButton isn't needed (in a subclass) * then override this method to return null. * * @return a component that will replace the spinners model with the * next value in the sequence, or null * @see #installUI * @see #createPreviousButton * @see #installNextButtonListeners */ protected Component createNextButton() { Component c = createArrowButton(SwingConstants.NORTH); c.setName("Spinner.nextButton"); installNextButtonListeners(c); return c; } private Component createArrowButton(int direction) { JButton b = new BasicArrowButton(direction); Border buttonBorder = UIManager.getBorder("Spinner.arrowButtonBorder"); if (buttonBorder instanceof UIResource) { // Wrap the border to avoid having the UIResource be replaced by // the ButtonUI. This is the opposite of using BorderUIResource. b.setBorder(new CompoundBorder(buttonBorder, null)); } else { b.setBorder(buttonBorder); } b.setInheritsPopupMenu(true); return b; } /** {@collect.stats} * This method is called by installUI to get the editor component * of the <code>JSpinner</code>. By default it just returns * <code>JSpinner.getEditor()</code>. Subclasses can override * <code>createEditor</code> to return a component that contains * the spinner's editor or null, if they're going to handle adding * the editor to the <code>JSpinner</code> in an * <code>installUI</code> override. * <p> * Typically this method would be overridden to wrap the editor * with a container with a custom border, since one can't assume * that the editors border can be set directly. * <p> * The <code>replaceEditor</code> method is called when the spinners * editor is changed with <code>JSpinner.setEditor</code>. If you've * overriden this method, then you'll probably want to override * <code>replaceEditor</code> as well. * * @return the JSpinners editor JComponent, spinner.getEditor() by default * @see #installUI * @see #replaceEditor * @see JSpinner#getEditor */ protected JComponent createEditor() { JComponent editor = spinner.getEditor(); maybeRemoveEditorBorder(editor); installEditorBorderListener(editor); editor.setInheritsPopupMenu(true); updateEditorAlignment(editor); return editor; } /** {@collect.stats} * Called by the <code>PropertyChangeListener</code> when the * <code>JSpinner</code> editor property changes. It's the responsibility * of this method to remove the old editor and add the new one. By * default this operation is just: * <pre> * spinner.remove(oldEditor); * spinner.add(newEditor, "Editor"); * </pre> * The implementation of <code>replaceEditor</code> should be coordinated * with the <code>createEditor</code> method. * * @see #createEditor * @see #createPropertyChangeListener */ protected void replaceEditor(JComponent oldEditor, JComponent newEditor) { spinner.remove(oldEditor); maybeRemoveEditorBorder(newEditor); installEditorBorderListener(newEditor); newEditor.setInheritsPopupMenu(true); updateEditorAlignment(newEditor); spinner.add(newEditor, "Editor"); } private void updateEditorAlignment(JComponent editor) { if (editor instanceof JSpinner.DefaultEditor) { // if editor alignment isn't set in LAF, we get 0 (CENTER) here int alignment = UIManager.getInt("Spinner.editorAlignment"); JTextField text = ((JSpinner.DefaultEditor)editor).getTextField(); text.setHorizontalAlignment(alignment); } } /** {@collect.stats} * Remove the border around the inner editor component for LaFs * that install an outside border around the spinner, */ private void maybeRemoveEditorBorder(JComponent editor) { if (!UIManager.getBoolean("Spinner.editorBorderPainted")) { if (editor instanceof JPanel && editor.getBorder() == null && editor.getComponentCount() > 0) { editor = (JComponent)editor.getComponent(0); } if (editor != null && editor.getBorder() instanceof UIResource) { editor.setBorder(null); } } } /** {@collect.stats} * Remove the border around the inner editor component for LaFs * that install an outside border around the spinner, */ private void installEditorBorderListener(JComponent editor) { if (!UIManager.getBoolean("Spinner.editorBorderPainted")) { if (editor instanceof JPanel && editor.getBorder() == null && editor.getComponentCount() > 0) { editor = (JComponent)editor.getComponent(0); } if (editor != null && (editor.getBorder() == null || editor.getBorder() instanceof UIResource)) { editor.addPropertyChangeListener(getHandler()); } } } private void removeEditorBorderListener(JComponent editor) { if (!UIManager.getBoolean("Spinner.editorBorderPainted")) { if (editor instanceof JPanel && editor.getComponentCount() > 0) { editor = (JComponent)editor.getComponent(0); } if (editor != null) { editor.removePropertyChangeListener(getHandler()); } } } /** {@collect.stats} * Updates the enabled state of the children Components based on the * enabled state of the <code>JSpinner</code>. */ private void updateEnabledState() { updateEnabledState(spinner, spinner.isEnabled()); } /** {@collect.stats} * Recursively updates the enabled state of the child * <code>Component</code>s of <code>c</code>. */ private void updateEnabledState(Container c, boolean enabled) { for (int counter = c.getComponentCount() - 1; counter >= 0;counter--) { Component child = c.getComponent(counter); if (DefaultLookup.getBoolean(spinner, this, "Spinner.disableOnBoundaryValues", false)) { SpinnerModel model = spinner.getModel(); if (child.getName() == "Spinner.nextButton" && model.getNextValue() == null) { child.setEnabled(false); } else if (child.getName() == "Spinner.previousButton" && model.getPreviousValue() == null) { child.setEnabled(false); } else { child.setEnabled(enabled); } } else { child.setEnabled(enabled); } if (child instanceof Container) { updateEnabledState((Container)child, enabled); } } } /** {@collect.stats} * Installs the keyboard Actions onto the JSpinner. * * @since 1.5 */ protected void installKeyboardActions() { InputMap iMap = getInputMap(JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); SwingUtilities.replaceUIInputMap(spinner, JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, iMap); LazyActionMap.installLazyActionMap(spinner, BasicSpinnerUI.class, "Spinner.actionMap"); } /** {@collect.stats} * Returns the InputMap to install for <code>condition</code>. */ private InputMap getInputMap(int condition) { if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) { return (InputMap)DefaultLookup.get(spinner, this, "Spinner.ancestorInputMap"); } return null; } static void loadActionMap(LazyActionMap map) { map.put("increment", nextButtonHandler); map.put("decrement", previousButtonHandler); } /** {@collect.stats} * Returns the baseline. * * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public int getBaseline(JComponent c, int width, int height) { super.getBaseline(c, width, height); JComponent editor = spinner.getEditor(); Insets insets = spinner.getInsets(); width = width - insets.left - insets.right; height = height - insets.top - insets.bottom; if (width >= 0 && height >= 0) { int baseline = editor.getBaseline(width, height); if (baseline >= 0) { return insets.top + baseline; } } return -1; } /** {@collect.stats} * Returns an enum indicating how the baseline of the component * changes as the size changes. * * @throws NullPointerException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public Component.BaselineResizeBehavior getBaselineResizeBehavior( JComponent c) { super.getBaselineResizeBehavior(c); return spinner.getEditor().getBaselineResizeBehavior(); } /** {@collect.stats} * A handler for spinner arrow button mouse and action events. When * a left mouse pressed event occurs we look up the (enabled) spinner * that's the source of the event and start the autorepeat timer. The * timer fires action events until any button is released at which * point the timer is stopped and the reference to the spinner cleared. * The timer doesn't start until after a 300ms delay, so often the * source of the initial (and final) action event is just the button * logic for mouse released - which means that we're relying on the fact * that our mouse listener runs after the buttons mouse listener. * <p> * Note that one instance of this handler is shared by all slider previous * arrow buttons and likewise for all of the next buttons, * so it doesn't have any state that persists beyond the limits * of a single button pressed/released gesture. */ private static class ArrowButtonHandler extends AbstractAction implements FocusListener, MouseListener, UIResource { final javax.swing.Timer autoRepeatTimer; final boolean isNext; JSpinner spinner = null; JButton arrowButton = null; ArrowButtonHandler(String name, boolean isNext) { super(name); this.isNext = isNext; autoRepeatTimer = new javax.swing.Timer(60, this); autoRepeatTimer.setInitialDelay(300); } private JSpinner eventToSpinner(AWTEvent e) { Object src = e.getSource(); while ((src instanceof Component) && !(src instanceof JSpinner)) { src = ((Component)src).getParent(); } return (src instanceof JSpinner) ? (JSpinner)src : null; } public void actionPerformed(ActionEvent e) { JSpinner spinner = this.spinner; if (!(e.getSource() instanceof javax.swing.Timer)) { // Most likely resulting from being in ActionMap. spinner = eventToSpinner(e); if (e.getSource() instanceof JButton) { arrowButton = (JButton)e.getSource(); } } else { if (arrowButton!=null && !arrowButton.getModel().isPressed() && autoRepeatTimer.isRunning()) { autoRepeatTimer.stop(); spinner = null; arrowButton = null; } } if (spinner != null) { try { int calendarField = getCalendarField(spinner); spinner.commitEdit(); if (calendarField != -1) { ((SpinnerDateModel)spinner.getModel()). setCalendarField(calendarField); } Object value = (isNext) ? spinner.getNextValue() : spinner.getPreviousValue(); if (value != null) { spinner.setValue(value); select(spinner); } } catch (IllegalArgumentException iae) { UIManager.getLookAndFeel().provideErrorFeedback(spinner); } catch (ParseException pe) { UIManager.getLookAndFeel().provideErrorFeedback(spinner); } } } /** {@collect.stats} * If the spinner's editor is a DateEditor, this selects the field * associated with the value that is being incremented. */ private void select(JSpinner spinner) { JComponent editor = spinner.getEditor(); if (editor instanceof JSpinner.DateEditor) { JSpinner.DateEditor dateEditor = (JSpinner.DateEditor)editor; JFormattedTextField ftf = dateEditor.getTextField(); Format format = dateEditor.getFormat(); Object value; if (format != null && (value = spinner.getValue()) != null) { SpinnerDateModel model = dateEditor.getModel(); DateFormat.Field field = DateFormat.Field.ofCalendarField( model.getCalendarField()); if (field != null) { try { AttributedCharacterIterator iterator = format. formatToCharacterIterator(value); if (!select(ftf, iterator, field) && field == DateFormat.Field.HOUR0) { select(ftf, iterator, DateFormat.Field.HOUR1); } } catch (IllegalArgumentException iae) {} } } } } /** {@collect.stats} * Selects the passed in field, returning true if it is found, * false otherwise. */ private boolean select(JFormattedTextField ftf, AttributedCharacterIterator iterator, DateFormat.Field field) { int max = ftf.getDocument().getLength(); iterator.first(); do { Map attrs = iterator.getAttributes(); if (attrs != null && attrs.containsKey(field)){ int start = iterator.getRunStart(field); int end = iterator.getRunLimit(field); if (start != -1 && end != -1 && start <= max && end <= max) { ftf.select(start, end); } return true; } } while (iterator.next() != CharacterIterator.DONE); return false; } /** {@collect.stats} * Returns the calendarField under the start of the selection, or * -1 if there is no valid calendar field under the selection (or * the spinner isn't editing dates. */ private int getCalendarField(JSpinner spinner) { JComponent editor = spinner.getEditor(); if (editor instanceof JSpinner.DateEditor) { JSpinner.DateEditor dateEditor = (JSpinner.DateEditor)editor; JFormattedTextField ftf = dateEditor.getTextField(); int start = ftf.getSelectionStart(); JFormattedTextField.AbstractFormatter formatter = ftf.getFormatter(); if (formatter instanceof InternationalFormatter) { Format.Field[] fields = ((InternationalFormatter) formatter).getFields(start); for (int counter = 0; counter < fields.length; counter++) { if (fields[counter] instanceof DateFormat.Field) { int calendarField; if (fields[counter] == DateFormat.Field.HOUR1) { calendarField = Calendar.HOUR; } else { calendarField = ((DateFormat.Field) fields[counter]).getCalendarField(); } if (calendarField != -1) { return calendarField; } } } } } return -1; } public void mousePressed(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e) && e.getComponent().isEnabled()) { spinner = eventToSpinner(e); autoRepeatTimer.start(); focusSpinnerIfNecessary(); } } public void mouseReleased(MouseEvent e) { autoRepeatTimer.stop(); arrowButton = null; spinner = null; } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { if (spinner != null && !autoRepeatTimer.isRunning() && spinner == eventToSpinner(e)) { autoRepeatTimer.start(); } } public void mouseExited(MouseEvent e) { if (autoRepeatTimer.isRunning()) { autoRepeatTimer.stop(); } } /** {@collect.stats} * Requests focus on a child of the spinner if the spinner doesn't * have focus. */ private void focusSpinnerIfNecessary() { Component fo = KeyboardFocusManager. getCurrentKeyboardFocusManager().getFocusOwner(); if (spinner.isRequestFocusEnabled() && ( fo == null || !SwingUtilities.isDescendingFrom(fo, spinner))) { Container root = spinner; if (!root.isFocusCycleRoot()) { root = root.getFocusCycleRootAncestor(); } if (root != null) { FocusTraversalPolicy ftp = root.getFocusTraversalPolicy(); Component child = ftp.getComponentAfter(root, spinner); if (child != null && SwingUtilities.isDescendingFrom( child, spinner)) { child.requestFocus(); } } } } public void focusGained(FocusEvent e) { } public void focusLost(FocusEvent e) { if (spinner == eventToSpinner(e)) { if (autoRepeatTimer.isRunning()) { autoRepeatTimer.stop(); } spinner = null; if (arrowButton != null) { ButtonModel model = arrowButton.getModel(); model.setPressed(false); model.setArmed(false); arrowButton = null; } } } } private static class Handler implements LayoutManager, PropertyChangeListener, ChangeListener { // // LayoutManager // private Component nextButton = null; private Component previousButton = null; private Component editor = null; public void addLayoutComponent(String name, Component c) { if ("Next".equals(name)) { nextButton = c; } else if ("Previous".equals(name)) { previousButton = c; } else if ("Editor".equals(name)) { editor = c; } } public void removeLayoutComponent(Component c) { if (c == nextButton) { nextButton = null; } else if (c == previousButton) { previousButton = null; } else if (c == editor) { editor = null; } } private Dimension preferredSize(Component c) { return (c == null) ? zeroSize : c.getPreferredSize(); } public Dimension preferredLayoutSize(Container parent) { Dimension nextD = preferredSize(nextButton); Dimension previousD = preferredSize(previousButton); Dimension editorD = preferredSize(editor); /* Force the editors height to be a multiple of 2 */ editorD.height = ((editorD.height + 1) / 2) * 2; Dimension size = new Dimension(editorD.width, editorD.height); size.width += Math.max(nextD.width, previousD.width); Insets insets = parent.getInsets(); size.width += insets.left + insets.right; size.height += insets.top + insets.bottom; return size; } public Dimension minimumLayoutSize(Container parent) { return preferredLayoutSize(parent); } private void setBounds(Component c, int x, int y, int width, int height) { if (c != null) { c.setBounds(x, y, width, height); } } public void layoutContainer(Container parent) { int width = parent.getWidth(); int height = parent.getHeight(); Insets insets = parent.getInsets(); Dimension nextD = preferredSize(nextButton); Dimension previousD = preferredSize(previousButton); int buttonsWidth = Math.max(nextD.width, previousD.width); int editorHeight = height - (insets.top + insets.bottom); // The arrowButtonInsets value is used instead of the JSpinner's // insets if not null. Defining this to be (0, 0, 0, 0) causes the // buttons to be aligned with the outer edge of the spinner's // border, and leaving it as "null" places the buttons completely // inside the spinner's border. Insets buttonInsets = UIManager.getInsets("Spinner.arrowButtonInsets"); if (buttonInsets == null) { buttonInsets = insets; } /* Deal with the spinner's componentOrientation property. */ int editorX, editorWidth, buttonsX; if (parent.getComponentOrientation().isLeftToRight()) { editorX = insets.left; editorWidth = width - insets.left - buttonsWidth - buttonInsets.right; buttonsX = width - buttonsWidth - buttonInsets.right; } else { buttonsX = buttonInsets.left; editorX = buttonsX + buttonsWidth; editorWidth = width - buttonInsets.left - buttonsWidth - insets.right; } int nextY = buttonInsets.top; int nextHeight = (height / 2) + (height % 2) - nextY; int previousY = buttonInsets.top + nextHeight; int previousHeight = height - previousY - buttonInsets.bottom; setBounds(editor, editorX, insets.top, editorWidth, editorHeight); setBounds(nextButton, buttonsX, nextY, buttonsWidth, nextHeight); setBounds(previousButton, buttonsX, previousY, buttonsWidth, previousHeight); } // // PropertyChangeListener // public void propertyChange(PropertyChangeEvent e) { String propertyName = e.getPropertyName(); if (e.getSource() instanceof JSpinner) { JSpinner spinner = (JSpinner)(e.getSource()); SpinnerUI spinnerUI = spinner.getUI(); if (spinnerUI instanceof BasicSpinnerUI) { BasicSpinnerUI ui = (BasicSpinnerUI)spinnerUI; if ("editor".equals(propertyName)) { JComponent oldEditor = (JComponent)e.getOldValue(); JComponent newEditor = (JComponent)e.getNewValue(); ui.replaceEditor(oldEditor, newEditor); ui.updateEnabledState(); if (oldEditor instanceof JSpinner.DefaultEditor) { JTextField tf = ((JSpinner.DefaultEditor)oldEditor).getTextField(); if (tf != null) { tf.removeFocusListener(nextButtonHandler); tf.removeFocusListener(previousButtonHandler); } } if (newEditor instanceof JSpinner.DefaultEditor) { JTextField tf = ((JSpinner.DefaultEditor)newEditor).getTextField(); if (tf != null) { if (tf.getFont() instanceof UIResource) { tf.setFont(spinner.getFont()); } tf.addFocusListener(nextButtonHandler); tf.addFocusListener(previousButtonHandler); } } } else if ("enabled".equals(propertyName) || "model".equals(propertyName)) { ui.updateEnabledState(); } else if ("font".equals(propertyName)) { JComponent editor = spinner.getEditor(); if (editor!=null && editor instanceof JSpinner.DefaultEditor) { JTextField tf = ((JSpinner.DefaultEditor)editor).getTextField(); if (tf != null) { if (tf.getFont() instanceof UIResource) { tf.setFont(spinner.getFont()); } } } } else if (JComponent.TOOL_TIP_TEXT_KEY.equals(propertyName)) { updateToolTipTextForChildren(spinner); } } } else if (e.getSource() instanceof JComponent) { JComponent c = (JComponent)e.getSource(); if ((c.getParent() instanceof JPanel) && (c.getParent().getParent() instanceof JSpinner) && "border".equals(propertyName)) { JSpinner spinner = (JSpinner)c.getParent().getParent(); SpinnerUI spinnerUI = spinner.getUI(); if (spinnerUI instanceof BasicSpinnerUI) { BasicSpinnerUI ui = (BasicSpinnerUI)spinnerUI; ui.maybeRemoveEditorBorder(c); } } } } // Syncronizes the ToolTip text for the components within the spinner // to be the same value as the spinner ToolTip text. private void updateToolTipTextForChildren(JComponent spinner) { String toolTipText = spinner.getToolTipText(); Component[] children = spinner.getComponents(); for (int i = 0; i < children.length; i++) { if (children[i] instanceof JSpinner.DefaultEditor) { JTextField tf = ((JSpinner.DefaultEditor)children[i]).getTextField(); if (tf != null) { tf.setToolTipText(toolTipText); } } else if (children[i] instanceof JComponent) { ((JComponent)children[i]).setToolTipText( spinner.getToolTipText() ); } } } public void stateChanged(ChangeEvent e) { if (e.getSource() instanceof JSpinner) { JSpinner spinner = (JSpinner)e.getSource(); SpinnerUI spinnerUI = spinner.getUI(); if (DefaultLookup.getBoolean(spinner, spinnerUI, "Spinner.disableOnBoundaryValues", false) && spinnerUI instanceof BasicSpinnerUI) { BasicSpinnerUI ui = (BasicSpinnerUI)spinnerUI; ui.updateEnabledState(); } } } } }
Java
/* * Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import java.awt.event.*; import java.beans.*; import javax.swing.*; import javax.swing.text.*; import javax.swing.plaf.*; import javax.swing.border.*; /** {@collect.stats} * Provides the look and feel for a styled text editor. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Timothy Prinzing */ public class BasicTextPaneUI extends BasicEditorPaneUI { /** {@collect.stats} * Creates a UI for the JTextPane. * * @param c the JTextPane object * @return the UI */ public static ComponentUI createUI(JComponent c) { return new BasicTextPaneUI(); } /** {@collect.stats} * Creates a new BasicTextPaneUI. */ public BasicTextPaneUI() { super(); } /** {@collect.stats} * Fetches the name used as a key to lookup properties through the * UIManager. This is used as a prefix to all the standard * text properties. * * @return the name ("TextPane") */ protected String getPropertyPrefix() { return "TextPane"; } public void installUI(JComponent c) { super.installUI(c); } /** {@collect.stats} * This method gets called when a bound property is changed * on the associated JTextComponent. This is a hook * which UI implementations may change to reflect how the * UI displays bound properties of JTextComponent subclasses. * If the font, foreground or document has changed, the * the appropriate property is set in the default style of * the document. * * @param evt the property change event */ protected void propertyChange(PropertyChangeEvent evt) { super.propertyChange(evt); } }
Java
/* * Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.awt.datatransfer.*; import java.beans.*; import java.util.Enumeration; import java.util.Hashtable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.UIResource; import javax.swing.plaf.TreeUI; import javax.swing.tree.*; import javax.swing.text.Position; import javax.swing.plaf.basic.DragRecognitionSupport.BeforeDrag; import sun.swing.SwingUtilities2; import sun.swing.DefaultLookup; import sun.swing.UIAction; /** {@collect.stats} * The basic L&F for a hierarchical data structure. * <p> * * @author Scott Violet * @author Shannon Hickey (drag and drop) */ public class BasicTreeUI extends TreeUI { private static final Object BASELINE_COMPONENT_KEY = new Object(); // Tree.baselineComponent // Old actions forward to an instance of this. static private final Actions SHARED_ACTION = new Actions(); transient protected Icon collapsedIcon; transient protected Icon expandedIcon; /** {@collect.stats} * Color used to draw hash marks. If <code>null</code> no hash marks * will be drawn. */ private Color hashColor; /** {@collect.stats} Distance between left margin and where vertical dashes will be * drawn. */ protected int leftChildIndent; /** {@collect.stats} Distance to add to leftChildIndent to determine where cell * contents will be drawn. */ protected int rightChildIndent; /** {@collect.stats} Total distance that will be indented. The sum of leftChildIndent * and rightChildIndent. */ protected int totalChildIndent; /** {@collect.stats} Minimum preferred size. */ protected Dimension preferredMinSize; /** {@collect.stats} Index of the row that was last selected. */ protected int lastSelectedRow; /** {@collect.stats} Component that we're going to be drawing into. */ protected JTree tree; /** {@collect.stats} Renderer that is being used to do the actual cell drawing. */ transient protected TreeCellRenderer currentCellRenderer; /** {@collect.stats} Set to true if the renderer that is currently in the tree was * created by this instance. */ protected boolean createdRenderer; /** {@collect.stats} Editor for the tree. */ transient protected TreeCellEditor cellEditor; /** {@collect.stats} Set to true if editor that is currently in the tree was * created by this instance. */ protected boolean createdCellEditor; /** {@collect.stats} Set to false when editing and shouldSelectCell() returns true meaning * the node should be selected before editing, used in completeEditing. */ protected boolean stopEditingInCompleteEditing; /** {@collect.stats} Used to paint the TreeCellRenderer. */ protected CellRendererPane rendererPane; /** {@collect.stats} Size needed to completely display all the nodes. */ protected Dimension preferredSize; /** {@collect.stats} Is the preferredSize valid? */ protected boolean validCachedPreferredSize; /** {@collect.stats} Object responsible for handling sizing and expanded issues. */ // WARNING: Be careful with the bounds held by treeState. They are // always in terms of left-to-right. They get mapped to right-to-left // by the various methods of this class. protected AbstractLayoutCache treeState; /** {@collect.stats} Used for minimizing the drawing of vertical lines. */ protected Hashtable<TreePath,Boolean> drawingCache; /** {@collect.stats} True if doing optimizations for a largeModel. Subclasses that * don't support this may wish to override createLayoutCache to not * return a FixedHeightLayoutCache instance. */ protected boolean largeModel; /** {@collect.stats} Reponsible for telling the TreeState the size needed for a node. */ protected AbstractLayoutCache.NodeDimensions nodeDimensions; /** {@collect.stats} Used to determine what to display. */ protected TreeModel treeModel; /** {@collect.stats} Model maintaing the selection. */ protected TreeSelectionModel treeSelectionModel; /** {@collect.stats} How much the depth should be offset to properly calculate * x locations. This is based on whether or not the root is visible, * and if the root handles are visible. */ protected int depthOffset; // Following 4 ivars are only valid when editing. /** {@collect.stats} When editing, this will be the Component that is doing the actual * editing. */ protected Component editingComponent; /** {@collect.stats} Path that is being edited. */ protected TreePath editingPath; /** {@collect.stats} Row that is being edited. Should only be referenced if * editingComponent is not null. */ protected int editingRow; /** {@collect.stats} Set to true if the editor has a different size than the renderer. */ protected boolean editorHasDifferentSize; /** {@collect.stats} Row correspondin to lead path. */ private int leadRow; /** {@collect.stats} If true, the property change event for LEAD_SELECTION_PATH_PROPERTY, * or ANCHOR_SELECTION_PATH_PROPERTY will not generate a repaint. */ private boolean ignoreLAChange; /** {@collect.stats} Indicates the orientation. */ private boolean leftToRight; // Cached listeners private PropertyChangeListener propertyChangeListener; private PropertyChangeListener selectionModelPropertyChangeListener; private MouseListener mouseListener; private FocusListener focusListener; private KeyListener keyListener; /** {@collect.stats} Used for large models, listens for moved/resized events and * updates the validCachedPreferredSize bit accordingly. */ private ComponentListener componentListener; /** {@collect.stats} Listens for CellEditor events. */ private CellEditorListener cellEditorListener; /** {@collect.stats} Updates the display when the selection changes. */ private TreeSelectionListener treeSelectionListener; /** {@collect.stats} Is responsible for updating the display based on model events. */ private TreeModelListener treeModelListener; /** {@collect.stats} Updates the treestate as the nodes expand. */ private TreeExpansionListener treeExpansionListener; /** {@collect.stats} UI property indicating whether to paint lines */ private boolean paintLines = true; /** {@collect.stats} UI property for painting dashed lines */ private boolean lineTypeDashed; /** {@collect.stats} * The time factor to treate the series of typed alphanumeric key * as prefix for first letter navigation. */ private long timeFactor = 1000L; private Handler handler; /** {@collect.stats} * A temporary variable for communication between startEditingOnRelease * and startEditing. */ private MouseEvent releaseEvent; public static ComponentUI createUI(JComponent x) { return new BasicTreeUI(); } static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.SELECT_PREVIOUS)); map.put(new Actions(Actions.SELECT_PREVIOUS_CHANGE_LEAD)); map.put(new Actions(Actions.SELECT_PREVIOUS_EXTEND_SELECTION)); map.put(new Actions(Actions.SELECT_NEXT)); map.put(new Actions(Actions.SELECT_NEXT_CHANGE_LEAD)); map.put(new Actions(Actions.SELECT_NEXT_EXTEND_SELECTION)); map.put(new Actions(Actions.SELECT_CHILD)); map.put(new Actions(Actions.SELECT_CHILD_CHANGE_LEAD)); map.put(new Actions(Actions.SELECT_PARENT)); map.put(new Actions(Actions.SELECT_PARENT_CHANGE_LEAD)); map.put(new Actions(Actions.SCROLL_UP_CHANGE_SELECTION)); map.put(new Actions(Actions.SCROLL_UP_CHANGE_LEAD)); map.put(new Actions(Actions.SCROLL_UP_EXTEND_SELECTION)); map.put(new Actions(Actions.SCROLL_DOWN_CHANGE_SELECTION)); map.put(new Actions(Actions.SCROLL_DOWN_EXTEND_SELECTION)); map.put(new Actions(Actions.SCROLL_DOWN_CHANGE_LEAD)); map.put(new Actions(Actions.SELECT_FIRST)); map.put(new Actions(Actions.SELECT_FIRST_CHANGE_LEAD)); map.put(new Actions(Actions.SELECT_FIRST_EXTEND_SELECTION)); map.put(new Actions(Actions.SELECT_LAST)); map.put(new Actions(Actions.SELECT_LAST_CHANGE_LEAD)); map.put(new Actions(Actions.SELECT_LAST_EXTEND_SELECTION)); map.put(new Actions(Actions.TOGGLE)); map.put(new Actions(Actions.CANCEL_EDITING)); map.put(new Actions(Actions.START_EDITING)); map.put(new Actions(Actions.SELECT_ALL)); map.put(new Actions(Actions.CLEAR_SELECTION)); map.put(new Actions(Actions.SCROLL_LEFT)); map.put(new Actions(Actions.SCROLL_RIGHT)); map.put(new Actions(Actions.SCROLL_LEFT_EXTEND_SELECTION)); map.put(new Actions(Actions.SCROLL_RIGHT_EXTEND_SELECTION)); map.put(new Actions(Actions.SCROLL_RIGHT_CHANGE_LEAD)); map.put(new Actions(Actions.SCROLL_LEFT_CHANGE_LEAD)); map.put(new Actions(Actions.EXPAND)); map.put(new Actions(Actions.COLLAPSE)); map.put(new Actions(Actions.MOVE_SELECTION_TO_PARENT)); map.put(new Actions(Actions.ADD_TO_SELECTION)); map.put(new Actions(Actions.TOGGLE_AND_ANCHOR)); map.put(new Actions(Actions.EXTEND_TO)); map.put(new Actions(Actions.MOVE_SELECTION_TO)); map.put(TransferHandler.getCutAction()); map.put(TransferHandler.getCopyAction()); map.put(TransferHandler.getPasteAction()); } public BasicTreeUI() { super(); } protected Color getHashColor() { return hashColor; } protected void setHashColor(Color color) { hashColor = color; } public void setLeftChildIndent(int newAmount) { leftChildIndent = newAmount; totalChildIndent = leftChildIndent + rightChildIndent; if(treeState != null) treeState.invalidateSizes(); updateSize(); } public int getLeftChildIndent() { return leftChildIndent; } public void setRightChildIndent(int newAmount) { rightChildIndent = newAmount; totalChildIndent = leftChildIndent + rightChildIndent; if(treeState != null) treeState.invalidateSizes(); updateSize(); } public int getRightChildIndent() { return rightChildIndent; } public void setExpandedIcon(Icon newG) { expandedIcon = newG; } public Icon getExpandedIcon() { return expandedIcon; } public void setCollapsedIcon(Icon newG) { collapsedIcon = newG; } public Icon getCollapsedIcon() { return collapsedIcon; } // // Methods for configuring the behavior of the tree. None of them // push the value to the JTree instance. You should really only // call these methods on the JTree. // /** {@collect.stats} * Updates the componentListener, if necessary. */ protected void setLargeModel(boolean largeModel) { if(getRowHeight() < 1) largeModel = false; if(this.largeModel != largeModel) { completeEditing(); this.largeModel = largeModel; treeState = createLayoutCache(); configureLayoutCache(); updateLayoutCacheExpandedNodesIfNecessary(); updateSize(); } } protected boolean isLargeModel() { return largeModel; } /** {@collect.stats} * Sets the row height, this is forwarded to the treeState. */ protected void setRowHeight(int rowHeight) { completeEditing(); if(treeState != null) { setLargeModel(tree.isLargeModel()); treeState.setRowHeight(rowHeight); updateSize(); } } protected int getRowHeight() { return (tree == null) ? -1 : tree.getRowHeight(); } /** {@collect.stats} * Sets the TreeCellRenderer to <code>tcr</code>. This invokes * <code>updateRenderer</code>. */ protected void setCellRenderer(TreeCellRenderer tcr) { completeEditing(); updateRenderer(); if(treeState != null) { treeState.invalidateSizes(); updateSize(); } } /** {@collect.stats} * Return currentCellRenderer, which will either be the trees * renderer, or defaultCellRenderer, which ever wasn't null. */ protected TreeCellRenderer getCellRenderer() { return currentCellRenderer; } /** {@collect.stats} * Sets the TreeModel. */ protected void setModel(TreeModel model) { completeEditing(); if(treeModel != null && treeModelListener != null) treeModel.removeTreeModelListener(treeModelListener); treeModel = model; if(treeModel != null) { if(treeModelListener != null) treeModel.addTreeModelListener(treeModelListener); } if(treeState != null) { treeState.setModel(model); updateLayoutCacheExpandedNodesIfNecessary(); updateSize(); } } protected TreeModel getModel() { return treeModel; } /** {@collect.stats} * Sets the root to being visible. */ protected void setRootVisible(boolean newValue) { completeEditing(); updateDepthOffset(); if(treeState != null) { treeState.setRootVisible(newValue); treeState.invalidateSizes(); updateSize(); } } protected boolean isRootVisible() { return (tree != null) ? tree.isRootVisible() : false; } /** {@collect.stats} * Determines whether the node handles are to be displayed. */ protected void setShowsRootHandles(boolean newValue) { completeEditing(); updateDepthOffset(); if(treeState != null) { treeState.invalidateSizes(); updateSize(); } } protected boolean getShowsRootHandles() { return (tree != null) ? tree.getShowsRootHandles() : false; } /** {@collect.stats} * Sets the cell editor. */ protected void setCellEditor(TreeCellEditor editor) { updateCellEditor(); } protected TreeCellEditor getCellEditor() { return (tree != null) ? tree.getCellEditor() : null; } /** {@collect.stats} * Configures the receiver to allow, or not allow, editing. */ protected void setEditable(boolean newValue) { updateCellEditor(); } protected boolean isEditable() { return (tree != null) ? tree.isEditable() : false; } /** {@collect.stats} * Resets the selection model. The appropriate listener are installed * on the model. */ protected void setSelectionModel(TreeSelectionModel newLSM) { completeEditing(); if(selectionModelPropertyChangeListener != null && treeSelectionModel != null) treeSelectionModel.removePropertyChangeListener (selectionModelPropertyChangeListener); if(treeSelectionListener != null && treeSelectionModel != null) treeSelectionModel.removeTreeSelectionListener (treeSelectionListener); treeSelectionModel = newLSM; if(treeSelectionModel != null) { if(selectionModelPropertyChangeListener != null) treeSelectionModel.addPropertyChangeListener (selectionModelPropertyChangeListener); if(treeSelectionListener != null) treeSelectionModel.addTreeSelectionListener (treeSelectionListener); if(treeState != null) treeState.setSelectionModel(treeSelectionModel); } else if(treeState != null) treeState.setSelectionModel(null); if(tree != null) tree.repaint(); } protected TreeSelectionModel getSelectionModel() { return treeSelectionModel; } // // TreeUI methods // /** {@collect.stats} * Returns the Rectangle enclosing the label portion that the * last item in path will be drawn into. Will return null if * any component in path is currently valid. */ public Rectangle getPathBounds(JTree tree, TreePath path) { if(tree != null && treeState != null) { return getPathBounds(path, tree.getInsets(), new Rectangle()); } return null; } private Rectangle getPathBounds(TreePath path, Insets insets, Rectangle bounds) { bounds = treeState.getBounds(path, bounds); if (bounds != null) { if (leftToRight) { bounds.x += insets.left; } else { bounds.x = tree.getWidth() - (bounds.x + bounds.width) - insets.right; } bounds.y += insets.top; } return bounds; } /** {@collect.stats} * Returns the path for passed in row. If row is not visible * null is returned. */ public TreePath getPathForRow(JTree tree, int row) { return (treeState != null) ? treeState.getPathForRow(row) : null; } /** {@collect.stats} * Returns the row that the last item identified in path is visible * at. Will return -1 if any of the elements in path are not * currently visible. */ public int getRowForPath(JTree tree, TreePath path) { return (treeState != null) ? treeState.getRowForPath(path) : -1; } /** {@collect.stats} * Returns the number of rows that are being displayed. */ public int getRowCount(JTree tree) { return (treeState != null) ? treeState.getRowCount() : 0; } /** {@collect.stats} * Returns the path to the node that is closest to x,y. If * there is nothing currently visible this will return null, otherwise * it'll always return a valid path. If you need to test if the * returned object is exactly at x, y you should get the bounds for * the returned path and test x, y against that. */ public TreePath getClosestPathForLocation(JTree tree, int x, int y) { if(tree != null && treeState != null) { // TreeState doesn't care about the x location, hence it isn't // adjusted y -= tree.getInsets().top; return treeState.getPathClosestTo(x, y); } return null; } /** {@collect.stats} * Returns true if the tree is being edited. The item that is being * edited can be returned by getEditingPath(). */ public boolean isEditing(JTree tree) { return (editingComponent != null); } /** {@collect.stats} * Stops the current editing session. This has no effect if the * tree isn't being edited. Returns true if the editor allows the * editing session to stop. */ public boolean stopEditing(JTree tree) { if(editingComponent != null && cellEditor.stopCellEditing()) { completeEditing(false, false, true); return true; } return false; } /** {@collect.stats} * Cancels the current editing session. */ public void cancelEditing(JTree tree) { if(editingComponent != null) { completeEditing(false, true, false); } } /** {@collect.stats} * Selects the last item in path and tries to edit it. Editing will * fail if the CellEditor won't allow it for the selected item. */ public void startEditingAtPath(JTree tree, TreePath path) { tree.scrollPathToVisible(path); if(path != null && tree.isVisible(path)) startEditing(path, null); } /** {@collect.stats} * Returns the path to the element that is being edited. */ public TreePath getEditingPath(JTree tree) { return editingPath; } // // Install methods // public void installUI(JComponent c) { if ( c == null ) { throw new NullPointerException( "null component passed to BasicTreeUI.installUI()" ); } tree = (JTree)c; prepareForUIInstall(); // Boilerplate install block installDefaults(); installKeyboardActions(); installComponents(); installListeners(); completeUIInstall(); } /** {@collect.stats} * Invoked after the <code>tree</code> instance variable has been * set, but before any defaults/listeners have been installed. */ protected void prepareForUIInstall() { drawingCache = new Hashtable<TreePath,Boolean>(7); // Data member initializations leftToRight = BasicGraphicsUtils.isLeftToRight(tree); stopEditingInCompleteEditing = true; lastSelectedRow = -1; leadRow = -1; preferredSize = new Dimension(); largeModel = tree.isLargeModel(); if(getRowHeight() <= 0) largeModel = false; setModel(tree.getModel()); } /** {@collect.stats} * Invoked from installUI after all the defaults/listeners have been * installed. */ protected void completeUIInstall() { // Custom install code this.setShowsRootHandles(tree.getShowsRootHandles()); updateRenderer(); updateDepthOffset(); setSelectionModel(tree.getSelectionModel()); // Create, if necessary, the TreeState instance. treeState = createLayoutCache(); configureLayoutCache(); updateSize(); } protected void installDefaults() { if(tree.getBackground() == null || tree.getBackground() instanceof UIResource) { tree.setBackground(UIManager.getColor("Tree.background")); } if(getHashColor() == null || getHashColor() instanceof UIResource) { setHashColor(UIManager.getColor("Tree.hash")); } if (tree.getFont() == null || tree.getFont() instanceof UIResource) tree.setFont( UIManager.getFont("Tree.font") ); // JTree's original row height is 16. To correctly display the // contents on Linux we should have set it to 18, Windows 19 and // Solaris 20. As these values vary so much it's too hard to // be backward compatable and try to update the row height, we're // therefor NOT going to adjust the row height based on font. If the // developer changes the font, it's there responsibility to update // the row height. setExpandedIcon( (Icon)UIManager.get( "Tree.expandedIcon" ) ); setCollapsedIcon( (Icon)UIManager.get( "Tree.collapsedIcon" ) ); setLeftChildIndent(((Integer)UIManager.get("Tree.leftChildIndent")). intValue()); setRightChildIndent(((Integer)UIManager.get("Tree.rightChildIndent")). intValue()); LookAndFeel.installProperty(tree, "rowHeight", UIManager.get("Tree.rowHeight")); largeModel = (tree.isLargeModel() && tree.getRowHeight() > 0); Object scrollsOnExpand = UIManager.get("Tree.scrollsOnExpand"); if (scrollsOnExpand != null) { LookAndFeel.installProperty(tree, "scrollsOnExpand", scrollsOnExpand); } paintLines = UIManager.getBoolean("Tree.paintLines"); lineTypeDashed = UIManager.getBoolean("Tree.lineTypeDashed"); Long l = (Long)UIManager.get("Tree.timeFactor"); timeFactor = (l!=null) ? l.longValue() : 1000L; Object showsRootHandles = UIManager.get("Tree.showsRootHandles"); if (showsRootHandles != null) { LookAndFeel.installProperty(tree, JTree.SHOWS_ROOT_HANDLES_PROPERTY, showsRootHandles); } } protected void installListeners() { if ( (propertyChangeListener = createPropertyChangeListener()) != null ) { tree.addPropertyChangeListener(propertyChangeListener); } if ( (mouseListener = createMouseListener()) != null ) { tree.addMouseListener(mouseListener); if (mouseListener instanceof MouseMotionListener) { tree.addMouseMotionListener((MouseMotionListener)mouseListener); } } if ((focusListener = createFocusListener()) != null ) { tree.addFocusListener(focusListener); } if ((keyListener = createKeyListener()) != null) { tree.addKeyListener(keyListener); } if((treeExpansionListener = createTreeExpansionListener()) != null) { tree.addTreeExpansionListener(treeExpansionListener); } if((treeModelListener = createTreeModelListener()) != null && treeModel != null) { treeModel.addTreeModelListener(treeModelListener); } if((selectionModelPropertyChangeListener = createSelectionModelPropertyChangeListener()) != null && treeSelectionModel != null) { treeSelectionModel.addPropertyChangeListener (selectionModelPropertyChangeListener); } if((treeSelectionListener = createTreeSelectionListener()) != null && treeSelectionModel != null) { treeSelectionModel.addTreeSelectionListener(treeSelectionListener); } TransferHandler th = tree.getTransferHandler(); if (th == null || th instanceof UIResource) { tree.setTransferHandler(defaultTransferHandler); // default TransferHandler doesn't support drop // so we don't want drop handling if (tree.getDropTarget() instanceof UIResource) { tree.setDropTarget(null); } } LookAndFeel.installProperty(tree, "opaque", Boolean.TRUE); } protected void installKeyboardActions() { InputMap km = getInputMap(JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); SwingUtilities.replaceUIInputMap(tree, JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, km); km = getInputMap(JComponent.WHEN_FOCUSED); SwingUtilities.replaceUIInputMap(tree, JComponent.WHEN_FOCUSED, km); LazyActionMap.installLazyActionMap(tree, BasicTreeUI.class, "Tree.actionMap"); } InputMap getInputMap(int condition) { if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) { return (InputMap)DefaultLookup.get(tree, this, "Tree.ancestorInputMap"); } else if (condition == JComponent.WHEN_FOCUSED) { InputMap keyMap = (InputMap)DefaultLookup.get(tree, this, "Tree.focusInputMap"); InputMap rtlKeyMap; if (tree.getComponentOrientation().isLeftToRight() || ((rtlKeyMap = (InputMap)DefaultLookup.get(tree, this, "Tree.focusInputMap.RightToLeft")) == null)) { return keyMap; } else { rtlKeyMap.setParent(keyMap); return rtlKeyMap; } } return null; } /** {@collect.stats} * Intalls the subcomponents of the tree, which is the renderer pane. */ protected void installComponents() { if ((rendererPane = createCellRendererPane()) != null) { tree.add( rendererPane ); } } // // Create methods. // /** {@collect.stats} * Creates an instance of NodeDimensions that is able to determine * the size of a given node in the tree. */ protected AbstractLayoutCache.NodeDimensions createNodeDimensions() { return new NodeDimensionsHandler(); } /** {@collect.stats} * Creates a listener that is responsible that updates the UI based on * how the tree changes. */ protected PropertyChangeListener createPropertyChangeListener() { return getHandler(); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } /** {@collect.stats} * Creates the listener responsible for updating the selection based on * mouse events. */ protected MouseListener createMouseListener() { return getHandler(); } /** {@collect.stats} * Creates a listener that is responsible for updating the display * when focus is lost/gained. */ protected FocusListener createFocusListener() { return getHandler(); } /** {@collect.stats} * Creates the listener reponsible for getting key events from * the tree. */ protected KeyListener createKeyListener() { return getHandler(); } /** {@collect.stats} * Creates the listener responsible for getting property change * events from the selection model. */ protected PropertyChangeListener createSelectionModelPropertyChangeListener() { return getHandler(); } /** {@collect.stats} * Creates the listener that updates the display based on selection change * methods. */ protected TreeSelectionListener createTreeSelectionListener() { return getHandler(); } /** {@collect.stats} * Creates a listener to handle events from the current editor. */ protected CellEditorListener createCellEditorListener() { return getHandler(); } /** {@collect.stats} * Creates and returns a new ComponentHandler. This is used for * the large model to mark the validCachedPreferredSize as invalid * when the component moves. */ protected ComponentListener createComponentListener() { return new ComponentHandler(); } /** {@collect.stats} * Creates and returns the object responsible for updating the treestate * when nodes expanded state changes. */ protected TreeExpansionListener createTreeExpansionListener() { return getHandler(); } /** {@collect.stats} * Creates the object responsible for managing what is expanded, as * well as the size of nodes. */ protected AbstractLayoutCache createLayoutCache() { if(isLargeModel() && getRowHeight() > 0) { return new FixedHeightLayoutCache(); } return new VariableHeightLayoutCache(); } /** {@collect.stats} * Returns the renderer pane that renderer components are placed in. */ protected CellRendererPane createCellRendererPane() { return new CellRendererPane(); } /** {@collect.stats} * Creates a default cell editor. */ protected TreeCellEditor createDefaultCellEditor() { if(currentCellRenderer != null && (currentCellRenderer instanceof DefaultTreeCellRenderer)) { DefaultTreeCellEditor editor = new DefaultTreeCellEditor (tree, (DefaultTreeCellRenderer)currentCellRenderer); return editor; } return new DefaultTreeCellEditor(tree, null); } /** {@collect.stats} * Returns the default cell renderer that is used to do the * stamping of each node. */ protected TreeCellRenderer createDefaultCellRenderer() { return new DefaultTreeCellRenderer(); } /** {@collect.stats} * Returns a listener that can update the tree when the model changes. */ protected TreeModelListener createTreeModelListener() { return getHandler(); } // // Uninstall methods // public void uninstallUI(JComponent c) { completeEditing(); prepareForUIUninstall(); uninstallDefaults(); uninstallListeners(); uninstallKeyboardActions(); uninstallComponents(); completeUIUninstall(); } protected void prepareForUIUninstall() { } protected void completeUIUninstall() { if(createdRenderer) { tree.setCellRenderer(null); } if(createdCellEditor) { tree.setCellEditor(null); } cellEditor = null; currentCellRenderer = null; rendererPane = null; componentListener = null; propertyChangeListener = null; mouseListener = null; focusListener = null; keyListener = null; setSelectionModel(null); treeState = null; drawingCache = null; selectionModelPropertyChangeListener = null; tree = null; treeModel = null; treeSelectionModel = null; treeSelectionListener = null; treeExpansionListener = null; } protected void uninstallDefaults() { if (tree.getTransferHandler() instanceof UIResource) { tree.setTransferHandler(null); } } protected void uninstallListeners() { if(componentListener != null) { tree.removeComponentListener(componentListener); } if (propertyChangeListener != null) { tree.removePropertyChangeListener(propertyChangeListener); } if (mouseListener != null) { tree.removeMouseListener(mouseListener); if (mouseListener instanceof MouseMotionListener) { tree.removeMouseMotionListener((MouseMotionListener)mouseListener); } } if (focusListener != null) { tree.removeFocusListener(focusListener); } if (keyListener != null) { tree.removeKeyListener(keyListener); } if(treeExpansionListener != null) { tree.removeTreeExpansionListener(treeExpansionListener); } if(treeModel != null && treeModelListener != null) { treeModel.removeTreeModelListener(treeModelListener); } if(selectionModelPropertyChangeListener != null && treeSelectionModel != null) { treeSelectionModel.removePropertyChangeListener (selectionModelPropertyChangeListener); } if(treeSelectionListener != null && treeSelectionModel != null) { treeSelectionModel.removeTreeSelectionListener (treeSelectionListener); } handler = null; } protected void uninstallKeyboardActions() { SwingUtilities.replaceUIActionMap(tree, null); SwingUtilities.replaceUIInputMap(tree, JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null); SwingUtilities.replaceUIInputMap(tree, JComponent.WHEN_FOCUSED, null); } /** {@collect.stats} * Uninstalls the renderer pane. */ protected void uninstallComponents() { if(rendererPane != null) { tree.remove(rendererPane); } } /** {@collect.stats} * Recomputes the right margin, and invalidates any tree states */ private void redoTheLayout() { if (treeState != null) { treeState.invalidateSizes(); } } /** {@collect.stats} * Returns the baseline. * * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public int getBaseline(JComponent c, int width, int height) { super.getBaseline(c, width, height); UIDefaults lafDefaults = UIManager.getLookAndFeelDefaults(); Component renderer = (Component)lafDefaults.get( BASELINE_COMPONENT_KEY); if (renderer == null) { TreeCellRenderer tcr = createDefaultCellRenderer(); renderer = tcr.getTreeCellRendererComponent( tree, "a", false, false, false, -1, false); lafDefaults.put(BASELINE_COMPONENT_KEY, renderer); } int rowHeight = tree.getRowHeight(); int baseline; if (rowHeight > 0) { baseline = renderer.getBaseline(Integer.MAX_VALUE, rowHeight); } else { Dimension pref = renderer.getPreferredSize(); baseline = renderer.getBaseline(pref.width, pref.height); } return baseline + tree.getInsets().top; } /** {@collect.stats} * Returns an enum indicating how the baseline of the component * changes as the size changes. * * @throws NullPointerException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public Component.BaselineResizeBehavior getBaselineResizeBehavior( JComponent c) { super.getBaselineResizeBehavior(c); return Component.BaselineResizeBehavior.CONSTANT_ASCENT; } // // Painting routines. // public void paint(Graphics g, JComponent c) { if (tree != c) { throw new InternalError("incorrect component"); } // Should never happen if installed for a UI if(treeState == null) { return; } Rectangle paintBounds = g.getClipBounds(); Insets insets = tree.getInsets(); TreePath initialPath = getClosestPathForLocation (tree, 0, paintBounds.y); Enumeration paintingEnumerator = treeState.getVisiblePathsFrom (initialPath); int row = treeState.getRowForPath(initialPath); int endY = paintBounds.y + paintBounds.height; drawingCache.clear(); if(initialPath != null && paintingEnumerator != null) { TreePath parentPath = initialPath; // Draw the lines, knobs, and rows // Find each parent and have them draw a line to their last child parentPath = parentPath.getParentPath(); while(parentPath != null) { paintVerticalPartOfLeg(g, paintBounds, insets, parentPath); drawingCache.put(parentPath, Boolean.TRUE); parentPath = parentPath.getParentPath(); } boolean done = false; // Information for the node being rendered. boolean isExpanded; boolean hasBeenExpanded; boolean isLeaf; Rectangle boundsBuffer = new Rectangle(); Rectangle bounds; TreePath path; boolean rootVisible = isRootVisible(); while(!done && paintingEnumerator.hasMoreElements()) { path = (TreePath)paintingEnumerator.nextElement(); if(path != null) { isLeaf = treeModel.isLeaf(path.getLastPathComponent()); if(isLeaf) isExpanded = hasBeenExpanded = false; else { isExpanded = treeState.getExpandedState(path); hasBeenExpanded = tree.hasBeenExpanded(path); } bounds = getPathBounds(path, insets, boundsBuffer); if(bounds == null) // This will only happen if the model changes out // from under us (usually in another thread). // Swing isn't multithreaded, but I'll put this // check in anyway. return; // See if the vertical line to the parent has been drawn. parentPath = path.getParentPath(); if(parentPath != null) { if(drawingCache.get(parentPath) == null) { paintVerticalPartOfLeg(g, paintBounds, insets, parentPath); drawingCache.put(parentPath, Boolean.TRUE); } paintHorizontalPartOfLeg(g, paintBounds, insets, bounds, path, row, isExpanded, hasBeenExpanded, isLeaf); } else if(rootVisible && row == 0) { paintHorizontalPartOfLeg(g, paintBounds, insets, bounds, path, row, isExpanded, hasBeenExpanded, isLeaf); } if(shouldPaintExpandControl(path, row, isExpanded, hasBeenExpanded, isLeaf)) { paintExpandControl(g, paintBounds, insets, bounds, path, row, isExpanded, hasBeenExpanded, isLeaf); } paintRow(g, paintBounds, insets, bounds, path, row, isExpanded, hasBeenExpanded, isLeaf); if((bounds.y + bounds.height) >= endY) done = true; } else { done = true; } row++; } } paintDropLine(g); // Empty out the renderer pane, allowing renderers to be gc'ed. rendererPane.removeAll(); drawingCache.clear(); } private boolean isDropLine(JTree.DropLocation loc) { return loc != null && loc.getPath() != null && loc.getChildIndex() != -1; } private void paintDropLine(Graphics g) { JTree.DropLocation loc = tree.getDropLocation(); if (!isDropLine(loc)) { return; } Color c = UIManager.getColor("Tree.dropLineColor"); if (c != null) { g.setColor(c); Rectangle rect = getDropLineRect(loc); g.fillRect(rect.x, rect.y, rect.width, rect.height); } } private Rectangle getDropLineRect(JTree.DropLocation loc) { Rectangle rect = null; TreePath path = loc.getPath(); int index = loc.getChildIndex(); boolean ltr = leftToRight; Insets insets = tree.getInsets(); if (tree.getRowCount() == 0) { rect = new Rectangle(insets.left, insets.top, tree.getWidth() - insets.left - insets.right, 0); } else { TreeModel model = getModel(); Object root = model.getRoot(); if (path.getLastPathComponent() == root && index >= model.getChildCount(root)) { rect = tree.getRowBounds(tree.getRowCount() - 1); rect.y = rect.y + rect.height; Rectangle xRect; if (!tree.isRootVisible()) { xRect = tree.getRowBounds(0); } else if (model.getChildCount(root) == 0){ xRect = tree.getRowBounds(0); xRect.x += totalChildIndent; xRect.width -= totalChildIndent + totalChildIndent; } else { TreePath lastChildPath = path.pathByAddingChild( model.getChild(root, model.getChildCount(root) - 1)); xRect = tree.getPathBounds(lastChildPath); } rect.x = xRect.x; rect.width = xRect.width; } else { rect = tree.getPathBounds(path.pathByAddingChild( model.getChild(path.getLastPathComponent(), index))); } } if (rect.y != 0) { rect.y--; } if (!ltr) { rect.x = rect.x + rect.width - 100; } rect.width = 100; rect.height = 2; return rect; } /** {@collect.stats} * Paints the horizontal part of the leg. The receiver should * NOT modify <code>clipBounds</code>, or <code>insets</code>.<p> * NOTE: <code>parentRow</code> can be -1 if the root is not visible. */ protected void paintHorizontalPartOfLeg(Graphics g, Rectangle clipBounds, Insets insets, Rectangle bounds, TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) { if (!paintLines) { return; } // Don't paint the legs for the root'ish node if the int depth = path.getPathCount() - 1; if((depth == 0 || (depth == 1 && !isRootVisible())) && !getShowsRootHandles()) { return; } int clipLeft = clipBounds.x; int clipRight = clipBounds.x + clipBounds.width; int clipTop = clipBounds.y; int clipBottom = clipBounds.y + clipBounds.height; int lineY = bounds.y + bounds.height / 2; if (leftToRight) { int leftX = bounds.x - getRightChildIndent(); int nodeX = bounds.x - getHorizontalLegBuffer(); if(lineY >= clipTop && lineY < clipBottom && nodeX >= clipLeft && leftX < clipRight && leftX < nodeX) { g.setColor(getHashColor()); paintHorizontalLine(g, tree, lineY, leftX, nodeX - 1); } } else { int nodeX = bounds.x + bounds.width + getHorizontalLegBuffer(); int rightX = bounds.x + bounds.width + getRightChildIndent(); if(lineY >= clipTop && lineY < clipBottom && rightX >= clipLeft && nodeX < clipRight && nodeX < rightX) { g.setColor(getHashColor()); paintHorizontalLine(g, tree, lineY, nodeX, rightX - 1); } } } /** {@collect.stats} * Paints the vertical part of the leg. The receiver should * NOT modify <code>clipBounds</code>, <code>insets</code>.<p> */ protected void paintVerticalPartOfLeg(Graphics g, Rectangle clipBounds, Insets insets, TreePath path) { if (!paintLines) { return; } int depth = path.getPathCount() - 1; if (depth == 0 && !getShowsRootHandles() && !isRootVisible()) { return; } int lineX = getRowX(-1, depth + 1); if (leftToRight) { lineX = lineX - getRightChildIndent() + insets.left; } else { lineX = tree.getWidth() - lineX - insets.right + getRightChildIndent() - 1; } int clipLeft = clipBounds.x; int clipRight = clipBounds.x + (clipBounds.width - 1); if (lineX >= clipLeft && lineX <= clipRight) { int clipTop = clipBounds.y; int clipBottom = clipBounds.y + clipBounds.height; Rectangle parentBounds = getPathBounds(tree, path); Rectangle lastChildBounds = getPathBounds(tree, getLastChildPath(path)); if(lastChildBounds == null) // This shouldn't happen, but if the model is modified // in another thread it is possible for this to happen. // Swing isn't multithreaded, but I'll add this check in // anyway. return; int top; if(parentBounds == null) { top = Math.max(insets.top + getVerticalLegBuffer(), clipTop); } else top = Math.max(parentBounds.y + parentBounds.height + getVerticalLegBuffer(), clipTop); if(depth == 0 && !isRootVisible()) { TreeModel model = getModel(); if(model != null) { Object root = model.getRoot(); if(model.getChildCount(root) > 0) { parentBounds = getPathBounds(tree, path. pathByAddingChild(model.getChild(root, 0))); if(parentBounds != null) top = Math.max(insets.top + getVerticalLegBuffer(), parentBounds.y + parentBounds.height / 2); } } } int bottom = Math.min(lastChildBounds.y + (lastChildBounds.height / 2), clipBottom); if (top <= bottom) { g.setColor(getHashColor()); paintVerticalLine(g, tree, lineX, top, bottom); } } } /** {@collect.stats} * Paints the expand (toggle) part of a row. The receiver should * NOT modify <code>clipBounds</code>, or <code>insets</code>. */ protected void paintExpandControl(Graphics g, Rectangle clipBounds, Insets insets, Rectangle bounds, TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) { Object value = path.getLastPathComponent(); // Draw icons if not a leaf and either hasn't been loaded, // or the model child count is > 0. if (!isLeaf && (!hasBeenExpanded || treeModel.getChildCount(value) > 0)) { int middleXOfKnob; if (leftToRight) { middleXOfKnob = bounds.x - getRightChildIndent() + 1; } else { middleXOfKnob = bounds.x + bounds.width + getRightChildIndent() - 1; } int middleYOfKnob = bounds.y + (bounds.height / 2); if (isExpanded) { Icon expandedIcon = getExpandedIcon(); if(expandedIcon != null) drawCentered(tree, g, expandedIcon, middleXOfKnob, middleYOfKnob ); } else { Icon collapsedIcon = getCollapsedIcon(); if(collapsedIcon != null) drawCentered(tree, g, collapsedIcon, middleXOfKnob, middleYOfKnob); } } } /** {@collect.stats} * Paints the renderer part of a row. The receiver should * NOT modify <code>clipBounds</code>, or <code>insets</code>. */ protected void paintRow(Graphics g, Rectangle clipBounds, Insets insets, Rectangle bounds, TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) { // Don't paint the renderer if editing this row. if(editingComponent != null && editingRow == row) return; int leadIndex; if(tree.hasFocus()) { leadIndex = getLeadSelectionRow(); } else leadIndex = -1; Component component; component = currentCellRenderer.getTreeCellRendererComponent (tree, path.getLastPathComponent(), tree.isRowSelected(row), isExpanded, isLeaf, row, (leadIndex == row)); rendererPane.paintComponent(g, component, tree, bounds.x, bounds.y, bounds.width, bounds.height, true); } /** {@collect.stats} * Returns true if the expand (toggle) control should be drawn for * the specified row. */ protected boolean shouldPaintExpandControl(TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) { if(isLeaf) return false; int depth = path.getPathCount() - 1; if((depth == 0 || (depth == 1 && !isRootVisible())) && !getShowsRootHandles()) return false; return true; } /** {@collect.stats} * Paints a vertical line. */ protected void paintVerticalLine(Graphics g, JComponent c, int x, int top, int bottom) { if (lineTypeDashed) { drawDashedVerticalLine(g, x, top, bottom); } else { g.drawLine(x, top, x, bottom); } } /** {@collect.stats} * Paints a horizontal line. */ protected void paintHorizontalLine(Graphics g, JComponent c, int y, int left, int right) { if (lineTypeDashed) { drawDashedHorizontalLine(g, y, left, right); } else { g.drawLine(left, y, right, y); } } /** {@collect.stats} * The vertical element of legs between nodes starts at the bottom of the * parent node by default. This method makes the leg start below that. */ protected int getVerticalLegBuffer() { return 0; } /** {@collect.stats} * The horizontal element of legs between nodes starts at the * right of the left-hand side of the child node by default. This * method makes the leg end before that. */ protected int getHorizontalLegBuffer() { return 0; } private int findCenteredX(int x, int iconWidth) { return leftToRight ? x - (int)Math.ceil(iconWidth / 2.0) : x - (int)Math.floor(iconWidth / 2.0); } // // Generic painting methods // // Draws the icon centered at (x,y) protected void drawCentered(Component c, Graphics graphics, Icon icon, int x, int y) { icon.paintIcon(c, graphics, findCenteredX(x, icon.getIconWidth()), y - icon.getIconHeight() / 2); } // This method is slow -- revisit when Java2D is ready. // assumes x1 <= x2 protected void drawDashedHorizontalLine(Graphics g, int y, int x1, int x2){ // Drawing only even coordinates helps join line segments so they // appear as one line. This can be defeated by translating the // Graphics by an odd amount. x1 += (x1 % 2); for (int x = x1; x <= x2; x+=2) { g.drawLine(x, y, x, y); } } // This method is slow -- revisit when Java2D is ready. // assumes y1 <= y2 protected void drawDashedVerticalLine(Graphics g, int x, int y1, int y2) { // Drawing only even coordinates helps join line segments so they // appear as one line. This can be defeated by translating the // Graphics by an odd amount. y1 += (y1 % 2); for (int y = y1; y <= y2; y+=2) { g.drawLine(x, y, x, y); } } // // Various local methods // /** {@collect.stats} * Returns the location, along the x-axis, to render a particular row * at. The return value does not include any Insets specified on the JTree. * This does not check for the validity of the row or depth, it is assumed * to be correct and will not throw an Exception if the row or depth * doesn't match that of the tree. * * @param row Row to return x location for * @param depth Depth of the row * @return amount to indent the given row. * @since 1.5 */ protected int getRowX(int row, int depth) { return totalChildIndent * (depth + depthOffset); } /** {@collect.stats} * Makes all the nodes that are expanded in JTree expanded in LayoutCache. * This invokes updateExpandedDescendants with the root path. */ protected void updateLayoutCacheExpandedNodes() { if(treeModel != null && treeModel.getRoot() != null) updateExpandedDescendants(new TreePath(treeModel.getRoot())); } private void updateLayoutCacheExpandedNodesIfNecessary() { if (treeModel != null && treeModel.getRoot() != null) { TreePath rootPath = new TreePath(treeModel.getRoot()); if (tree.isExpanded(rootPath)) { updateLayoutCacheExpandedNodes(); } else { treeState.setExpandedState(rootPath, false); } } } /** {@collect.stats} * Updates the expanded state of all the descendants of <code>path</code> * by getting the expanded descendants from the tree and forwarding * to the tree state. */ protected void updateExpandedDescendants(TreePath path) { completeEditing(); if(treeState != null) { treeState.setExpandedState(path, true); Enumeration descendants = tree.getExpandedDescendants(path); if(descendants != null) { while(descendants.hasMoreElements()) { path = (TreePath)descendants.nextElement(); treeState.setExpandedState(path, true); } } updateLeadRow(); updateSize(); } } /** {@collect.stats} * Returns a path to the last child of <code>parent</code>. */ protected TreePath getLastChildPath(TreePath parent) { if(treeModel != null) { int childCount = treeModel.getChildCount (parent.getLastPathComponent()); if(childCount > 0) return parent.pathByAddingChild(treeModel.getChild (parent.getLastPathComponent(), childCount - 1)); } return null; } /** {@collect.stats} * Updates how much each depth should be offset by. */ protected void updateDepthOffset() { if(isRootVisible()) { if(getShowsRootHandles()) depthOffset = 1; else depthOffset = 0; } else if(!getShowsRootHandles()) depthOffset = -1; else depthOffset = 0; } /** {@collect.stats} * Updates the cellEditor based on the editability of the JTree that * we're contained in. If the tree is editable but doesn't have a * cellEditor, a basic one will be used. */ protected void updateCellEditor() { TreeCellEditor newEditor; completeEditing(); if(tree == null) newEditor = null; else { if(tree.isEditable()) { newEditor = tree.getCellEditor(); if(newEditor == null) { newEditor = createDefaultCellEditor(); if(newEditor != null) { tree.setCellEditor(newEditor); createdCellEditor = true; } } } else newEditor = null; } if(newEditor != cellEditor) { if(cellEditor != null && cellEditorListener != null) cellEditor.removeCellEditorListener(cellEditorListener); cellEditor = newEditor; if(cellEditorListener == null) cellEditorListener = createCellEditorListener(); if(newEditor != null && cellEditorListener != null) newEditor.addCellEditorListener(cellEditorListener); createdCellEditor = false; } } /** {@collect.stats} * Messaged from the tree we're in when the renderer has changed. */ protected void updateRenderer() { if(tree != null) { TreeCellRenderer newCellRenderer; newCellRenderer = tree.getCellRenderer(); if(newCellRenderer == null) { tree.setCellRenderer(createDefaultCellRenderer()); createdRenderer = true; } else { createdRenderer = false; currentCellRenderer = newCellRenderer; if(createdCellEditor) { tree.setCellEditor(null); } } } else { createdRenderer = false; currentCellRenderer = null; } updateCellEditor(); } /** {@collect.stats} * Resets the TreeState instance based on the tree we're providing the * look and feel for. */ protected void configureLayoutCache() { if(treeState != null && tree != null) { if(nodeDimensions == null) nodeDimensions = createNodeDimensions(); treeState.setNodeDimensions(nodeDimensions); treeState.setRootVisible(tree.isRootVisible()); treeState.setRowHeight(tree.getRowHeight()); treeState.setSelectionModel(getSelectionModel()); // Only do this if necessary, may loss state if call with // same model as it currently has. if(treeState.getModel() != tree.getModel()) treeState.setModel(tree.getModel()); updateLayoutCacheExpandedNodesIfNecessary(); // Create a listener to update preferred size when bounds // changes, if necessary. if(isLargeModel()) { if(componentListener == null) { componentListener = createComponentListener(); if(componentListener != null) tree.addComponentListener(componentListener); } } else if(componentListener != null) { tree.removeComponentListener(componentListener); componentListener = null; } } else if(componentListener != null) { tree.removeComponentListener(componentListener); componentListener = null; } } /** {@collect.stats} * Marks the cached size as being invalid, and messages the * tree with <code>treeDidChange</code>. */ protected void updateSize() { validCachedPreferredSize = false; tree.treeDidChange(); } private void updateSize0() { validCachedPreferredSize = false; tree.revalidate(); } /** {@collect.stats} * Updates the <code>preferredSize</code> instance variable, * which is returned from <code>getPreferredSize()</code>.<p> * For left to right orientations, the size is determined from the * current AbstractLayoutCache. For RTL orientations, the preferred size * becomes the width minus the minimum x position. */ protected void updateCachedPreferredSize() { if(treeState != null) { Insets i = tree.getInsets(); if(isLargeModel()) { Rectangle visRect = tree.getVisibleRect(); if (visRect.x == 0 && visRect.y == 0 && visRect.width == 0 && visRect.height == 0 && tree.getVisibleRowCount() > 0) { // The tree doesn't have a valid bounds yet. Calculate // based on visible row count. visRect.width = 1; visRect.height = tree.getRowHeight() * tree.getVisibleRowCount(); } else { visRect.x -= i.left; visRect.y -= i.top; } preferredSize.width = treeState.getPreferredWidth(visRect); } else { preferredSize.width = treeState.getPreferredWidth(null); } preferredSize.height = treeState.getPreferredHeight(); preferredSize.width += i.left + i.right; preferredSize.height += i.top + i.bottom; } validCachedPreferredSize = true; } /** {@collect.stats} * Messaged from the VisibleTreeNode after it has been expanded. */ protected void pathWasExpanded(TreePath path) { if(tree != null) { tree.fireTreeExpanded(path); } } /** {@collect.stats} * Messaged from the VisibleTreeNode after it has collapsed. */ protected void pathWasCollapsed(TreePath path) { if(tree != null) { tree.fireTreeCollapsed(path); } } /** {@collect.stats} * Ensures that the rows identified by beginRow through endRow are * visible. */ protected void ensureRowsAreVisible(int beginRow, int endRow) { if(tree != null && beginRow >= 0 && endRow < getRowCount(tree)) { boolean scrollVert = DefaultLookup.getBoolean(tree, this, "Tree.scrollsHorizontallyAndVertically", false); if(beginRow == endRow) { Rectangle scrollBounds = getPathBounds(tree, getPathForRow (tree, beginRow)); if(scrollBounds != null) { if (!scrollVert) { scrollBounds.x = tree.getVisibleRect().x; scrollBounds.width = 1; } tree.scrollRectToVisible(scrollBounds); } } else { Rectangle beginRect = getPathBounds(tree, getPathForRow (tree, beginRow)); Rectangle visRect = tree.getVisibleRect(); Rectangle testRect = beginRect; int beginY = beginRect.y; int maxY = beginY + visRect.height; for(int counter = beginRow + 1; counter <= endRow; counter++) { testRect = getPathBounds(tree, getPathForRow(tree, counter)); if((testRect.y + testRect.height) > maxY) counter = endRow; } tree.scrollRectToVisible(new Rectangle(visRect.x, beginY, 1, testRect.y + testRect.height- beginY)); } } } /** {@collect.stats} Sets the preferred minimum size. */ public void setPreferredMinSize(Dimension newSize) { preferredMinSize = newSize; } /** {@collect.stats} Returns the minimum preferred size. */ public Dimension getPreferredMinSize() { if(preferredMinSize == null) return null; return new Dimension(preferredMinSize); } /** {@collect.stats} Returns the preferred size to properly display the tree, * this is a cover method for getPreferredSize(c, false). */ public Dimension getPreferredSize(JComponent c) { return getPreferredSize(c, true); } /** {@collect.stats} Returns the preferred size to represent the tree in * <I>c</I>. If <I>checkConsistancy</I> is true * <b>checkConsistancy</b> is messaged first. */ public Dimension getPreferredSize(JComponent c, boolean checkConsistancy) { Dimension pSize = this.getPreferredMinSize(); if(!validCachedPreferredSize) updateCachedPreferredSize(); if(tree != null) { if(pSize != null) return new Dimension(Math.max(pSize.width, preferredSize.width), Math.max(pSize.height, preferredSize.height)); return new Dimension(preferredSize.width, preferredSize.height); } else if(pSize != null) return pSize; else return new Dimension(0, 0); } /** {@collect.stats} * Returns the minimum size for this component. Which will be * the min preferred size or 0, 0. */ public Dimension getMinimumSize(JComponent c) { if(this.getPreferredMinSize() != null) return this.getPreferredMinSize(); return new Dimension(0, 0); } /** {@collect.stats} * Returns the maximum size for this component, which will be the * preferred size if the instance is currently in a JTree, or 0, 0. */ public Dimension getMaximumSize(JComponent c) { if(tree != null) return getPreferredSize(tree); if(this.getPreferredMinSize() != null) return this.getPreferredMinSize(); return new Dimension(0, 0); } /** {@collect.stats} * Messages to stop the editing session. If the UI the receiver * is providing the look and feel for returns true from * <code>getInvokesStopCellEditing</code>, stopCellEditing will * invoked on the current editor. Then completeEditing will * be messaged with false, true, false to cancel any lingering * editing. */ protected void completeEditing() { /* If should invoke stopCellEditing, try that */ if(tree.getInvokesStopCellEditing() && stopEditingInCompleteEditing && editingComponent != null) { cellEditor.stopCellEditing(); } /* Invoke cancelCellEditing, this will do nothing if stopCellEditing was successful. */ completeEditing(false, true, false); } /** {@collect.stats} * Stops the editing session. If messageStop is true the editor * is messaged with stopEditing, if messageCancel is true the * editor is messaged with cancelEditing. If messageTree is true * the treeModel is messaged with valueForPathChanged. */ protected void completeEditing(boolean messageStop, boolean messageCancel, boolean messageTree) { if(stopEditingInCompleteEditing && editingComponent != null) { Component oldComponent = editingComponent; TreePath oldPath = editingPath; TreeCellEditor oldEditor = cellEditor; Object newValue = oldEditor.getCellEditorValue(); Rectangle editingBounds = getPathBounds(tree, editingPath); boolean requestFocus = (tree != null && (tree.hasFocus() || SwingUtilities. findFocusOwner(editingComponent) != null)); editingComponent = null; editingPath = null; if(messageStop) oldEditor.stopCellEditing(); else if(messageCancel) oldEditor.cancelCellEditing(); tree.remove(oldComponent); if(editorHasDifferentSize) { treeState.invalidatePathBounds(oldPath); updateSize(); } else { editingBounds.x = 0; editingBounds.width = tree.getSize().width; tree.repaint(editingBounds); } if(requestFocus) tree.requestFocus(); if(messageTree) treeModel.valueForPathChanged(oldPath, newValue); } } // cover method for startEditing that allows us to pass extra // information into that method via a class variable private boolean startEditingOnRelease(TreePath path, MouseEvent event, MouseEvent releaseEvent) { this.releaseEvent = releaseEvent; try { return startEditing(path, event); } finally { this.releaseEvent = null; } } /** {@collect.stats} * Will start editing for node if there is a cellEditor and * shouldSelectCell returns true.<p> * This assumes that path is valid and visible. */ protected boolean startEditing(TreePath path, MouseEvent event) { if (isEditing(tree) && tree.getInvokesStopCellEditing() && !stopEditing(tree)) { return false; } completeEditing(); if(cellEditor != null && tree.isPathEditable(path)) { int row = getRowForPath(tree, path); if(cellEditor.isCellEditable(event)) { editingComponent = cellEditor.getTreeCellEditorComponent (tree, path.getLastPathComponent(), tree.isPathSelected(path), tree.isExpanded(path), treeModel.isLeaf(path.getLastPathComponent()), row); Rectangle nodeBounds = getPathBounds(tree, path); editingRow = row; Dimension editorSize = editingComponent.getPreferredSize(); // Only allow odd heights if explicitly set. if(editorSize.height != nodeBounds.height && getRowHeight() > 0) editorSize.height = getRowHeight(); if(editorSize.width != nodeBounds.width || editorSize.height != nodeBounds.height) { // Editor wants different width or height, invalidate // treeState and relayout. editorHasDifferentSize = true; treeState.invalidatePathBounds(path); updateSize(); // To make sure x/y are updated correctly, fetch // the bounds again. nodeBounds = getPathBounds(tree, path); } else editorHasDifferentSize = false; tree.add(editingComponent); editingComponent.setBounds(nodeBounds.x, nodeBounds.y, nodeBounds.width, nodeBounds.height); editingPath = path; if (editingComponent instanceof JComponent) { ((JComponent)editingComponent).revalidate(); } else { editingComponent.validate(); } editingComponent.repaint(); if(cellEditor.shouldSelectCell(event)) { stopEditingInCompleteEditing = false; tree.setSelectionRow(row); stopEditingInCompleteEditing = true; } Component focusedComponent = SwingUtilities2. compositeRequestFocus(editingComponent); boolean selectAll = true; if(event != null && event instanceof MouseEvent) { /* Find the component that will get forwarded all the mouse events until mouseReleased. */ Point componentPoint = SwingUtilities.convertPoint (tree, new Point(event.getX(), event.getY()), editingComponent); /* Create an instance of BasicTreeMouseListener to handle passing the mouse/motion events to the necessary component. */ // We really want similar behavior to getMouseEventTarget, // but it is package private. Component activeComponent = SwingUtilities. getDeepestComponentAt(editingComponent, componentPoint.x, componentPoint.y); if (activeComponent != null) { MouseInputHandler handler = new MouseInputHandler(tree, activeComponent, event, focusedComponent); if (releaseEvent != null) { handler.mouseReleased(releaseEvent); } selectAll = false; } } if (selectAll && focusedComponent instanceof JTextField) { ((JTextField)focusedComponent).selectAll(); } return true; } else editingComponent = null; } return false; } // // Following are primarily for handling mouse events. // /** {@collect.stats} * If the <code>mouseX</code> and <code>mouseY</code> are in the * expand/collapse region of the <code>row</code>, this will toggle * the row. */ protected void checkForClickInExpandControl(TreePath path, int mouseX, int mouseY) { if (isLocationInExpandControl(path, mouseX, mouseY)) { handleExpandControlClick(path, mouseX, mouseY); } } /** {@collect.stats} * Returns true if <code>mouseX</code> and <code>mouseY</code> fall * in the area of row that is used to expand/collapse the node and * the node at <code>row</code> does not represent a leaf. */ protected boolean isLocationInExpandControl(TreePath path, int mouseX, int mouseY) { if(path != null && !treeModel.isLeaf(path.getLastPathComponent())){ int boxWidth; Insets i = tree.getInsets(); if(getExpandedIcon() != null) boxWidth = getExpandedIcon().getIconWidth(); else boxWidth = 8; int boxLeftX = getRowX(tree.getRowForPath(path), path.getPathCount() - 1); if (leftToRight) { boxLeftX = boxLeftX + i.left - getRightChildIndent() + 1; } else { boxLeftX = tree.getWidth() - boxLeftX - i.right + getRightChildIndent() - 1; } boxLeftX = findCenteredX(boxLeftX, boxWidth); return (mouseX >= boxLeftX && mouseX < (boxLeftX + boxWidth)); } return false; } /** {@collect.stats} * Messaged when the user clicks the particular row, this invokes * toggleExpandState. */ protected void handleExpandControlClick(TreePath path, int mouseX, int mouseY) { toggleExpandState(path); } /** {@collect.stats} * Expands path if it is not expanded, or collapses row if it is expanded. * If expanding a path and JTree scrolls on expand, ensureRowsAreVisible * is invoked to scroll as many of the children to visible as possible * (tries to scroll to last visible descendant of path). */ protected void toggleExpandState(TreePath path) { if(!tree.isExpanded(path)) { int row = getRowForPath(tree, path); tree.expandPath(path); updateSize(); if(row != -1) { if(tree.getScrollsOnExpand()) ensureRowsAreVisible(row, row + treeState. getVisibleChildCount(path)); else ensureRowsAreVisible(row, row); } } else { tree.collapsePath(path); updateSize(); } } /** {@collect.stats} * Returning true signifies a mouse event on the node should toggle * the selection of only the row under mouse. */ protected boolean isToggleSelectionEvent(MouseEvent event) { return (SwingUtilities.isLeftMouseButton(event) && event.isControlDown()); } /** {@collect.stats} * Returning true signifies a mouse event on the node should select * from the anchor point. */ protected boolean isMultiSelectEvent(MouseEvent event) { return (SwingUtilities.isLeftMouseButton(event) && event.isShiftDown()); } /** {@collect.stats} * Returning true indicates the row under the mouse should be toggled * based on the event. This is invoked after checkForClickInExpandControl, * implying the location is not in the expand (toggle) control */ protected boolean isToggleEvent(MouseEvent event) { if(!SwingUtilities.isLeftMouseButton(event)) { return false; } int clickCount = tree.getToggleClickCount(); if(clickCount <= 0) { return false; } return ((event.getClickCount() % clickCount) == 0); } /** {@collect.stats} * Messaged to update the selection based on a MouseEvent over a * particular row. If the event is a toggle selection event, the * row is either selected, or deselected. If the event identifies * a multi selection event, the selection is updated from the * anchor point. Otherwise the row is selected, and if the event * specified a toggle event the row is expanded/collapsed. */ protected void selectPathForEvent(TreePath path, MouseEvent event) { /* Adjust from the anchor point. */ if(isMultiSelectEvent(event)) { TreePath anchor = getAnchorSelectionPath(); int anchorRow = (anchor == null) ? -1 : getRowForPath(tree, anchor); if(anchorRow == -1 || tree.getSelectionModel(). getSelectionMode() == TreeSelectionModel. SINGLE_TREE_SELECTION) { tree.setSelectionPath(path); } else { int row = getRowForPath(tree, path); TreePath lastAnchorPath = anchor; if (isToggleSelectionEvent(event)) { if (tree.isRowSelected(anchorRow)) { tree.addSelectionInterval(anchorRow, row); } else { tree.removeSelectionInterval(anchorRow, row); tree.addSelectionInterval(row, row); } } else if(row < anchorRow) { tree.setSelectionInterval(row, anchorRow); } else { tree.setSelectionInterval(anchorRow, row); } lastSelectedRow = row; setAnchorSelectionPath(lastAnchorPath); setLeadSelectionPath(path); } } // Should this event toggle the selection of this row? /* Control toggles just this node. */ else if(isToggleSelectionEvent(event)) { if(tree.isPathSelected(path)) tree.removeSelectionPath(path); else tree.addSelectionPath(path); lastSelectedRow = getRowForPath(tree, path); setAnchorSelectionPath(path); setLeadSelectionPath(path); } /* Otherwise set the selection to just this interval. */ else if(SwingUtilities.isLeftMouseButton(event)) { tree.setSelectionPath(path); if(isToggleEvent(event)) { toggleExpandState(path); } } } /** {@collect.stats} * @return true if the node at <code>row</code> is a leaf. */ protected boolean isLeaf(int row) { TreePath path = getPathForRow(tree, row); if(path != null) return treeModel.isLeaf(path.getLastPathComponent()); // Have to return something here... return true; } // // The following selection methods (lead/anchor) are covers for the // methods in JTree. // private void setAnchorSelectionPath(TreePath newPath) { ignoreLAChange = true; try { tree.setAnchorSelectionPath(newPath); } finally{ ignoreLAChange = false; } } private TreePath getAnchorSelectionPath() { return tree.getAnchorSelectionPath(); } private void setLeadSelectionPath(TreePath newPath) { setLeadSelectionPath(newPath, false); } private void setLeadSelectionPath(TreePath newPath, boolean repaint) { Rectangle bounds = repaint ? getPathBounds(tree, getLeadSelectionPath()) : null; ignoreLAChange = true; try { tree.setLeadSelectionPath(newPath); } finally { ignoreLAChange = false; } leadRow = getRowForPath(tree, newPath); if (repaint) { if (bounds != null) { tree.repaint(getRepaintPathBounds(bounds)); } bounds = getPathBounds(tree, newPath); if (bounds != null) { tree.repaint(getRepaintPathBounds(bounds)); } } } private Rectangle getRepaintPathBounds(Rectangle bounds) { if (UIManager.getBoolean("Tree.repaintWholeRow")) { bounds.x = 0; bounds.width = tree.getWidth(); } return bounds; } private TreePath getLeadSelectionPath() { return tree.getLeadSelectionPath(); } private void updateLeadRow() { leadRow = getRowForPath(tree, getLeadSelectionPath()); } private int getLeadSelectionRow() { return leadRow; } /** {@collect.stats} * Extends the selection from the anchor to make <code>newLead</code> * the lead of the selection. This does not scroll. */ private void extendSelection(TreePath newLead) { TreePath aPath = getAnchorSelectionPath(); int aRow = (aPath == null) ? -1 : getRowForPath(tree, aPath); int newIndex = getRowForPath(tree, newLead); if(aRow == -1) { tree.setSelectionRow(newIndex); } else { if(aRow < newIndex) { tree.setSelectionInterval(aRow, newIndex); } else { tree.setSelectionInterval(newIndex, aRow); } setAnchorSelectionPath(aPath); setLeadSelectionPath(newLead); } } /** {@collect.stats} * Invokes <code>repaint</code> on the JTree for the passed in TreePath, * <code>path</code>. */ private void repaintPath(TreePath path) { if (path != null) { Rectangle bounds = getPathBounds(tree, path); if (bounds != null) { tree.repaint(bounds.x, bounds.y, bounds.width, bounds.height); } } } /** {@collect.stats} * Updates the TreeState in response to nodes expanding/collapsing. */ public class TreeExpansionHandler implements TreeExpansionListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. /** {@collect.stats} * Called whenever an item in the tree has been expanded. */ public void treeExpanded(TreeExpansionEvent event) { getHandler().treeExpanded(event); } /** {@collect.stats} * Called whenever an item in the tree has been collapsed. */ public void treeCollapsed(TreeExpansionEvent event) { getHandler().treeCollapsed(event); } } // BasicTreeUI.TreeExpansionHandler /** {@collect.stats} * Updates the preferred size when scrolling (if necessary). */ public class ComponentHandler extends ComponentAdapter implements ActionListener { /** {@collect.stats} Timer used when inside a scrollpane and the scrollbar is * adjusting. */ protected Timer timer; /** {@collect.stats} ScrollBar that is being adjusted. */ protected JScrollBar scrollBar; public void componentMoved(ComponentEvent e) { if(timer == null) { JScrollPane scrollPane = getScrollPane(); if(scrollPane == null) updateSize(); else { scrollBar = scrollPane.getVerticalScrollBar(); if(scrollBar == null || !scrollBar.getValueIsAdjusting()) { // Try the horizontal scrollbar. if((scrollBar = scrollPane.getHorizontalScrollBar()) != null && scrollBar.getValueIsAdjusting()) startTimer(); else updateSize(); } else startTimer(); } } } /** {@collect.stats} * Creates, if necessary, and starts a Timer to check if need to * resize the bounds. */ protected void startTimer() { if(timer == null) { timer = new Timer(200, this); timer.setRepeats(true); } timer.start(); } /** {@collect.stats} * Returns the JScrollPane housing the JTree, or null if one isn't * found. */ protected JScrollPane getScrollPane() { Component c = tree.getParent(); while(c != null && !(c instanceof JScrollPane)) c = c.getParent(); if(c instanceof JScrollPane) return (JScrollPane)c; return null; } /** {@collect.stats} * Public as a result of Timer. If the scrollBar is null, or * not adjusting, this stops the timer and updates the sizing. */ public void actionPerformed(ActionEvent ae) { if(scrollBar == null || !scrollBar.getValueIsAdjusting()) { if(timer != null) timer.stop(); updateSize(); timer = null; scrollBar = null; } } } // End of BasicTreeUI.ComponentHandler /** {@collect.stats} * Forwards all TreeModel events to the TreeState. */ public class TreeModelHandler implements TreeModelListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void treeNodesChanged(TreeModelEvent e) { getHandler().treeNodesChanged(e); } public void treeNodesInserted(TreeModelEvent e) { getHandler().treeNodesInserted(e); } public void treeNodesRemoved(TreeModelEvent e) { getHandler().treeNodesRemoved(e); } public void treeStructureChanged(TreeModelEvent e) { getHandler().treeStructureChanged(e); } } // End of BasicTreeUI.TreeModelHandler /** {@collect.stats} * Listens for changes in the selection model and updates the display * accordingly. */ public class TreeSelectionHandler implements TreeSelectionListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. /** {@collect.stats} * Messaged when the selection changes in the tree we're displaying * for. Stops editing, messages super and displays the changed paths. */ public void valueChanged(TreeSelectionEvent event) { getHandler().valueChanged(event); } }// End of BasicTreeUI.TreeSelectionHandler /** {@collect.stats} * Listener responsible for getting cell editing events and updating * the tree accordingly. */ public class CellEditorHandler implements CellEditorListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. /** {@collect.stats} Messaged when editing has stopped in the tree. */ public void editingStopped(ChangeEvent e) { getHandler().editingStopped(e); } /** {@collect.stats} Messaged when editing has been canceled in the tree. */ public void editingCanceled(ChangeEvent e) { getHandler().editingCanceled(e); } } // BasicTreeUI.CellEditorHandler /** {@collect.stats} * This is used to get mutliple key down events to appropriately generate * events. */ public class KeyHandler extends KeyAdapter { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. // Also note these fields aren't use anymore, nor does Handler have // the old functionality. This behavior worked around an old bug // in JComponent that has long since been fixed. /** {@collect.stats} Key code that is being generated for. */ protected Action repeatKeyAction; /** {@collect.stats} Set to true while keyPressed is active. */ protected boolean isKeyDown; /** {@collect.stats} * Invoked when a key has been typed. * * Moves the keyboard focus to the first element * whose first letter matches the alphanumeric key * pressed by the user. Subsequent same key presses * move the keyboard focus to the next object that * starts with the same letter. */ public void keyTyped(KeyEvent e) { getHandler().keyTyped(e); } public void keyPressed(KeyEvent e) { getHandler().keyPressed(e); } public void keyReleased(KeyEvent e) { getHandler().keyReleased(e); } } // End of BasicTreeUI.KeyHandler /** {@collect.stats} * Repaints the lead selection row when focus is lost/gained. */ public class FocusHandler implements FocusListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. /** {@collect.stats} * Invoked when focus is activated on the tree we're in, redraws the * lead row. */ public void focusGained(FocusEvent e) { getHandler().focusGained(e); } /** {@collect.stats} * Invoked when focus is activated on the tree we're in, redraws the * lead row. */ public void focusLost(FocusEvent e) { getHandler().focusLost(e); } } // End of class BasicTreeUI.FocusHandler /** {@collect.stats} * Class responsible for getting size of node, method is forwarded * to BasicTreeUI method. X location does not include insets, that is * handled in getPathBounds. */ // This returns locations that don't include any Insets. public class NodeDimensionsHandler extends AbstractLayoutCache.NodeDimensions { /** {@collect.stats} * Responsible for getting the size of a particular node. */ public Rectangle getNodeDimensions(Object value, int row, int depth, boolean expanded, Rectangle size) { // Return size of editing component, if editing and asking // for editing row. if(editingComponent != null && editingRow == row) { Dimension prefSize = editingComponent. getPreferredSize(); int rh = getRowHeight(); if(rh > 0 && rh != prefSize.height) prefSize.height = rh; if(size != null) { size.x = getRowX(row, depth); size.width = prefSize.width; size.height = prefSize.height; } else { size = new Rectangle(getRowX(row, depth), 0, prefSize.width, prefSize.height); } return size; } // Not editing, use renderer. if(currentCellRenderer != null) { Component aComponent; aComponent = currentCellRenderer.getTreeCellRendererComponent (tree, value, tree.isRowSelected(row), expanded, treeModel.isLeaf(value), row, false); if(tree != null) { // Only ever removed when UI changes, this is OK! rendererPane.add(aComponent); aComponent.validate(); } Dimension prefSize = aComponent.getPreferredSize(); if(size != null) { size.x = getRowX(row, depth); size.width = prefSize.width; size.height = prefSize.height; } else { size = new Rectangle(getRowX(row, depth), 0, prefSize.width, prefSize.height); } return size; } return null; } /** {@collect.stats} * @return amount to indent the given row. */ protected int getRowX(int row, int depth) { return BasicTreeUI.this.getRowX(row, depth); } } // End of class BasicTreeUI.NodeDimensionsHandler /** {@collect.stats} * TreeMouseListener is responsible for updating the selection * based on mouse events. */ public class MouseHandler extends MouseAdapter implements MouseMotionListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. /** {@collect.stats} * Invoked when a mouse button has been pressed on a component. */ public void mousePressed(MouseEvent e) { getHandler().mousePressed(e); } public void mouseDragged(MouseEvent e) { getHandler().mouseDragged(e); } /** {@collect.stats} * Invoked when the mouse button has been moved on a component * (with no buttons no down). * @since 1.4 */ public void mouseMoved(MouseEvent e) { getHandler().mouseMoved(e); } public void mouseReleased(MouseEvent e) { getHandler().mouseReleased(e); } } // End of BasicTreeUI.MouseHandler /** {@collect.stats} * PropertyChangeListener for the tree. Updates the appropriate * varaible, or TreeState, based on what changes. */ public class PropertyChangeHandler implements PropertyChangeListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void propertyChange(PropertyChangeEvent event) { getHandler().propertyChange(event); } } // End of BasicTreeUI.PropertyChangeHandler /** {@collect.stats} * Listener on the TreeSelectionModel, resets the row selection if * any of the properties of the model change. */ public class SelectionModelPropertyChangeHandler implements PropertyChangeListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void propertyChange(PropertyChangeEvent event) { getHandler().propertyChange(event); } } // End of BasicTreeUI.SelectionModelPropertyChangeHandler /** {@collect.stats} * <code>TreeTraverseAction</code> is the action used for left/right keys. * Will toggle the expandedness of a node, as well as potentially * incrementing the selection. */ public class TreeTraverseAction extends AbstractAction { /** {@collect.stats} Determines direction to traverse, 1 means expand, -1 means * collapse. */ protected int direction; /** {@collect.stats} True if the selection is reset, false means only the lead path * changes. */ private boolean changeSelection; public TreeTraverseAction(int direction, String name) { this(direction, name, true); } private TreeTraverseAction(int direction, String name, boolean changeSelection) { this.direction = direction; this.changeSelection = changeSelection; } public void actionPerformed(ActionEvent e) { if (tree != null) { SHARED_ACTION.traverse(tree, BasicTreeUI.this, direction, changeSelection); } } public boolean isEnabled() { return (tree != null && tree.isEnabled()); } } // BasicTreeUI.TreeTraverseAction /** {@collect.stats} TreePageAction handles page up and page down events. */ public class TreePageAction extends AbstractAction { /** {@collect.stats} Specifies the direction to adjust the selection by. */ protected int direction; /** {@collect.stats} True indicates should set selection from anchor path. */ private boolean addToSelection; private boolean changeSelection; public TreePageAction(int direction, String name) { this(direction, name, false, true); } private TreePageAction(int direction, String name, boolean addToSelection, boolean changeSelection) { this.direction = direction; this.addToSelection = addToSelection; this.changeSelection = changeSelection; } public void actionPerformed(ActionEvent e) { if (tree != null) { SHARED_ACTION.page(tree, BasicTreeUI.this, direction, addToSelection, changeSelection); } } public boolean isEnabled() { return (tree != null && tree.isEnabled()); } } // BasicTreeUI.TreePageAction /** {@collect.stats} TreeIncrementAction is used to handle up/down actions. Selection * is moved up or down based on direction. */ public class TreeIncrementAction extends AbstractAction { /** {@collect.stats} Specifies the direction to adjust the selection by. */ protected int direction; /** {@collect.stats} If true the new item is added to the selection, if false the * selection is reset. */ private boolean addToSelection; private boolean changeSelection; public TreeIncrementAction(int direction, String name) { this(direction, name, false, true); } private TreeIncrementAction(int direction, String name, boolean addToSelection, boolean changeSelection) { this.direction = direction; this.addToSelection = addToSelection; this.changeSelection = changeSelection; } public void actionPerformed(ActionEvent e) { if (tree != null) { SHARED_ACTION.increment(tree, BasicTreeUI.this, direction, addToSelection, changeSelection); } } public boolean isEnabled() { return (tree != null && tree.isEnabled()); } } // End of class BasicTreeUI.TreeIncrementAction /** {@collect.stats} * TreeHomeAction is used to handle end/home actions. * Scrolls either the first or last cell to be visible based on * direction. */ public class TreeHomeAction extends AbstractAction { protected int direction; /** {@collect.stats} Set to true if append to selection. */ private boolean addToSelection; private boolean changeSelection; public TreeHomeAction(int direction, String name) { this(direction, name, false, true); } private TreeHomeAction(int direction, String name, boolean addToSelection, boolean changeSelection) { this.direction = direction; this.changeSelection = changeSelection; this.addToSelection = addToSelection; } public void actionPerformed(ActionEvent e) { if (tree != null) { SHARED_ACTION.home(tree, BasicTreeUI.this, direction, addToSelection, changeSelection); } } public boolean isEnabled() { return (tree != null && tree.isEnabled()); } } // End of class BasicTreeUI.TreeHomeAction /** {@collect.stats} * For the first selected row expandedness will be toggled. */ public class TreeToggleAction extends AbstractAction { public TreeToggleAction(String name) { } public void actionPerformed(ActionEvent e) { if(tree != null) { SHARED_ACTION.toggle(tree, BasicTreeUI.this); } } public boolean isEnabled() { return (tree != null && tree.isEnabled()); } } // End of class BasicTreeUI.TreeToggleAction /** {@collect.stats} * ActionListener that invokes cancelEditing when action performed. */ public class TreeCancelEditingAction extends AbstractAction { public TreeCancelEditingAction(String name) { } public void actionPerformed(ActionEvent e) { if(tree != null) { SHARED_ACTION.cancelEditing(tree, BasicTreeUI.this); } } public boolean isEnabled() { return (tree != null && tree.isEnabled() && isEditing(tree)); } } // End of class BasicTreeUI.TreeCancelEditingAction /** {@collect.stats} * MouseInputHandler handles passing all mouse events, * including mouse motion events, until the mouse is released to * the destination it is constructed with. It is assumed all the * events are currently target at source. */ public class MouseInputHandler extends Object implements MouseInputListener { /** {@collect.stats} Source that events are coming from. */ protected Component source; /** {@collect.stats} Destination that receives all events. */ protected Component destination; private Component focusComponent; private boolean dispatchedEvent; public MouseInputHandler(Component source, Component destination, MouseEvent event){ this(source, destination, event, null); } MouseInputHandler(Component source, Component destination, MouseEvent event, Component focusComponent) { this.source = source; this.destination = destination; this.source.addMouseListener(this); this.source.addMouseMotionListener(this); SwingUtilities2.setSkipClickCount(destination, event.getClickCount() - 1); /* Dispatch the editing event! */ destination.dispatchEvent(SwingUtilities.convertMouseEvent (source, event, destination)); this.focusComponent = focusComponent; } public void mouseClicked(MouseEvent e) { if(destination != null) { dispatchedEvent = true; destination.dispatchEvent(SwingUtilities.convertMouseEvent (source, e, destination)); } } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { if(destination != null) destination.dispatchEvent(SwingUtilities.convertMouseEvent (source, e, destination)); removeFromSource(); } public void mouseEntered(MouseEvent e) { if (!SwingUtilities.isLeftMouseButton(e)) { removeFromSource(); } } public void mouseExited(MouseEvent e) { if (!SwingUtilities.isLeftMouseButton(e)) { removeFromSource(); } } public void mouseDragged(MouseEvent e) { if(destination != null) { dispatchedEvent = true; destination.dispatchEvent(SwingUtilities.convertMouseEvent (source, e, destination)); } } public void mouseMoved(MouseEvent e) { removeFromSource(); } protected void removeFromSource() { if(source != null) { source.removeMouseListener(this); source.removeMouseMotionListener(this); if (focusComponent != null && focusComponent == destination && !dispatchedEvent && (focusComponent instanceof JTextField)) { ((JTextField)focusComponent).selectAll(); } } source = destination = null; } } // End of class BasicTreeUI.MouseInputHandler private static final TransferHandler defaultTransferHandler = new TreeTransferHandler(); static class TreeTransferHandler extends TransferHandler implements UIResource, Comparator { private JTree tree; /** {@collect.stats} * Create a Transferable to use as the source for a data transfer. * * @param c The component holding the data to be transfered. This * argument is provided to enable sharing of TransferHandlers by * multiple components. * @return The representation of the data to be transfered. * */ protected Transferable createTransferable(JComponent c) { if (c instanceof JTree) { tree = (JTree) c; TreePath[] paths = tree.getSelectionPaths(); if (paths == null || paths.length == 0) { return null; } StringBuffer plainBuf = new StringBuffer(); StringBuffer htmlBuf = new StringBuffer(); htmlBuf.append("<html>\n<body>\n<ul>\n"); TreeModel model = tree.getModel(); TreePath lastPath = null; TreePath[] displayPaths = getDisplayOrderPaths(paths); for (int i = 0; i < displayPaths.length; i++) { TreePath path = displayPaths[i]; Object node = path.getLastPathComponent(); boolean leaf = model.isLeaf(node); String label = getDisplayString(path, true, leaf); plainBuf.append(label + "\n"); htmlBuf.append(" <li>" + label + "\n"); } // remove the last newline plainBuf.deleteCharAt(plainBuf.length() - 1); htmlBuf.append("</ul>\n</body>\n</html>"); tree = null; return new BasicTransferable(plainBuf.toString(), htmlBuf.toString()); } return null; } public int compare(Object o1, Object o2) { int row1 = tree.getRowForPath((TreePath)o1); int row2 = tree.getRowForPath((TreePath)o2); return row1 - row2; } String getDisplayString(TreePath path, boolean selected, boolean leaf) { int row = tree.getRowForPath(path); boolean hasFocus = tree.getLeadSelectionRow() == row; Object node = path.getLastPathComponent(); return tree.convertValueToText(node, selected, tree.isExpanded(row), leaf, row, hasFocus); } /** {@collect.stats} * Selection paths are in selection order. The conversion to * HTML requires display order. This method resorts the paths * to be in the display order. */ TreePath[] getDisplayOrderPaths(TreePath[] paths) { // sort the paths to display order rather than selection order ArrayList selOrder = new ArrayList(); for (int i = 0; i < paths.length; i++) { selOrder.add(paths[i]); } Collections.sort(selOrder, this); int n = selOrder.size(); TreePath[] displayPaths = new TreePath[n]; for (int i = 0; i < n; i++) { displayPaths[i] = (TreePath) selOrder.get(i); } return displayPaths; } public int getSourceActions(JComponent c) { return COPY; } } private class Handler implements CellEditorListener, FocusListener, KeyListener, MouseListener, MouseMotionListener, PropertyChangeListener, TreeExpansionListener, TreeModelListener, TreeSelectionListener, BeforeDrag { // // KeyListener // private String prefix = ""; private String typedString = ""; private long lastTime = 0L; /** {@collect.stats} * Invoked when a key has been typed. * * Moves the keyboard focus to the first element whose prefix matches the * sequence of alphanumeric keys pressed by the user with delay less * than value of <code>timeFactor</code> property (or 1000 milliseconds * if it is not defined). Subsequent same key presses move the keyboard * focus to the next object that starts with the same letter until another * key is pressed, then it is treated as the prefix with appropriate number * of the same letters followed by first typed another letter. */ public void keyTyped(KeyEvent e) { // handle first letter navigation if(tree != null && tree.getRowCount()>0 && tree.hasFocus() && tree.isEnabled()) { if (e.isAltDown() || e.isControlDown() || e.isMetaDown() || isNavigationKey(e)) { return; } boolean startingFromSelection = true; char c = e.getKeyChar(); long time = e.getWhen(); int startingRow = tree.getLeadSelectionRow(); if (time - lastTime < timeFactor) { typedString += c; if((prefix.length() == 1) && (c == prefix.charAt(0))) { // Subsequent same key presses move the keyboard focus to the next // object that starts with the same letter. startingRow++; } else { prefix = typedString; } } else { startingRow++; typedString = "" + c; prefix = typedString; } lastTime = time; if (startingRow < 0 || startingRow >= tree.getRowCount()) { startingFromSelection = false; startingRow = 0; } TreePath path = tree.getNextMatch(prefix, startingRow, Position.Bias.Forward); if (path != null) { tree.setSelectionPath(path); int row = getRowForPath(tree, path); ensureRowsAreVisible(row, row); } else if (startingFromSelection) { path = tree.getNextMatch(prefix, 0, Position.Bias.Forward); if (path != null) { tree.setSelectionPath(path); int row = getRowForPath(tree, path); ensureRowsAreVisible(row, row); } } } } /** {@collect.stats} * Invoked when a key has been pressed. * * Checks to see if the key event is a navigation key to prevent * dispatching these keys for the first letter navigation. */ public void keyPressed(KeyEvent e) { if ( isNavigationKey(e) ) { prefix = ""; typedString = ""; lastTime = 0L; } } public void keyReleased(KeyEvent e) { } /** {@collect.stats} * Returns whether or not the supplied key event maps to a key that is used for * navigation. This is used for optimizing key input by only passing non- * navigation keys to the first letter navigation mechanism. */ private boolean isNavigationKey(KeyEvent event) { InputMap inputMap = tree.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); KeyStroke key = KeyStroke.getKeyStrokeForEvent(event); if (inputMap != null && inputMap.get(key) != null) { return true; } return false; } // // PropertyChangeListener // public void propertyChange(PropertyChangeEvent event) { if (event.getSource() == treeSelectionModel) { treeSelectionModel.resetRowSelection(); } else if(event.getSource() == tree) { String changeName = event.getPropertyName(); if (changeName == JTree.LEAD_SELECTION_PATH_PROPERTY) { if (!ignoreLAChange) { updateLeadRow(); repaintPath((TreePath)event.getOldValue()); repaintPath((TreePath)event.getNewValue()); } } else if (changeName == JTree.ANCHOR_SELECTION_PATH_PROPERTY) { if (!ignoreLAChange) { repaintPath((TreePath)event.getOldValue()); repaintPath((TreePath)event.getNewValue()); } } if(changeName == JTree.CELL_RENDERER_PROPERTY) { setCellRenderer((TreeCellRenderer)event.getNewValue()); redoTheLayout(); } else if(changeName == JTree.TREE_MODEL_PROPERTY) { setModel((TreeModel)event.getNewValue()); } else if(changeName == JTree.ROOT_VISIBLE_PROPERTY) { setRootVisible(((Boolean)event.getNewValue()). booleanValue()); } else if(changeName == JTree.SHOWS_ROOT_HANDLES_PROPERTY) { setShowsRootHandles(((Boolean)event.getNewValue()). booleanValue()); } else if(changeName == JTree.ROW_HEIGHT_PROPERTY) { setRowHeight(((Integer)event.getNewValue()). intValue()); } else if(changeName == JTree.CELL_EDITOR_PROPERTY) { setCellEditor((TreeCellEditor)event.getNewValue()); } else if(changeName == JTree.EDITABLE_PROPERTY) { setEditable(((Boolean)event.getNewValue()).booleanValue()); } else if(changeName == JTree.LARGE_MODEL_PROPERTY) { setLargeModel(tree.isLargeModel()); } else if(changeName == JTree.SELECTION_MODEL_PROPERTY) { setSelectionModel(tree.getSelectionModel()); } else if(changeName == "font") { completeEditing(); if(treeState != null) treeState.invalidateSizes(); updateSize(); } else if (changeName == "componentOrientation") { if (tree != null) { leftToRight = BasicGraphicsUtils.isLeftToRight(tree); redoTheLayout(); tree.treeDidChange(); InputMap km = getInputMap(JComponent.WHEN_FOCUSED); SwingUtilities.replaceUIInputMap(tree, JComponent.WHEN_FOCUSED, km); } } else if ("dropLocation" == changeName) { JTree.DropLocation oldValue = (JTree.DropLocation)event.getOldValue(); repaintDropLocation(oldValue); repaintDropLocation(tree.getDropLocation()); } } } private void repaintDropLocation(JTree.DropLocation loc) { if (loc == null) { return; } Rectangle r; if (isDropLine(loc)) { r = getDropLineRect(loc); } else { r = tree.getPathBounds(loc.getPath()); } if (r != null) { tree.repaint(r); } } // // MouseListener // // Whether or not the mouse press (which is being considered as part // of a drag sequence) also caused the selection change to be fully // processed. private boolean dragPressDidSelection; // Set to true when a drag gesture has been fully recognized and DnD // begins. Use this to ignore further mouse events which could be // delivered if DnD is cancelled (via ESCAPE for example) private boolean dragStarted; // The path over which the press occurred and the press event itself private TreePath pressedPath; private MouseEvent pressedEvent; // Used to detect whether the press event causes a selection change. // If it does, we won't try to start editing on the release. private boolean valueChangedOnPress; private boolean isActualPath(TreePath path, int x, int y) { if (path == null) { return false; } Rectangle bounds = getPathBounds(tree, path); if (y > (bounds.y + bounds.height)) { return false; } return (x >= bounds.x) && (x <= (bounds.x + bounds.width)); } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } /** {@collect.stats} * Invoked when a mouse button has been pressed on a component. */ public void mousePressed(MouseEvent e) { if (SwingUtilities2.shouldIgnore(e, tree)) { return; } // if we can't stop any ongoing editing, do nothing if (isEditing(tree) && tree.getInvokesStopCellEditing() && !stopEditing(tree)) { return; } completeEditing(); pressedPath = getClosestPathForLocation(tree, e.getX(), e.getY()); if (tree.getDragEnabled()) { mousePressedDND(e); } else { SwingUtilities2.adjustFocus(tree); handleSelection(e); } } private void mousePressedDND(MouseEvent e) { pressedEvent = e; boolean grabFocus = true; dragStarted = false; valueChangedOnPress = false; // if we have a valid path and this is a drag initiating event if (isActualPath(pressedPath, e.getX(), e.getY()) && DragRecognitionSupport.mousePressed(e)) { dragPressDidSelection = false; if (e.isControlDown()) { // do nothing for control - will be handled on release // or when drag starts return; } else if (!e.isShiftDown() && tree.isPathSelected(pressedPath)) { // clicking on something that's already selected // and need to make it the lead now setAnchorSelectionPath(pressedPath); setLeadSelectionPath(pressedPath, true); return; } dragPressDidSelection = true; // could be a drag initiating event - don't grab focus grabFocus = false; } if (grabFocus) { SwingUtilities2.adjustFocus(tree); } handleSelection(e); } void handleSelection(MouseEvent e) { if(pressedPath != null) { Rectangle bounds = getPathBounds(tree, pressedPath); if(e.getY() >= (bounds.y + bounds.height)) { return; } // Preferably checkForClickInExpandControl could take // the Event to do this it self! if(SwingUtilities.isLeftMouseButton(e)) { checkForClickInExpandControl(pressedPath, e.getX(), e.getY()); } int x = e.getX(); // Perhaps they clicked the cell itself. If so, // select it. if (x >= bounds.x && x < (bounds.x + bounds.width)) { if (tree.getDragEnabled() || !startEditing(pressedPath, e)) { selectPathForEvent(pressedPath, e); } } } } public void dragStarting(MouseEvent me) { dragStarted = true; if (me.isControlDown()) { tree.addSelectionPath(pressedPath); setAnchorSelectionPath(pressedPath); setLeadSelectionPath(pressedPath, true); } pressedEvent = null; pressedPath = null; } public void mouseDragged(MouseEvent e) { if (SwingUtilities2.shouldIgnore(e, tree)) { return; } if (tree.getDragEnabled()) { DragRecognitionSupport.mouseDragged(e, this); } } /** {@collect.stats} * Invoked when the mouse button has been moved on a component * (with no buttons no down). */ public void mouseMoved(MouseEvent e) { } public void mouseReleased(MouseEvent e) { if (SwingUtilities2.shouldIgnore(e, tree)) { return; } if (tree.getDragEnabled()) { mouseReleasedDND(e); } pressedEvent = null; pressedPath = null; } private void mouseReleasedDND(MouseEvent e) { MouseEvent me = DragRecognitionSupport.mouseReleased(e); if (me != null) { SwingUtilities2.adjustFocus(tree); if (!dragPressDidSelection) { handleSelection(me); } } if (!dragStarted) { // Note: We don't give the tree a chance to start editing if the // mouse press caused a selection change. Otherwise the default // tree cell editor will start editing on EVERY press and // release. If it turns out that this affects some editors, we // can always parameterize this with a client property. ex: // // if (pressedPath != null && // (Boolean.TRUE == tree.getClientProperty("Tree.DnD.canEditOnValueChange") || // !valueChangedOnPress) && ... if (pressedPath != null && !valueChangedOnPress && isActualPath(pressedPath, pressedEvent.getX(), pressedEvent.getY())) { startEditingOnRelease(pressedPath, pressedEvent, e); } } } // // FocusListener // public void focusGained(FocusEvent e) { if(tree != null) { Rectangle pBounds; pBounds = getPathBounds(tree, tree.getLeadSelectionPath()); if(pBounds != null) tree.repaint(getRepaintPathBounds(pBounds)); pBounds = getPathBounds(tree, getLeadSelectionPath()); if(pBounds != null) tree.repaint(getRepaintPathBounds(pBounds)); } } public void focusLost(FocusEvent e) { focusGained(e); } // // CellEditorListener // public void editingStopped(ChangeEvent e) { completeEditing(false, false, true); } /** {@collect.stats} Messaged when editing has been canceled in the tree. */ public void editingCanceled(ChangeEvent e) { completeEditing(false, false, false); } // // TreeSelectionListener // public void valueChanged(TreeSelectionEvent event) { valueChangedOnPress = true; // Stop editing completeEditing(); // Make sure all the paths are visible, if necessary. // PENDING: This should be tweaked when isAdjusting is added if(tree.getExpandsSelectedPaths() && treeSelectionModel != null) { TreePath[] paths = treeSelectionModel .getSelectionPaths(); if(paths != null) { for(int counter = paths.length - 1; counter >= 0; counter--) { TreePath path = paths[counter].getParentPath(); boolean expand = true; while (path != null) { // Indicates this path isn't valid anymore, // we shouldn't attempt to expand it then. if (treeModel.isLeaf(path.getLastPathComponent())){ expand = false; path = null; } else { path = path.getParentPath(); } } if (expand) { tree.makeVisible(paths[counter]); } } } } TreePath oldLead = getLeadSelectionPath(); lastSelectedRow = tree.getMinSelectionRow(); TreePath lead = tree.getSelectionModel().getLeadSelectionPath(); setAnchorSelectionPath(lead); setLeadSelectionPath(lead); TreePath[] changedPaths = event.getPaths(); Rectangle nodeBounds; Rectangle visRect = tree.getVisibleRect(); boolean paintPaths = true; int nWidth = tree.getWidth(); if(changedPaths != null) { int counter, maxCounter = changedPaths.length; if(maxCounter > 4) { tree.repaint(); paintPaths = false; } else { for (counter = 0; counter < maxCounter; counter++) { nodeBounds = getPathBounds(tree, changedPaths[counter]); if(nodeBounds != null && visRect.intersects(nodeBounds)) tree.repaint(0, nodeBounds.y, nWidth, nodeBounds.height); } } } if(paintPaths) { nodeBounds = getPathBounds(tree, oldLead); if(nodeBounds != null && visRect.intersects(nodeBounds)) tree.repaint(0, nodeBounds.y, nWidth, nodeBounds.height); nodeBounds = getPathBounds(tree, lead); if(nodeBounds != null && visRect.intersects(nodeBounds)) tree.repaint(0, nodeBounds.y, nWidth, nodeBounds.height); } } // // TreeExpansionListener // public void treeExpanded(TreeExpansionEvent event) { if(event != null && tree != null) { TreePath path = event.getPath(); updateExpandedDescendants(path); } } public void treeCollapsed(TreeExpansionEvent event) { if(event != null && tree != null) { TreePath path = event.getPath(); completeEditing(); if(path != null && tree.isVisible(path)) { treeState.setExpandedState(path, false); updateLeadRow(); updateSize(); } } } // // TreeModelListener // public void treeNodesChanged(TreeModelEvent e) { if(treeState != null && e != null) { TreePath parentPath = e.getTreePath(); int[] indices = e.getChildIndices(); if (indices == null || indices.length == 0) { // The root has changed treeState.treeNodesChanged(e); updateSize(); } else if (treeState.isExpanded(parentPath)) { // Changed nodes are visible // Find the minimum index, we only need paint from there // down. int minIndex = indices[0]; for (int i = indices.length - 1; i > 0; i--) { minIndex = Math.min(indices[i], minIndex); } Object minChild = treeModel.getChild( parentPath.getLastPathComponent(), minIndex); TreePath minPath = parentPath.pathByAddingChild(minChild); Rectangle minBounds = getPathBounds(tree, minPath); // Forward to the treestate treeState.treeNodesChanged(e); // Mark preferred size as bogus. updateSize0(); // And repaint Rectangle newMinBounds = getPathBounds(tree, minPath); if (indices.length == 1 && newMinBounds.height == minBounds.height) { tree.repaint(0, minBounds.y, tree.getWidth(), minBounds.height); } else { tree.repaint(0, minBounds.y, tree.getWidth(), tree.getHeight() - minBounds.y); } } else { // Nodes that changed aren't visible. No need to paint treeState.treeNodesChanged(e); } } } public void treeNodesInserted(TreeModelEvent e) { if(treeState != null && e != null) { treeState.treeNodesInserted(e); updateLeadRow(); TreePath path = e.getTreePath(); if(treeState.isExpanded(path)) { updateSize(); } else { // PENDING(sky): Need a method in TreeModelEvent // that can return the count, getChildIndices allocs // a new array! int[] indices = e.getChildIndices(); int childCount = treeModel.getChildCount (path.getLastPathComponent()); if(indices != null && (childCount - indices.length) == 0) updateSize(); } } } public void treeNodesRemoved(TreeModelEvent e) { if(treeState != null && e != null) { treeState.treeNodesRemoved(e); updateLeadRow(); TreePath path = e.getTreePath(); if(treeState.isExpanded(path) || treeModel.getChildCount(path.getLastPathComponent()) == 0) updateSize(); } } public void treeStructureChanged(TreeModelEvent e) { if(treeState != null && e != null) { treeState.treeStructureChanged(e); updateLeadRow(); TreePath pPath = e.getTreePath(); if (pPath != null) { pPath = pPath.getParentPath(); } if(pPath == null || treeState.isExpanded(pPath)) updateSize(); } } } private static class Actions extends UIAction { private static final String SELECT_PREVIOUS = "selectPrevious"; private static final String SELECT_PREVIOUS_CHANGE_LEAD = "selectPreviousChangeLead"; private static final String SELECT_PREVIOUS_EXTEND_SELECTION = "selectPreviousExtendSelection"; private static final String SELECT_NEXT = "selectNext"; private static final String SELECT_NEXT_CHANGE_LEAD = "selectNextChangeLead"; private static final String SELECT_NEXT_EXTEND_SELECTION = "selectNextExtendSelection"; private static final String SELECT_CHILD = "selectChild"; private static final String SELECT_CHILD_CHANGE_LEAD = "selectChildChangeLead"; private static final String SELECT_PARENT = "selectParent"; private static final String SELECT_PARENT_CHANGE_LEAD = "selectParentChangeLead"; private static final String SCROLL_UP_CHANGE_SELECTION = "scrollUpChangeSelection"; private static final String SCROLL_UP_CHANGE_LEAD = "scrollUpChangeLead"; private static final String SCROLL_UP_EXTEND_SELECTION = "scrollUpExtendSelection"; private static final String SCROLL_DOWN_CHANGE_SELECTION = "scrollDownChangeSelection"; private static final String SCROLL_DOWN_EXTEND_SELECTION = "scrollDownExtendSelection"; private static final String SCROLL_DOWN_CHANGE_LEAD = "scrollDownChangeLead"; private static final String SELECT_FIRST = "selectFirst"; private static final String SELECT_FIRST_CHANGE_LEAD = "selectFirstChangeLead"; private static final String SELECT_FIRST_EXTEND_SELECTION = "selectFirstExtendSelection"; private static final String SELECT_LAST = "selectLast"; private static final String SELECT_LAST_CHANGE_LEAD = "selectLastChangeLead"; private static final String SELECT_LAST_EXTEND_SELECTION = "selectLastExtendSelection"; private static final String TOGGLE = "toggle"; private static final String CANCEL_EDITING = "cancel"; private static final String START_EDITING = "startEditing"; private static final String SELECT_ALL = "selectAll"; private static final String CLEAR_SELECTION = "clearSelection"; private static final String SCROLL_LEFT = "scrollLeft"; private static final String SCROLL_RIGHT = "scrollRight"; private static final String SCROLL_LEFT_EXTEND_SELECTION = "scrollLeftExtendSelection"; private static final String SCROLL_RIGHT_EXTEND_SELECTION = "scrollRightExtendSelection"; private static final String SCROLL_RIGHT_CHANGE_LEAD = "scrollRightChangeLead"; private static final String SCROLL_LEFT_CHANGE_LEAD = "scrollLeftChangeLead"; private static final String EXPAND = "expand"; private static final String COLLAPSE = "collapse"; private static final String MOVE_SELECTION_TO_PARENT = "moveSelectionToParent"; // add the lead item to the selection without changing lead or anchor private static final String ADD_TO_SELECTION = "addToSelection"; // toggle the selected state of the lead item and move the anchor to it private static final String TOGGLE_AND_ANCHOR = "toggleAndAnchor"; // extend the selection to the lead item private static final String EXTEND_TO = "extendTo"; // move the anchor to the lead and ensure only that item is selected private static final String MOVE_SELECTION_TO = "moveSelectionTo"; Actions() { super(null); } Actions(String key) { super(key); } public boolean isEnabled(Object o) { if (o instanceof JTree) { if (getName() == CANCEL_EDITING) { return ((JTree)o).isEditing(); } } return true; } public void actionPerformed(ActionEvent e) { JTree tree = (JTree)e.getSource(); BasicTreeUI ui = (BasicTreeUI)BasicLookAndFeel.getUIOfType( tree.getUI(), BasicTreeUI.class); if (ui == null) { return; } String key = getName(); if (key == SELECT_PREVIOUS) { increment(tree, ui, -1, false, true); } else if (key == SELECT_PREVIOUS_CHANGE_LEAD) { increment(tree, ui, -1, false, false); } else if (key == SELECT_PREVIOUS_EXTEND_SELECTION) { increment(tree, ui, -1, true, true); } else if (key == SELECT_NEXT) { increment(tree, ui, 1, false, true); } else if (key == SELECT_NEXT_CHANGE_LEAD) { increment(tree, ui, 1, false, false); } else if (key == SELECT_NEXT_EXTEND_SELECTION) { increment(tree, ui, 1, true, true); } else if (key == SELECT_CHILD) { traverse(tree, ui, 1, true); } else if (key == SELECT_CHILD_CHANGE_LEAD) { traverse(tree, ui, 1, false); } else if (key == SELECT_PARENT) { traverse(tree, ui, -1, true); } else if (key == SELECT_PARENT_CHANGE_LEAD) { traverse(tree, ui, -1, false); } else if (key == SCROLL_UP_CHANGE_SELECTION) { page(tree, ui, -1, false, true); } else if (key == SCROLL_UP_CHANGE_LEAD) { page(tree, ui, -1, false, false); } else if (key == SCROLL_UP_EXTEND_SELECTION) { page(tree, ui, -1, true, true); } else if (key == SCROLL_DOWN_CHANGE_SELECTION) { page(tree, ui, 1, false, true); } else if (key == SCROLL_DOWN_EXTEND_SELECTION) { page(tree, ui, 1, true, true); } else if (key == SCROLL_DOWN_CHANGE_LEAD) { page(tree, ui, 1, false, false); } else if (key == SELECT_FIRST) { home(tree, ui, -1, false, true); } else if (key == SELECT_FIRST_CHANGE_LEAD) { home(tree, ui, -1, false, false); } else if (key == SELECT_FIRST_EXTEND_SELECTION) { home(tree, ui, -1, true, true); } else if (key == SELECT_LAST) { home(tree, ui, 1, false, true); } else if (key == SELECT_LAST_CHANGE_LEAD) { home(tree, ui, 1, false, false); } else if (key == SELECT_LAST_EXTEND_SELECTION) { home(tree, ui, 1, true, true); } else if (key == TOGGLE) { toggle(tree, ui); } else if (key == CANCEL_EDITING) { cancelEditing(tree, ui); } else if (key == START_EDITING) { startEditing(tree, ui); } else if (key == SELECT_ALL) { selectAll(tree, ui, true); } else if (key == CLEAR_SELECTION) { selectAll(tree, ui, false); } else if (key == ADD_TO_SELECTION) { if (ui.getRowCount(tree) > 0) { int lead = ui.getLeadSelectionRow(); if (!tree.isRowSelected(lead)) { TreePath aPath = ui.getAnchorSelectionPath(); tree.addSelectionRow(lead); ui.setAnchorSelectionPath(aPath); } } } else if (key == TOGGLE_AND_ANCHOR) { if (ui.getRowCount(tree) > 0) { int lead = ui.getLeadSelectionRow(); TreePath lPath = ui.getLeadSelectionPath(); if (!tree.isRowSelected(lead)) { tree.addSelectionRow(lead); } else { tree.removeSelectionRow(lead); ui.setLeadSelectionPath(lPath); } ui.setAnchorSelectionPath(lPath); } } else if (key == EXTEND_TO) { extendSelection(tree, ui); } else if (key == MOVE_SELECTION_TO) { if (ui.getRowCount(tree) > 0) { int lead = ui.getLeadSelectionRow(); tree.setSelectionInterval(lead, lead); } } else if (key == SCROLL_LEFT) { scroll(tree, ui, SwingConstants.HORIZONTAL, -10); } else if (key == SCROLL_RIGHT) { scroll(tree, ui, SwingConstants.HORIZONTAL, 10); } else if (key == SCROLL_LEFT_EXTEND_SELECTION) { scrollChangeSelection(tree, ui, -1, true, true); } else if (key == SCROLL_RIGHT_EXTEND_SELECTION) { scrollChangeSelection(tree, ui, 1, true, true); } else if (key == SCROLL_RIGHT_CHANGE_LEAD) { scrollChangeSelection(tree, ui, 1, false, false); } else if (key == SCROLL_LEFT_CHANGE_LEAD) { scrollChangeSelection(tree, ui, -1, false, false); } else if (key == EXPAND) { expand(tree, ui); } else if (key == COLLAPSE) { collapse(tree, ui); } else if (key == MOVE_SELECTION_TO_PARENT) { moveSelectionToParent(tree, ui); } } private void scrollChangeSelection(JTree tree, BasicTreeUI ui, int direction, boolean addToSelection, boolean changeSelection) { int rowCount; if((rowCount = ui.getRowCount(tree)) > 0 && ui.treeSelectionModel != null) { TreePath newPath; Rectangle visRect = tree.getVisibleRect(); if (direction == -1) { newPath = ui.getClosestPathForLocation(tree, visRect.x, visRect.y); visRect.x = Math.max(0, visRect.x - visRect.width); } else { visRect.x = Math.min(Math.max(0, tree.getWidth() - visRect.width), visRect.x + visRect.width); newPath = ui.getClosestPathForLocation(tree, visRect.x, visRect.y + visRect.height); } // Scroll tree.scrollRectToVisible(visRect); // select if (addToSelection) { ui.extendSelection(newPath); } else if(changeSelection) { tree.setSelectionPath(newPath); } else { ui.setLeadSelectionPath(newPath, true); } } } private void scroll(JTree component, BasicTreeUI ui, int direction, int amount) { Rectangle visRect = component.getVisibleRect(); Dimension size = component.getSize(); if (direction == SwingConstants.HORIZONTAL) { visRect.x += amount; visRect.x = Math.max(0, visRect.x); visRect.x = Math.min(Math.max(0, size.width - visRect.width), visRect.x); } else { visRect.y += amount; visRect.y = Math.max(0, visRect.y); visRect.y = Math.min(Math.max(0, size.width - visRect.height), visRect.y); } component.scrollRectToVisible(visRect); } private void extendSelection(JTree tree, BasicTreeUI ui) { if (ui.getRowCount(tree) > 0) { int lead = ui.getLeadSelectionRow(); if (lead != -1) { TreePath leadP = ui.getLeadSelectionPath(); TreePath aPath = ui.getAnchorSelectionPath(); int aRow = ui.getRowForPath(tree, aPath); if(aRow == -1) aRow = 0; tree.setSelectionInterval(aRow, lead); ui.setLeadSelectionPath(leadP); ui.setAnchorSelectionPath(aPath); } } } private void selectAll(JTree tree, BasicTreeUI ui, boolean selectAll) { int rowCount = ui.getRowCount(tree); if(rowCount > 0) { if(selectAll) { if (tree.getSelectionModel().getSelectionMode() == TreeSelectionModel.SINGLE_TREE_SELECTION) { int lead = ui.getLeadSelectionRow(); if (lead != -1) { tree.setSelectionRow(lead); } else if (tree.getMinSelectionRow() == -1) { tree.setSelectionRow(0); ui.ensureRowsAreVisible(0, 0); } return; } TreePath lastPath = ui.getLeadSelectionPath(); TreePath aPath = ui.getAnchorSelectionPath(); if(lastPath != null && !tree.isVisible(lastPath)) { lastPath = null; } tree.setSelectionInterval(0, rowCount - 1); if(lastPath != null) { ui.setLeadSelectionPath(lastPath); } if(aPath != null && tree.isVisible(aPath)) { ui.setAnchorSelectionPath(aPath); } } else { TreePath lastPath = ui.getLeadSelectionPath(); TreePath aPath = ui.getAnchorSelectionPath(); tree.clearSelection(); ui.setAnchorSelectionPath(aPath); ui.setLeadSelectionPath(lastPath); } } } private void startEditing(JTree tree, BasicTreeUI ui) { TreePath lead = ui.getLeadSelectionPath(); int editRow = (lead != null) ? ui.getRowForPath(tree, lead) : -1; if(editRow != -1) { tree.startEditingAtPath(lead); } } private void cancelEditing(JTree tree, BasicTreeUI ui) { tree.cancelEditing(); } private void toggle(JTree tree, BasicTreeUI ui) { int selRow = ui.getLeadSelectionRow(); if(selRow != -1 && !ui.isLeaf(selRow)) { TreePath aPath = ui.getAnchorSelectionPath(); TreePath lPath = ui.getLeadSelectionPath(); ui.toggleExpandState(ui.getPathForRow(tree, selRow)); ui.setAnchorSelectionPath(aPath); ui.setLeadSelectionPath(lPath); } } private void expand(JTree tree, BasicTreeUI ui) { int selRow = ui.getLeadSelectionRow(); tree.expandRow(selRow); } private void collapse(JTree tree, BasicTreeUI ui) { int selRow = ui.getLeadSelectionRow(); tree.collapseRow(selRow); } private void increment(JTree tree, BasicTreeUI ui, int direction, boolean addToSelection, boolean changeSelection) { // disable moving of lead unless in discontiguous mode if (!addToSelection && !changeSelection && tree.getSelectionModel().getSelectionMode() != TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION) { changeSelection = true; } int rowCount; if(ui.treeSelectionModel != null && (rowCount = tree.getRowCount()) > 0) { int selIndex = ui.getLeadSelectionRow(); int newIndex; if(selIndex == -1) { if(direction == 1) newIndex = 0; else newIndex = rowCount - 1; } else /* Aparently people don't like wrapping;( */ newIndex = Math.min(rowCount - 1, Math.max (0, (selIndex + direction))); if(addToSelection && ui.treeSelectionModel. getSelectionMode() != TreeSelectionModel. SINGLE_TREE_SELECTION) { ui.extendSelection(tree.getPathForRow(newIndex)); } else if(changeSelection) { tree.setSelectionInterval(newIndex, newIndex); } else { ui.setLeadSelectionPath(tree.getPathForRow(newIndex),true); } ui.ensureRowsAreVisible(newIndex, newIndex); ui.lastSelectedRow = newIndex; } } private void traverse(JTree tree, BasicTreeUI ui, int direction, boolean changeSelection) { // disable moving of lead unless in discontiguous mode if (!changeSelection && tree.getSelectionModel().getSelectionMode() != TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION) { changeSelection = true; } int rowCount; if((rowCount = tree.getRowCount()) > 0) { int minSelIndex = ui.getLeadSelectionRow(); int newIndex; if(minSelIndex == -1) newIndex = 0; else { /* Try and expand the node, otherwise go to next node. */ if(direction == 1) { TreePath minSelPath = ui.getPathForRow(tree, minSelIndex); int childCount = tree.getModel(). getChildCount(minSelPath.getLastPathComponent()); newIndex = -1; if (!ui.isLeaf(minSelIndex)) { if (!tree.isExpanded(minSelIndex)) { ui.toggleExpandState(minSelPath); } else if (childCount > 0) { newIndex = Math.min(minSelIndex + 1, rowCount - 1); } } } /* Try to collapse node. */ else { if(!ui.isLeaf(minSelIndex) && tree.isExpanded(minSelIndex)) { ui.toggleExpandState(ui.getPathForRow (tree, minSelIndex)); newIndex = -1; } else { TreePath path = ui.getPathForRow(tree, minSelIndex); if(path != null && path.getPathCount() > 1) { newIndex = ui.getRowForPath(tree, path. getParentPath()); } else newIndex = -1; } } } if(newIndex != -1) { if(changeSelection) { tree.setSelectionInterval(newIndex, newIndex); } else { ui.setLeadSelectionPath(ui.getPathForRow( tree, newIndex), true); } ui.ensureRowsAreVisible(newIndex, newIndex); } } } private void moveSelectionToParent(JTree tree, BasicTreeUI ui) { int selRow = ui.getLeadSelectionRow(); TreePath path = ui.getPathForRow(tree, selRow); if (path != null && path.getPathCount() > 1) { int newIndex = ui.getRowForPath(tree, path.getParentPath()); if (newIndex != -1) { tree.setSelectionInterval(newIndex, newIndex); ui.ensureRowsAreVisible(newIndex, newIndex); } } } private void page(JTree tree, BasicTreeUI ui, int direction, boolean addToSelection, boolean changeSelection) { // disable moving of lead unless in discontiguous mode if (!addToSelection && !changeSelection && tree.getSelectionModel().getSelectionMode() != TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION) { changeSelection = true; } int rowCount; if((rowCount = ui.getRowCount(tree)) > 0 && ui.treeSelectionModel != null) { Dimension maxSize = tree.getSize(); TreePath lead = ui.getLeadSelectionPath(); TreePath newPath; Rectangle visRect = tree.getVisibleRect(); if(direction == -1) { // up. newPath = ui.getClosestPathForLocation(tree, visRect.x, visRect.y); if(newPath.equals(lead)) { visRect.y = Math.max(0, visRect.y - visRect.height); newPath = tree.getClosestPathForLocation(visRect.x, visRect.y); } } else { // down visRect.y = Math.min(maxSize.height, visRect.y + visRect.height - 1); newPath = tree.getClosestPathForLocation(visRect.x, visRect.y); if(newPath.equals(lead)) { visRect.y = Math.min(maxSize.height, visRect.y + visRect.height - 1); newPath = tree.getClosestPathForLocation(visRect.x, visRect.y); } } Rectangle newRect = ui.getPathBounds(tree, newPath); newRect.x = visRect.x; newRect.width = visRect.width; if(direction == -1) { newRect.height = visRect.height; } else { newRect.y -= (visRect.height - newRect.height); newRect.height = visRect.height; } if(addToSelection) { ui.extendSelection(newPath); } else if(changeSelection) { tree.setSelectionPath(newPath); } else { ui.setLeadSelectionPath(newPath, true); } tree.scrollRectToVisible(newRect); } } private void home(JTree tree, BasicTreeUI ui, int direction, boolean addToSelection, boolean changeSelection) { // disable moving of lead unless in discontiguous mode if (!addToSelection && !changeSelection && tree.getSelectionModel().getSelectionMode() != TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION) { changeSelection = true; } int rowCount = ui.getRowCount(tree); if (rowCount > 0) { if(direction == -1) { ui.ensureRowsAreVisible(0, 0); if (addToSelection) { TreePath aPath = ui.getAnchorSelectionPath(); int aRow = (aPath == null) ? -1 : ui.getRowForPath(tree, aPath); if (aRow == -1) { tree.setSelectionInterval(0, 0); } else { tree.setSelectionInterval(0, aRow); ui.setAnchorSelectionPath(aPath); ui.setLeadSelectionPath(ui.getPathForRow(tree, 0)); } } else if(changeSelection) { tree.setSelectionInterval(0, 0); } else { ui.setLeadSelectionPath(ui.getPathForRow(tree, 0), true); } } else { ui.ensureRowsAreVisible(rowCount - 1, rowCount - 1); if (addToSelection) { TreePath aPath = ui.getAnchorSelectionPath(); int aRow = (aPath == null) ? -1 : ui.getRowForPath(tree, aPath); if (aRow == -1) { tree.setSelectionInterval(rowCount - 1, rowCount -1); } else { tree.setSelectionInterval(aRow, rowCount - 1); ui.setAnchorSelectionPath(aPath); ui.setLeadSelectionPath(ui.getPathForRow(tree, rowCount -1)); } } else if(changeSelection) { tree.setSelectionInterval(rowCount - 1, rowCount - 1); } else { ui.setLeadSelectionPath(ui.getPathForRow(tree, rowCount - 1), true); } } } } } } // End of class BasicTreeUI
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.swing.*; import javax.swing.border.*; import javax.swing.plaf.*; import javax.swing.text.JTextComponent; import java.awt.Component; import java.awt.Insets; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Color; import java.awt.Graphics; import java.io.Serializable; /** {@collect.stats} * Factory object that can vend Borders appropriate for the basic L & F. * @author Georges Saab * @author Amy Fowler */ public class BasicBorders { public static Border getButtonBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border buttonBorder = new BorderUIResource.CompoundBorderUIResource( new BasicBorders.ButtonBorder( table.getColor("Button.shadow"), table.getColor("Button.darkShadow"), table.getColor("Button.light"), table.getColor("Button.highlight")), new MarginBorder()); return buttonBorder; } public static Border getRadioButtonBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border radioButtonBorder = new BorderUIResource.CompoundBorderUIResource( new BasicBorders.RadioButtonBorder( table.getColor("RadioButton.shadow"), table.getColor("RadioButton.darkShadow"), table.getColor("RadioButton.light"), table.getColor("RadioButton.highlight")), new MarginBorder()); return radioButtonBorder; } public static Border getToggleButtonBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border toggleButtonBorder = new BorderUIResource.CompoundBorderUIResource( new BasicBorders.ToggleButtonBorder( table.getColor("ToggleButton.shadow"), table.getColor("ToggleButton.darkShadow"), table.getColor("ToggleButton.light"), table.getColor("ToggleButton.highlight")), new MarginBorder()); return toggleButtonBorder; } public static Border getMenuBarBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border menuBarBorder = new BasicBorders.MenuBarBorder( table.getColor("MenuBar.shadow"), table.getColor("MenuBar.highlight") ); return menuBarBorder; } public static Border getSplitPaneBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border splitPaneBorder = new BasicBorders.SplitPaneBorder( table.getColor("SplitPane.highlight"), table.getColor("SplitPane.darkShadow")); return splitPaneBorder; } /** {@collect.stats} * Returns a border instance for a JSplitPane divider * @since 1.3 */ public static Border getSplitPaneDividerBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border splitPaneBorder = new BasicBorders.SplitPaneDividerBorder( table.getColor("SplitPane.highlight"), table.getColor("SplitPane.darkShadow")); return splitPaneBorder; } public static Border getTextFieldBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border textFieldBorder = new BasicBorders.FieldBorder( table.getColor("TextField.shadow"), table.getColor("TextField.darkShadow"), table.getColor("TextField.light"), table.getColor("TextField.highlight")); return textFieldBorder; } public static Border getProgressBarBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border progressBarBorder = new BorderUIResource.LineBorderUIResource(Color.green, 2); return progressBarBorder; } public static Border getInternalFrameBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); Border internalFrameBorder = new BorderUIResource.CompoundBorderUIResource( new BevelBorder(BevelBorder.RAISED, table.getColor("InternalFrame.borderLight"), table.getColor("InternalFrame.borderHighlight"), table.getColor("InternalFrame.borderDarkShadow"), table.getColor("InternalFrame.borderShadow")), BorderFactory.createLineBorder( table.getColor("InternalFrame.borderColor"), 1)); return internalFrameBorder; } /** {@collect.stats} * Special thin border for rollover toolbar buttons. * @since 1.4 */ public static class RolloverButtonBorder extends ButtonBorder { public RolloverButtonBorder(Color shadow, Color darkShadow, Color highlight, Color lightHighlight) { super(shadow, darkShadow, highlight, lightHighlight); } public void paintBorder( Component c, Graphics g, int x, int y, int w, int h ) { AbstractButton b = (AbstractButton) c; ButtonModel model = b.getModel(); Color shade = shadow; Component p = b.getParent(); if (p != null && p.getBackground().equals(shadow)) { shade = darkShadow; } if ((model.isRollover() && !(model.isPressed() && !model.isArmed())) || model.isSelected()) { Color oldColor = g.getColor(); g.translate(x, y); if (model.isPressed() && model.isArmed() || model.isSelected()) { // Draw the pressd button g.setColor(shade); g.drawRect(0, 0, w-1, h-1); g.setColor(lightHighlight); g.drawLine(w-1, 0, w-1, h-1); g.drawLine(0, h-1, w-1, h-1); } else { // Draw a rollover button g.setColor(lightHighlight); g.drawRect(0, 0, w-1, h-1); g.setColor(shade); g.drawLine(w-1, 0, w-1, h-1); g.drawLine(0, h-1, w-1, h-1); } g.translate(-x, -y); g.setColor(oldColor); } } } /** {@collect.stats} * A border which is like a Margin border but it will only honor the margin * if the margin has been explicitly set by the developer. * * Note: This is identical to the package private class * MetalBorders.RolloverMarginBorder and should probably be consolidated. */ static class RolloverMarginBorder extends EmptyBorder { public RolloverMarginBorder() { super(3,3,3,3); // hardcoded margin for JLF requirements. } public Insets getBorderInsets(Component c) { return getBorderInsets(c, new Insets(0,0,0,0)); } public Insets getBorderInsets(Component c, Insets insets) { Insets margin = null; if (c instanceof AbstractButton) { margin = ((AbstractButton)c).getMargin(); } if (margin == null || margin instanceof UIResource) { // default margin so replace insets.left = left; insets.top = top; insets.right = right; insets.bottom = bottom; } else { // Margin which has been explicitly set by the user. insets.left = margin.left; insets.top = margin.top; insets.right = margin.right; insets.bottom = margin.bottom; } return insets; } } public static class ButtonBorder extends AbstractBorder implements UIResource { protected Color shadow; protected Color darkShadow; protected Color highlight; protected Color lightHighlight; public ButtonBorder(Color shadow, Color darkShadow, Color highlight, Color lightHighlight) { this.shadow = shadow; this.darkShadow = darkShadow; this.highlight = highlight; this.lightHighlight = lightHighlight; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { boolean isPressed = false; boolean isDefault = false; if (c instanceof AbstractButton) { AbstractButton b = (AbstractButton)c; ButtonModel model = b.getModel(); isPressed = model.isPressed() && model.isArmed(); if (c instanceof JButton) { isDefault = ((JButton)c).isDefaultButton(); } } BasicGraphicsUtils.drawBezel(g, x, y, width, height, isPressed, isDefault, shadow, darkShadow, highlight, lightHighlight); } public Insets getBorderInsets(Component c) { return getBorderInsets(c, new Insets(0,0,0,0)); } public Insets getBorderInsets(Component c, Insets insets) { // leave room for default visual insets.top = 2; insets.left = insets.bottom = insets.right = 3; return insets; } } public static class ToggleButtonBorder extends ButtonBorder { public ToggleButtonBorder(Color shadow, Color darkShadow, Color highlight, Color lightHighlight) { super(shadow, darkShadow, highlight, lightHighlight); } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { BasicGraphicsUtils.drawBezel(g, x, y, width, height, false, false, shadow, darkShadow, highlight, lightHighlight); } public Insets getBorderInsets(Component c) { return new Insets(2, 2, 2, 2); } public Insets getBorderInsets(Component c, Insets insets) { insets.top = insets.left = insets.bottom = insets.right = 2; return insets; } } public static class RadioButtonBorder extends ButtonBorder { public RadioButtonBorder(Color shadow, Color darkShadow, Color highlight, Color lightHighlight) { super(shadow, darkShadow, highlight, lightHighlight); } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { if (c instanceof AbstractButton) { AbstractButton b = (AbstractButton)c; ButtonModel model = b.getModel(); if (model.isArmed() && model.isPressed() || model.isSelected()) { BasicGraphicsUtils.drawLoweredBezel(g, x, y, width, height, shadow, darkShadow, highlight, lightHighlight); } else { BasicGraphicsUtils.drawBezel(g, x, y, width, height, false, b.isFocusPainted() && b.hasFocus(), shadow, darkShadow, highlight, lightHighlight); } } else { BasicGraphicsUtils.drawBezel(g, x, y, width, height, false, false, shadow, darkShadow, highlight, lightHighlight); } } public Insets getBorderInsets(Component c) { return getBorderInsets(c, new Insets(0,0,0,0)); } public Insets getBorderInsets(Component c, Insets insets) { insets.top = insets.left = insets.bottom = insets.right = 2; return insets; } } public static class MenuBarBorder extends AbstractBorder implements UIResource { private Color shadow; private Color highlight; public MenuBarBorder(Color shadow, Color highlight) { this.shadow = shadow; this.highlight = highlight; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Color oldColor = g.getColor(); g.translate(x, y); g.setColor(shadow); g.drawLine(0, height-2, width, height-2); g.setColor(highlight); g.drawLine(0, height-1, width, height-1); g.translate(-x,-y); g.setColor(oldColor); } public Insets getBorderInsets(Component c) { return getBorderInsets(c, new Insets(0,0,0,0)); } public Insets getBorderInsets(Component c, Insets insets) { insets.top = 0; insets.left = 0; insets.bottom = 2; insets.right = 0; return insets; } } public static class MarginBorder extends AbstractBorder implements UIResource { public Insets getBorderInsets(Component c) { return getBorderInsets(c, new Insets(0,0,0,0)); } public Insets getBorderInsets(Component c, Insets insets) { Insets margin = null; // // Ideally we'd have an interface defined for classes which // support margins (to avoid this hackery), but we've // decided against it for simplicity // if (c instanceof AbstractButton) { AbstractButton b = (AbstractButton)c; margin = b.getMargin(); } else if (c instanceof JToolBar) { JToolBar t = (JToolBar)c; margin = t.getMargin(); } else if (c instanceof JTextComponent) { JTextComponent t = (JTextComponent)c; margin = t.getMargin(); } insets.top = margin != null? margin.top : 0; insets.left = margin != null? margin.left : 0; insets.bottom = margin != null? margin.bottom : 0; insets.right = margin != null? margin.right : 0; return insets; } } public static class FieldBorder extends AbstractBorder implements UIResource { protected Color shadow; protected Color darkShadow; protected Color highlight; protected Color lightHighlight; public FieldBorder(Color shadow, Color darkShadow, Color highlight, Color lightHighlight) { this.shadow = shadow; this.highlight = highlight; this.darkShadow = darkShadow; this.lightHighlight = lightHighlight; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { BasicGraphicsUtils.drawEtchedRect(g, x, y, width, height, shadow, darkShadow, highlight, lightHighlight); } public Insets getBorderInsets(Component c) { return getBorderInsets(c, new Insets(0,0,0,0)); } public Insets getBorderInsets(Component c, Insets insets) { Insets margin = null; if (c instanceof JTextComponent) { margin = ((JTextComponent)c).getMargin(); } insets.top = margin != null? 2+margin.top : 2; insets.left = margin != null? 2+margin.left : 2; insets.bottom = margin != null? 2+margin.bottom : 2; insets.right = margin != null? 2+margin.right : 2; return insets; } } /** {@collect.stats} * Draws the border around the divider in a splitpane * (when BasicSplitPaneUI is used). To get the appropriate effect, this * needs to be used with a SplitPaneBorder. */ static class SplitPaneDividerBorder implements Border, UIResource { Color highlight; Color shadow; SplitPaneDividerBorder(Color highlight, Color shadow) { this.highlight = highlight; this.shadow = shadow; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Component child; Rectangle cBounds; JSplitPane splitPane = ((BasicSplitPaneDivider)c). getBasicSplitPaneUI().getSplitPane(); Dimension size = c.getSize(); child = splitPane.getLeftComponent(); // This is needed for the space between the divider and end of // splitpane. g.setColor(c.getBackground()); g.drawRect(x, y, width - 1, height - 1); if(splitPane.getOrientation() == JSplitPane.HORIZONTAL_SPLIT) { if(child != null) { g.setColor(highlight); g.drawLine(0, 0, 0, size.height); } child = splitPane.getRightComponent(); if(child != null) { g.setColor(shadow); g.drawLine(size.width - 1, 0, size.width - 1, size.height); } } else { if(child != null) { g.setColor(highlight); g.drawLine(0, 0, size.width, 0); } child = splitPane.getRightComponent(); if(child != null) { g.setColor(shadow); g.drawLine(0, size.height - 1, size.width, size.height - 1); } } } public Insets getBorderInsets(Component c) { Insets insets = new Insets(0,0,0,0); if (c instanceof BasicSplitPaneDivider) { BasicSplitPaneUI bspui = ((BasicSplitPaneDivider)c). getBasicSplitPaneUI(); if (bspui != null) { JSplitPane splitPane = bspui.getSplitPane(); if (splitPane != null) { if (splitPane.getOrientation() == JSplitPane.HORIZONTAL_SPLIT) { insets.top = insets.bottom = 0; insets.left = insets.right = 1; return insets; } // VERTICAL_SPLIT insets.top = insets.bottom = 1; insets.left = insets.right = 0; return insets; } } } insets.top = insets.bottom = insets.left = insets.right = 1; return insets; } public boolean isBorderOpaque() { return true; } } /** {@collect.stats} * Draws the border around the splitpane. To work correctly you shoudl * also install a border on the divider (property SplitPaneDivider.border). */ public static class SplitPaneBorder implements Border, UIResource { protected Color highlight; protected Color shadow; public SplitPaneBorder(Color highlight, Color shadow) { this.highlight = highlight; this.shadow = shadow; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { // The only tricky part with this border is that the divider is // not positioned at the top (for horizontal) or left (for vert), // so this border draws to where the divider is: // ----------------- // |xxxxxxx xxxxxxx| // |x --- x| // |x | | x| // |x |D| x| // |x | | x| // |x --- x| // |xxxxxxx xxxxxxx| // ----------------- // The above shows (rather excessively) what this looks like for // a horizontal orientation. This border then draws the x's, with // the SplitPaneDividerBorder drawing its own border. Component child; Rectangle cBounds; JSplitPane splitPane = (JSplitPane)c; child = splitPane.getLeftComponent(); // This is needed for the space between the divider and end of // splitpane. g.setColor(c.getBackground()); g.drawRect(x, y, width - 1, height - 1); if(splitPane.getOrientation() == JSplitPane.HORIZONTAL_SPLIT) { if(child != null) { cBounds = child.getBounds(); g.setColor(shadow); g.drawLine(0, 0, cBounds.width + 1, 0); g.drawLine(0, 1, 0, cBounds.height + 1); g.setColor(highlight); g.drawLine(0, cBounds.height + 1, cBounds.width + 1, cBounds.height + 1); } child = splitPane.getRightComponent(); if(child != null) { cBounds = child.getBounds(); int maxX = cBounds.x + cBounds.width; int maxY = cBounds.y + cBounds.height; g.setColor(shadow); g.drawLine(cBounds.x - 1, 0, maxX, 0); g.setColor(highlight); g.drawLine(cBounds.x - 1, maxY, maxX, maxY); g.drawLine(maxX, 0, maxX, maxY + 1); } } else { if(child != null) { cBounds = child.getBounds(); g.setColor(shadow); g.drawLine(0, 0, cBounds.width + 1, 0); g.drawLine(0, 1, 0, cBounds.height); g.setColor(highlight); g.drawLine(1 + cBounds.width, 0, 1 + cBounds.width, cBounds.height + 1); g.drawLine(0, cBounds.height + 1, 0, cBounds.height + 1); } child = splitPane.getRightComponent(); if(child != null) { cBounds = child.getBounds(); int maxX = cBounds.x + cBounds.width; int maxY = cBounds.y + cBounds.height; g.setColor(shadow); g.drawLine(0, cBounds.y - 1, 0, maxY); g.drawLine(maxX, cBounds.y - 1, maxX, cBounds.y - 1); g.setColor(highlight); g.drawLine(0, maxY, cBounds.width + 1, maxY); g.drawLine(maxX, cBounds.y, maxX, maxY); } } } public Insets getBorderInsets(Component c) { return new Insets(1, 1, 1, 1); } public boolean isBorderOpaque() { return true; } } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.FocusEvent; import java.awt.event.InputEvent; import java.beans.PropertyChangeEvent; import java.io.Reader; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import javax.swing.text.*; import javax.swing.plaf.*; import sun.swing.DefaultLookup; /** {@collect.stats} * Basis of a look and feel for a JTextField. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Timothy Prinzing */ public class BasicTextFieldUI extends BasicTextUI { /** {@collect.stats} * Creates a UI for a JTextField. * * @param c the text field * @return the UI */ public static ComponentUI createUI(JComponent c) { return new BasicTextFieldUI(); } /** {@collect.stats} * Creates a new BasicTextFieldUI. */ public BasicTextFieldUI() { super(); } /** {@collect.stats} * Fetches the name used as a key to lookup properties through the * UIManager. This is used as a prefix to all the standard * text properties. * * @return the name ("TextField") */ protected String getPropertyPrefix() { return "TextField"; } /** {@collect.stats} * Creates a view (FieldView) based on an element. * * @param elem the element * @return the view */ public View create(Element elem) { Document doc = elem.getDocument(); Object i18nFlag = doc.getProperty("i18n"/*AbstractDocument.I18NProperty*/); if (Boolean.TRUE.equals(i18nFlag)) { // To support bidirectional text, we build a more heavyweight // representation of the field. String kind = elem.getName(); if (kind != null) { if (kind.equals(AbstractDocument.ContentElementName)) { return new GlyphView(elem); } else if (kind.equals(AbstractDocument.ParagraphElementName)) { return new I18nFieldView(elem); } } // this shouldn't happen, should probably throw in this case. } return new FieldView(elem); } /** {@collect.stats} * Returns the baseline. * * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public int getBaseline(JComponent c, int width, int height) { super.getBaseline(c, width, height); View rootView = getRootView((JTextComponent)c); if (rootView.getViewCount() > 0) { Insets insets = c.getInsets(); height = height - insets.top - insets.bottom; if (height > 0) { int baseline = insets.top; View fieldView = rootView.getView(0); int vspan = (int)fieldView.getPreferredSpan(View.Y_AXIS); if (height != vspan) { int slop = height - vspan; baseline += slop / 2; } if (fieldView instanceof I18nFieldView) { int fieldBaseline = BasicHTML.getBaseline( fieldView, width - insets.left - insets.right, height); if (fieldBaseline < 0) { return -1; } baseline += fieldBaseline; } else { FontMetrics fm = c.getFontMetrics(c.getFont()); baseline += fm.getAscent(); } return baseline; } } return -1; } /** {@collect.stats} * Returns an enum indicating how the baseline of the component * changes as the size changes. * * @throws NullPointerException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public Component.BaselineResizeBehavior getBaselineResizeBehavior( JComponent c) { super.getBaselineResizeBehavior(c); return Component.BaselineResizeBehavior.CENTER_OFFSET; } /** {@collect.stats} * A field view that support bidirectional text via the * support provided by ParagraphView. */ static class I18nFieldView extends ParagraphView { I18nFieldView(Element elem) { super(elem); } /** {@collect.stats} * Fetch the constraining span to flow against for * the given child index. There is no limit for * a field since it scrolls, so this is implemented to * return <code>Integer.MAX_VALUE</code>. */ public int getFlowSpan(int index) { return Integer.MAX_VALUE; } protected void setJustification(int j) { // Justification is done in adjustAllocation(), so disable // ParagraphView's justification handling by doing nothing here. } static boolean isLeftToRight( java.awt.Component c ) { return c.getComponentOrientation().isLeftToRight(); } /** {@collect.stats} * Adjusts the allocation given to the view * to be a suitable allocation for a text field. * If the view has been allocated more than the * preferred span vertically, the allocation is * changed to be centered vertically. Horizontally * the view is adjusted according to the horizontal * alignment property set on the associated JTextField * (if that is the type of the hosting component). * * @param a the allocation given to the view, which may need * to be adjusted. * @return the allocation that the superclass should use. */ Shape adjustAllocation(Shape a) { if (a != null) { Rectangle bounds = a.getBounds(); int vspan = (int) getPreferredSpan(Y_AXIS); int hspan = (int) getPreferredSpan(X_AXIS); if (bounds.height != vspan) { int slop = bounds.height - vspan; bounds.y += slop / 2; bounds.height -= slop; } // horizontal adjustments Component c = getContainer(); if (c instanceof JTextField) { JTextField field = (JTextField) c; BoundedRangeModel vis = field.getHorizontalVisibility(); int max = Math.max(hspan, bounds.width); int value = vis.getValue(); int extent = Math.min(max, bounds.width - 1); if ((value + extent) > max) { value = max - extent; } vis.setRangeProperties(value, extent, vis.getMinimum(), max, false); if (hspan < bounds.width) { // horizontally align the interior int slop = bounds.width - 1 - hspan; int align = ((JTextField)c).getHorizontalAlignment(); if(isLeftToRight(c)) { if(align==LEADING) { align = LEFT; } else if(align==TRAILING) { align = RIGHT; } } else { if(align==LEADING) { align = RIGHT; } else if(align==TRAILING) { align = LEFT; } } switch (align) { case SwingConstants.CENTER: bounds.x += slop / 2; bounds.width -= slop; break; case SwingConstants.RIGHT: bounds.x += slop; bounds.width -= slop; break; } } else { // adjust the allocation to match the bounded range. bounds.width = hspan; bounds.x -= vis.getValue(); } } return bounds; } return null; } /** {@collect.stats} * Update the visibility model with the associated JTextField * (if there is one) to reflect the current visibility as a * result of changes to the document model. The bounded * range properties are updated. If the view hasn't yet been * shown the extent will be zero and we just set it to be full * until determined otherwise. */ void updateVisibilityModel() { Component c = getContainer(); if (c instanceof JTextField) { JTextField field = (JTextField) c; BoundedRangeModel vis = field.getHorizontalVisibility(); int hspan = (int) getPreferredSpan(X_AXIS); int extent = vis.getExtent(); int maximum = Math.max(hspan, extent); extent = (extent == 0) ? maximum : extent; int value = maximum - extent; int oldValue = vis.getValue(); if ((oldValue + extent) > maximum) { oldValue = maximum - extent; } value = Math.max(0, Math.min(value, oldValue)); vis.setRangeProperties(value, extent, 0, maximum, false); } } // --- View methods ------------------------------------------- /** {@collect.stats} * Renders using the given rendering surface and area on that surface. * The view may need to do layout and create child views to enable * itself to render into the given allocation. * * @param g the rendering surface to use * @param a the allocated region to render into * * @see View#paint */ public void paint(Graphics g, Shape a) { Rectangle r = (Rectangle) a; g.clipRect(r.x, r.y, r.width, r.height); super.paint(g, adjustAllocation(a)); } /** {@collect.stats} * Determines the resizability of the view along the * given axis. A value of 0 or less is not resizable. * * @param axis View.X_AXIS or View.Y_AXIS * @return the weight -> 1 for View.X_AXIS, else 0 */ public int getResizeWeight(int axis) { if (axis == View.X_AXIS) { return 1; } return 0; } /** {@collect.stats} * Provides a mapping from the document model coordinate space * to the coordinate space of the view mapped to it. * * @param pos the position to convert >= 0 * @param a the allocated region to render into * @return the bounding box of the given position * @exception BadLocationException if the given position does not * represent a valid location in the associated document * @see View#modelToView */ public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException { return super.modelToView(pos, adjustAllocation(a), b); } /** {@collect.stats} * Provides a mapping from the document model coordinate space * to the coordinate space of the view mapped to it. * * @param p0 the position to convert >= 0 * @param b0 the bias toward the previous character or the * next character represented by p0, in case the * position is a boundary of two views. * @param p1 the position to convert >= 0 * @param b1 the bias toward the previous character or the * next character represented by p1, in case the * position is a boundary of two views. * @param a the allocated region to render into * @return the bounding box of the given position is returned * @exception BadLocationException if the given position does * not represent a valid location in the associated document * @exception IllegalArgumentException for an invalid bias argument * @see View#viewToModel */ public Shape modelToView(int p0, Position.Bias b0, int p1, Position.Bias b1, Shape a) throws BadLocationException { return super.modelToView(p0, b0, p1, b1, adjustAllocation(a)); } /** {@collect.stats} * Provides a mapping from the view coordinate space to the logical * coordinate space of the model. * * @param fx the X coordinate >= 0.0f * @param fy the Y coordinate >= 0.0f * @param a the allocated region to render into * @return the location within the model that best represents the * given point in the view * @see View#viewToModel */ public int viewToModel(float fx, float fy, Shape a, Position.Bias[] bias) { return super.viewToModel(fx, fy, adjustAllocation(a), bias); } /** {@collect.stats} * Gives notification that something was inserted into the document * in a location that this view is responsible for. * * @param changes the change information from the associated document * @param a the current allocation of the view * @param f the factory to use to rebuild if the view has children * @see View#insertUpdate */ public void insertUpdate(DocumentEvent changes, Shape a, ViewFactory f) { super.insertUpdate(changes, adjustAllocation(a), f); updateVisibilityModel(); } /** {@collect.stats} * Gives notification that something was removed from the document * in a location that this view is responsible for. * * @param changes the change information from the associated document * @param a the current allocation of the view * @param f the factory to use to rebuild if the view has children * @see View#removeUpdate */ public void removeUpdate(DocumentEvent changes, Shape a, ViewFactory f) { super.removeUpdate(changes, adjustAllocation(a), f); updateVisibilityModel(); } } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.beans.*; import java.util.Hashtable; import java.util.HashMap; import javax.swing.border.*; import javax.swing.plaf.*; import sun.swing.DefaultLookup; import sun.swing.UIAction; /** {@collect.stats} * A Basic L&F implementation of ToolBarUI. This implementation * is a "combined" view/controller. * <p> * * @author Georges Saab * @author Jeff Shapiro */ public class BasicToolBarUI extends ToolBarUI implements SwingConstants { protected JToolBar toolBar; private boolean floating; private int floatingX; private int floatingY; private JFrame floatingFrame; private RootPaneContainer floatingToolBar; protected DragWindow dragWindow; private Container dockingSource; private int dockingSensitivity = 0; protected int focusedCompIndex = -1; protected Color dockingColor = null; protected Color floatingColor = null; protected Color dockingBorderColor = null; protected Color floatingBorderColor = null; protected MouseInputListener dockingListener; protected PropertyChangeListener propertyListener; protected ContainerListener toolBarContListener; protected FocusListener toolBarFocusListener; private Handler handler; protected String constraintBeforeFloating = BorderLayout.NORTH; // Rollover button implementation. private static String IS_ROLLOVER = "JToolBar.isRollover"; private static Border rolloverBorder; private static Border nonRolloverBorder; private static Border nonRolloverToggleBorder; private boolean rolloverBorders = false; private HashMap borderTable = new HashMap(); private Hashtable rolloverTable = new Hashtable(); /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected KeyStroke upKey; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected KeyStroke downKey; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected KeyStroke leftKey; /** {@collect.stats} * As of Java 2 platform v1.3 this previously undocumented field is no * longer used. * Key bindings are now defined by the LookAndFeel, please refer to * the key bindings specification for further details. * * @deprecated As of Java 2 platform v1.3. */ @Deprecated protected KeyStroke rightKey; private static String FOCUSED_COMP_INDEX = "JToolBar.focusedCompIndex"; public static ComponentUI createUI( JComponent c ) { return new BasicToolBarUI(); } public void installUI( JComponent c ) { toolBar = (JToolBar) c; // Set defaults installDefaults(); installComponents(); installListeners(); installKeyboardActions(); // Initialize instance vars dockingSensitivity = 0; floating = false; floatingX = floatingY = 0; floatingToolBar = null; setOrientation( toolBar.getOrientation() ); LookAndFeel.installProperty(c, "opaque", Boolean.TRUE); if ( c.getClientProperty( FOCUSED_COMP_INDEX ) != null ) { focusedCompIndex = ( (Integer) ( c.getClientProperty( FOCUSED_COMP_INDEX ) ) ).intValue(); } } public void uninstallUI( JComponent c ) { // Clear defaults uninstallDefaults(); uninstallComponents(); uninstallListeners(); uninstallKeyboardActions(); // Clear instance vars if (isFloating() == true) setFloating(false, null); floatingToolBar = null; dragWindow = null; dockingSource = null; c.putClientProperty( FOCUSED_COMP_INDEX, new Integer( focusedCompIndex ) ); } protected void installDefaults( ) { LookAndFeel.installBorder(toolBar,"ToolBar.border"); LookAndFeel.installColorsAndFont(toolBar, "ToolBar.background", "ToolBar.foreground", "ToolBar.font"); // Toolbar specific defaults if ( dockingColor == null || dockingColor instanceof UIResource ) dockingColor = UIManager.getColor("ToolBar.dockingBackground"); if ( floatingColor == null || floatingColor instanceof UIResource ) floatingColor = UIManager.getColor("ToolBar.floatingBackground"); if ( dockingBorderColor == null || dockingBorderColor instanceof UIResource ) dockingBorderColor = UIManager.getColor("ToolBar.dockingForeground"); if ( floatingBorderColor == null || floatingBorderColor instanceof UIResource ) floatingBorderColor = UIManager.getColor("ToolBar.floatingForeground"); // ToolBar rollover button borders Object rolloverProp = toolBar.getClientProperty( IS_ROLLOVER ); if (rolloverProp == null) { rolloverProp = UIManager.get("ToolBar.isRollover"); } if ( rolloverProp != null ) { rolloverBorders = ((Boolean)rolloverProp).booleanValue(); } if (rolloverBorder == null) { rolloverBorder = createRolloverBorder(); } if (nonRolloverBorder == null) { nonRolloverBorder = createNonRolloverBorder(); } if (nonRolloverToggleBorder == null) { nonRolloverToggleBorder = createNonRolloverToggleBorder(); } setRolloverBorders( isRolloverBorders() ); } protected void uninstallDefaults( ) { LookAndFeel.uninstallBorder(toolBar); dockingColor = null; floatingColor = null; dockingBorderColor = null; floatingBorderColor = null; installNormalBorders(toolBar); rolloverBorder = null; nonRolloverBorder = null; nonRolloverToggleBorder = null; } protected void installComponents( ) { } protected void uninstallComponents( ) { } protected void installListeners( ) { dockingListener = createDockingListener( ); if ( dockingListener != null ) { toolBar.addMouseMotionListener( dockingListener ); toolBar.addMouseListener( dockingListener ); } propertyListener = createPropertyListener(); // added in setFloating if (propertyListener != null) { toolBar.addPropertyChangeListener(propertyListener); } toolBarContListener = createToolBarContListener(); if ( toolBarContListener != null ) { toolBar.addContainerListener( toolBarContListener ); } toolBarFocusListener = createToolBarFocusListener(); if ( toolBarFocusListener != null ) { // Put focus listener on all components in toolbar Component[] components = toolBar.getComponents(); for ( int i = 0; i < components.length; ++i ) { components[ i ].addFocusListener( toolBarFocusListener ); } } } protected void uninstallListeners( ) { if ( dockingListener != null ) { toolBar.removeMouseMotionListener(dockingListener); toolBar.removeMouseListener(dockingListener); dockingListener = null; } if ( propertyListener != null ) { toolBar.removePropertyChangeListener(propertyListener); propertyListener = null; // removed in setFloating } if ( toolBarContListener != null ) { toolBar.removeContainerListener( toolBarContListener ); toolBarContListener = null; } if ( toolBarFocusListener != null ) { // Remove focus listener from all components in toolbar Component[] components = toolBar.getComponents(); for ( int i = 0; i < components.length; ++i ) { components[ i ].removeFocusListener( toolBarFocusListener ); } toolBarFocusListener = null; } handler = null; } protected void installKeyboardActions( ) { InputMap km = getInputMap(JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); SwingUtilities.replaceUIInputMap(toolBar, JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, km); LazyActionMap.installLazyActionMap(toolBar, BasicToolBarUI.class, "ToolBar.actionMap"); } InputMap getInputMap(int condition) { if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) { return (InputMap)DefaultLookup.get(toolBar, this, "ToolBar.ancestorInputMap"); } return null; } static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.NAVIGATE_RIGHT)); map.put(new Actions(Actions.NAVIGATE_LEFT)); map.put(new Actions(Actions.NAVIGATE_UP)); map.put(new Actions(Actions.NAVIGATE_DOWN)); } protected void uninstallKeyboardActions( ) { SwingUtilities.replaceUIActionMap(toolBar, null); SwingUtilities.replaceUIInputMap(toolBar, JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null); } protected void navigateFocusedComp( int direction ) { int nComp = toolBar.getComponentCount(); int j; switch ( direction ) { case EAST: case SOUTH: if ( focusedCompIndex < 0 || focusedCompIndex >= nComp ) break; j = focusedCompIndex + 1; while ( j != focusedCompIndex ) { if ( j >= nComp ) j = 0; Component comp = toolBar.getComponentAtIndex( j++ ); if ( comp != null && comp.isFocusTraversable() && comp.isEnabled() ) { comp.requestFocus(); break; } } break; case WEST: case NORTH: if ( focusedCompIndex < 0 || focusedCompIndex >= nComp ) break; j = focusedCompIndex - 1; while ( j != focusedCompIndex ) { if ( j < 0 ) j = nComp - 1; Component comp = toolBar.getComponentAtIndex( j-- ); if ( comp != null && comp.isFocusTraversable() && comp.isEnabled() ) { comp.requestFocus(); break; } } break; default: break; } } /** {@collect.stats} * Creates a rollover border for toolbar components. The * rollover border will be installed if rollover borders are * enabled. * <p> * Override this method to provide an alternate rollover border. * * @since 1.4 */ protected Border createRolloverBorder() { Object border = UIManager.get("ToolBar.rolloverBorder"); if (border != null) { return (Border)border; } UIDefaults table = UIManager.getLookAndFeelDefaults(); return new CompoundBorder(new BasicBorders.RolloverButtonBorder( table.getColor("controlShadow"), table.getColor("controlDkShadow"), table.getColor("controlHighlight"), table.getColor("controlLtHighlight")), new BasicBorders.RolloverMarginBorder()); } /** {@collect.stats} * Creates the non rollover border for toolbar components. This * border will be installed as the border for components added * to the toolbar if rollover borders are not enabled. * <p> * Override this method to provide an alternate rollover border. * * @since 1.4 */ protected Border createNonRolloverBorder() { Object border = UIManager.get("ToolBar.nonrolloverBorder"); if (border != null) { return (Border)border; } UIDefaults table = UIManager.getLookAndFeelDefaults(); return new CompoundBorder(new BasicBorders.ButtonBorder( table.getColor("Button.shadow"), table.getColor("Button.darkShadow"), table.getColor("Button.light"), table.getColor("Button.highlight")), new BasicBorders.RolloverMarginBorder()); } /** {@collect.stats} * Creates a non rollover border for Toggle buttons in the toolbar. */ private Border createNonRolloverToggleBorder() { UIDefaults table = UIManager.getLookAndFeelDefaults(); return new CompoundBorder(new BasicBorders.RadioButtonBorder( table.getColor("ToggleButton.shadow"), table.getColor("ToggleButton.darkShadow"), table.getColor("ToggleButton.light"), table.getColor("ToggleButton.highlight")), new BasicBorders.RolloverMarginBorder()); } /** {@collect.stats} * No longer used, use BasicToolBarUI.createFloatingWindow(JToolBar) * @see #createFloatingWindow */ protected JFrame createFloatingFrame(JToolBar toolbar) { Window window = SwingUtilities.getWindowAncestor(toolbar); JFrame frame = new JFrame(toolbar.getName(), (window != null) ? window.getGraphicsConfiguration() : null) { // Override createRootPane() to automatically resize // the frame when contents change protected JRootPane createRootPane() { JRootPane rootPane = new JRootPane() { private boolean packing = false; public void validate() { super.validate(); if (!packing) { packing = true; pack(); packing = false; } } }; rootPane.setOpaque(true); return rootPane; } }; frame.getRootPane().setName("ToolBar.FloatingFrame"); frame.setResizable(false); WindowListener wl = createFrameListener(); frame.addWindowListener(wl); return frame; } /** {@collect.stats} * Creates a window which contains the toolbar after it has been * dragged out from its container * @return a <code>RootPaneContainer</code> object, containing the toolbar. * @since 1.4 */ protected RootPaneContainer createFloatingWindow(JToolBar toolbar) { class ToolBarDialog extends JDialog { public ToolBarDialog(Frame owner, String title, boolean modal) { super(owner, title, modal); } public ToolBarDialog(Dialog owner, String title, boolean modal) { super(owner, title, modal); } // Override createRootPane() to automatically resize // the frame when contents change protected JRootPane createRootPane() { JRootPane rootPane = new JRootPane() { private boolean packing = false; public void validate() { super.validate(); if (!packing) { packing = true; pack(); packing = false; } } }; rootPane.setOpaque(true); return rootPane; } } JDialog dialog; Window window = SwingUtilities.getWindowAncestor(toolbar); if (window instanceof Frame) { dialog = new ToolBarDialog((Frame)window, toolbar.getName(), false); } else if (window instanceof Dialog) { dialog = new ToolBarDialog((Dialog)window, toolbar.getName(), false); } else { dialog = new ToolBarDialog((Frame)null, toolbar.getName(), false); } dialog.getRootPane().setName("ToolBar.FloatingWindow"); dialog.setTitle(toolbar.getName()); dialog.setResizable(false); WindowListener wl = createFrameListener(); dialog.addWindowListener(wl); return dialog; } protected DragWindow createDragWindow(JToolBar toolbar) { Window frame = null; if(toolBar != null) { Container p; for(p = toolBar.getParent() ; p != null && !(p instanceof Window) ; p = p.getParent()); if(p != null && p instanceof Window) frame = (Window) p; } if(floatingToolBar == null) { floatingToolBar = createFloatingWindow(toolBar); } if (floatingToolBar instanceof Window) frame = (Window) floatingToolBar; DragWindow dragWindow = new DragWindow(frame); return dragWindow; } /** {@collect.stats} * Returns a flag to determine whether rollover button borders * are enabled. * * @return true if rollover borders are enabled; false otherwise * @see #setRolloverBorders * @since 1.4 */ public boolean isRolloverBorders() { return rolloverBorders; } /** {@collect.stats} * Sets the flag for enabling rollover borders on the toolbar and it will * also install the apropriate border depending on the state of the flag. * * @param rollover if true, rollover borders are installed. * Otherwise non-rollover borders are installed * @see #isRolloverBorders * @since 1.4 */ public void setRolloverBorders( boolean rollover ) { rolloverBorders = rollover; if ( rolloverBorders ) { installRolloverBorders( toolBar ); } else { installNonRolloverBorders( toolBar ); } } /** {@collect.stats} * Installs rollover borders on all the child components of the JComponent. * <p> * This is a convenience method to call <code>setBorderToRollover</code> * for each child component. * * @param c container which holds the child components (usally a JToolBar) * @see #setBorderToRollover * @since 1.4 */ protected void installRolloverBorders ( JComponent c ) { // Put rollover borders on buttons Component[] components = c.getComponents(); for ( int i = 0; i < components.length; ++i ) { if ( components[ i ] instanceof JComponent ) { ( (JComponent)components[ i ] ).updateUI(); setBorderToRollover( components[ i ] ); } } } /** {@collect.stats} * Installs non-rollover borders on all the child components of the JComponent. * A non-rollover border is the border that is installed on the child component * while it is in the toolbar. * <p> * This is a convenience method to call <code>setBorderToNonRollover</code> * for each child component. * * @param c container which holds the child components (usally a JToolBar) * @see #setBorderToNonRollover * @since 1.4 */ protected void installNonRolloverBorders ( JComponent c ) { // Put non-rollover borders on buttons. These borders reduce the margin. Component[] components = c.getComponents(); for ( int i = 0; i < components.length; ++i ) { if ( components[ i ] instanceof JComponent ) { ( (JComponent)components[ i ] ).updateUI(); setBorderToNonRollover( components[ i ] ); } } } /** {@collect.stats} * Installs normal borders on all the child components of the JComponent. * A normal border is the original border that was installed on the child * component before it was added to the toolbar. * <p> * This is a convenience method to call <code>setBorderNormal</code> * for each child component. * * @param c container which holds the child components (usally a JToolBar) * @see #setBorderToNonRollover * @since 1.4 */ protected void installNormalBorders ( JComponent c ) { // Put back the normal borders on buttons Component[] components = c.getComponents(); for ( int i = 0; i < components.length; ++i ) { setBorderToNormal( components[ i ] ); } } /** {@collect.stats} * Sets the border of the component to have a rollover border which * was created by <code>createRolloverBorder</code>. * * @param c component which will have a rollover border installed * @see #createRolloverBorder * @since 1.4 */ protected void setBorderToRollover(Component c) { if (c instanceof AbstractButton) { AbstractButton b = (AbstractButton)c; Border border = (Border)borderTable.get(b); if (border == null || border instanceof UIResource) { borderTable.put(b, b.getBorder()); } // Only set the border if its the default border if (b.getBorder() instanceof UIResource) { b.setBorder(getRolloverBorder(b)); } rolloverTable.put(b, b.isRolloverEnabled()? Boolean.TRUE: Boolean.FALSE); b.setRolloverEnabled(true); } } /** {@collect.stats} * Returns a rollover border for the button. * * @param b the button to calculate the rollover border for * @return the rollover border * @see #setBorderToRollover * @since 1.6 */ protected Border getRolloverBorder(AbstractButton b) { return rolloverBorder; } /** {@collect.stats} * Sets the border of the component to have a non-rollover border which * was created by <code>createNonRolloverBorder</code>. * * @param c component which will have a non-rollover border installed * @see #createNonRolloverBorder * @since 1.4 */ protected void setBorderToNonRollover(Component c) { if (c instanceof AbstractButton) { AbstractButton b = (AbstractButton)c; Border border = (Border)borderTable.get(b); if (border == null || border instanceof UIResource) { borderTable.put(b, b.getBorder()); } // Only set the border if its the default border if (b.getBorder() instanceof UIResource) { b.setBorder(getNonRolloverBorder(b)); } rolloverTable.put(b, b.isRolloverEnabled()? Boolean.TRUE: Boolean.FALSE); b.setRolloverEnabled(false); } } /** {@collect.stats} * Returns a non-rollover border for the button. * * @param b the button to calculate the non-rollover border for * @return the non-rollover border * @see #setBorderToNonRollover * @since 1.6 */ protected Border getNonRolloverBorder(AbstractButton b) { if (b instanceof JToggleButton) { return nonRolloverToggleBorder; } else { return nonRolloverBorder; } } /** {@collect.stats} * Sets the border of the component to have a normal border. * A normal border is the original border that was installed on the child * component before it was added to the toolbar. * * @param c component which will have a normal border re-installed * @see #createNonRolloverBorder * @since 1.4 */ protected void setBorderToNormal(Component c) { if (c instanceof AbstractButton) { AbstractButton b = (AbstractButton)c; Border border = (Border)borderTable.remove(b); b.setBorder(border); Boolean value = (Boolean)rolloverTable.remove(b); if (value != null) { b.setRolloverEnabled(value.booleanValue()); } } } public void setFloatingLocation(int x, int y) { floatingX = x; floatingY = y; } public boolean isFloating() { return floating; } public void setFloating(boolean b, Point p) { if (toolBar.isFloatable() == true) { boolean visible = false; Window ancestor = SwingUtilities.getWindowAncestor(toolBar); if (ancestor != null) { visible = ancestor.isVisible(); } if (dragWindow != null) dragWindow.setVisible(false); this.floating = b; if (floatingToolBar == null) { floatingToolBar = createFloatingWindow(toolBar); } if (b == true) { if (dockingSource == null) { dockingSource = toolBar.getParent(); dockingSource.remove(toolBar); } constraintBeforeFloating = calculateConstraint(); if ( propertyListener != null ) UIManager.addPropertyChangeListener( propertyListener ); floatingToolBar.getContentPane().add(toolBar,BorderLayout.CENTER); if (floatingToolBar instanceof Window) { ((Window)floatingToolBar).pack(); ((Window)floatingToolBar).setLocation(floatingX, floatingY); if (visible) { ((Window)floatingToolBar).show(); } else { ancestor.addWindowListener(new WindowAdapter() { public void windowOpened(WindowEvent e) { ((Window)floatingToolBar).show(); } }); } } } else { if (floatingToolBar == null) floatingToolBar = createFloatingWindow(toolBar); if (floatingToolBar instanceof Window) ((Window)floatingToolBar).setVisible(false); floatingToolBar.getContentPane().remove(toolBar); String constraint = getDockingConstraint(dockingSource, p); if (constraint == null) { constraint = BorderLayout.NORTH; } int orientation = mapConstraintToOrientation(constraint); setOrientation(orientation); if (dockingSource== null) dockingSource = toolBar.getParent(); if ( propertyListener != null ) UIManager.removePropertyChangeListener( propertyListener ); dockingSource.add(constraint, toolBar); } dockingSource.invalidate(); Container dockingSourceParent = dockingSource.getParent(); if (dockingSourceParent != null) dockingSourceParent.validate(); dockingSource.repaint(); } } private int mapConstraintToOrientation(String constraint) { int orientation = toolBar.getOrientation(); if ( constraint != null ) { if ( constraint.equals(BorderLayout.EAST) || constraint.equals(BorderLayout.WEST) ) orientation = JToolBar.VERTICAL; else if ( constraint.equals(BorderLayout.NORTH) || constraint.equals(BorderLayout.SOUTH) ) orientation = JToolBar.HORIZONTAL; } return orientation; } public void setOrientation(int orientation) { toolBar.setOrientation( orientation ); if (dragWindow !=null) dragWindow.setOrientation(orientation); } /** {@collect.stats} * Gets the color displayed when over a docking area */ public Color getDockingColor() { return dockingColor; } /** {@collect.stats} * Sets the color displayed when over a docking area */ public void setDockingColor(Color c) { this.dockingColor = c; } /** {@collect.stats} * Gets the color displayed when over a floating area */ public Color getFloatingColor() { return floatingColor; } /** {@collect.stats} * Sets the color displayed when over a floating area */ public void setFloatingColor(Color c) { this.floatingColor = c; } private boolean isBlocked(Component comp, Object constraint) { if (comp instanceof Container) { Container cont = (Container)comp; LayoutManager lm = cont.getLayout(); if (lm instanceof BorderLayout) { BorderLayout blm = (BorderLayout)lm; Component c = blm.getLayoutComponent(cont, constraint); return (c != null && c != toolBar); } } return false; } public boolean canDock(Component c, Point p) { return (p != null && getDockingConstraint(c, p) != null); } private String calculateConstraint() { String constraint = null; LayoutManager lm = dockingSource.getLayout(); if (lm instanceof BorderLayout) { constraint = (String)((BorderLayout)lm).getConstraints(toolBar); } return (constraint != null) ? constraint : constraintBeforeFloating; } private String getDockingConstraint(Component c, Point p) { if (p == null) return constraintBeforeFloating; if (c.contains(p)) { dockingSensitivity = (toolBar.getOrientation() == JToolBar.HORIZONTAL) ? toolBar.getSize().height : toolBar.getSize().width; // North (Base distance on height for now!) if (p.y < dockingSensitivity && !isBlocked(c, BorderLayout.NORTH)) { return BorderLayout.NORTH; } // East (Base distance on height for now!) if (p.x >= c.getWidth() - dockingSensitivity && !isBlocked(c, BorderLayout.EAST)) { return BorderLayout.EAST; } // West (Base distance on height for now!) if (p.x < dockingSensitivity && !isBlocked(c, BorderLayout.WEST)) { return BorderLayout.WEST; } if (p.y >= c.getHeight() - dockingSensitivity && !isBlocked(c, BorderLayout.SOUTH)) { return BorderLayout.SOUTH; } } return null; } protected void dragTo(Point position, Point origin) { if (toolBar.isFloatable() == true) { try { if (dragWindow == null) dragWindow = createDragWindow(toolBar); Point offset = dragWindow.getOffset(); if (offset == null) { Dimension size = toolBar.getPreferredSize(); offset = new Point(size.width/2, size.height/2); dragWindow.setOffset(offset); } Point global = new Point(origin.x+ position.x, origin.y+position.y); Point dragPoint = new Point(global.x- offset.x, global.y- offset.y); if (dockingSource == null) dockingSource = toolBar.getParent(); constraintBeforeFloating = calculateConstraint(); Point dockingPosition = dockingSource.getLocationOnScreen(); Point comparisonPoint = new Point(global.x-dockingPosition.x, global.y-dockingPosition.y); if (canDock(dockingSource, comparisonPoint)) { dragWindow.setBackground(getDockingColor()); String constraint = getDockingConstraint(dockingSource, comparisonPoint); int orientation = mapConstraintToOrientation(constraint); dragWindow.setOrientation(orientation); dragWindow.setBorderColor(dockingBorderColor); } else { dragWindow.setBackground(getFloatingColor()); dragWindow.setBorderColor(floatingBorderColor); dragWindow.setOrientation(toolBar.getOrientation()); } dragWindow.setLocation(dragPoint.x, dragPoint.y); if (dragWindow.isVisible() == false) { Dimension size = toolBar.getPreferredSize(); dragWindow.setSize(size.width, size.height); dragWindow.show(); } } catch ( IllegalComponentStateException e ) { } } } protected void floatAt(Point position, Point origin) { if(toolBar.isFloatable() == true) { try { Point offset = dragWindow.getOffset(); if (offset == null) { offset = position; dragWindow.setOffset(offset); } Point global = new Point(origin.x+ position.x, origin.y+position.y); setFloatingLocation(global.x-offset.x, global.y-offset.y); if (dockingSource != null) { Point dockingPosition = dockingSource.getLocationOnScreen(); Point comparisonPoint = new Point(global.x-dockingPosition.x, global.y-dockingPosition.y); if (canDock(dockingSource, comparisonPoint)) { setFloating(false, comparisonPoint); } else { setFloating(true, null); } } else { setFloating(true, null); } dragWindow.setOffset(null); } catch ( IllegalComponentStateException e ) { } } } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } protected ContainerListener createToolBarContListener( ) { return getHandler(); } protected FocusListener createToolBarFocusListener( ) { return getHandler(); } protected PropertyChangeListener createPropertyListener() { return getHandler(); } protected MouseInputListener createDockingListener( ) { getHandler().tb = toolBar; return getHandler(); } protected WindowListener createFrameListener() { return new FrameListener(); } /** {@collect.stats} * Paints the contents of the window used for dragging. * * @param g Graphics to paint to. * @throws NullPointerException is <code>g</code> is null * @since 1.5 */ protected void paintDragWindow(Graphics g) { g.setColor(dragWindow.getBackground()); int w = dragWindow.getWidth(); int h = dragWindow.getHeight(); g.fillRect(0, 0, w, h); g.setColor(dragWindow.getBorderColor()); g.drawRect(0, 0, w - 1, h - 1); } private static class Actions extends UIAction { private static final String NAVIGATE_RIGHT = "navigateRight"; private static final String NAVIGATE_LEFT = "navigateLeft"; private static final String NAVIGATE_UP = "navigateUp"; private static final String NAVIGATE_DOWN = "navigateDown"; public Actions(String name) { super(name); } public void actionPerformed(ActionEvent evt) { String key = getName(); JToolBar toolBar = (JToolBar)evt.getSource(); BasicToolBarUI ui = (BasicToolBarUI)BasicLookAndFeel.getUIOfType( toolBar.getUI(), BasicToolBarUI.class); if (NAVIGATE_RIGHT == key) { ui.navigateFocusedComp(EAST); } else if (NAVIGATE_LEFT == key) { ui.navigateFocusedComp(WEST); } else if (NAVIGATE_UP == key) { ui.navigateFocusedComp(NORTH); } else if (NAVIGATE_DOWN == key) { ui.navigateFocusedComp(SOUTH); } } } private class Handler implements ContainerListener, FocusListener, MouseInputListener, PropertyChangeListener { // // ContainerListener // public void componentAdded(ContainerEvent evt) { Component c = evt.getChild(); if (toolBarFocusListener != null) { c.addFocusListener(toolBarFocusListener); } if (isRolloverBorders()) { setBorderToRollover(c); } else { setBorderToNonRollover(c); } } public void componentRemoved(ContainerEvent evt) { Component c = evt.getChild(); if (toolBarFocusListener != null) { c.removeFocusListener(toolBarFocusListener); } // Revert the button border setBorderToNormal(c); } // // FocusListener // public void focusGained(FocusEvent evt) { Component c = evt.getComponent(); focusedCompIndex = toolBar.getComponentIndex(c); } public void focusLost(FocusEvent evt) { } // // MouseInputListener (DockingListener) // JToolBar tb; boolean isDragging = false; Point origin = null; public void mousePressed(MouseEvent evt) { if (!tb.isEnabled()) { return; } isDragging = false; } public void mouseReleased(MouseEvent evt) { if (!tb.isEnabled()) { return; } if (isDragging == true) { Point position = evt.getPoint(); if (origin == null) origin = evt.getComponent().getLocationOnScreen(); floatAt(position, origin); } origin = null; isDragging = false; } public void mouseDragged(MouseEvent evt) { if (!tb.isEnabled()) { return; } isDragging = true; Point position = evt.getPoint(); if (origin == null) { origin = evt.getComponent().getLocationOnScreen(); } dragTo(position, origin); } public void mouseClicked(MouseEvent evt) {} public void mouseEntered(MouseEvent evt) {} public void mouseExited(MouseEvent evt) {} public void mouseMoved(MouseEvent evt) {} // // PropertyChangeListener // public void propertyChange(PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if (propertyName == "lookAndFeel") { toolBar.updateUI(); } else if (propertyName == "orientation") { // Search for JSeparator components and change it's orientation // to match the toolbar and flip it's orientation. Component[] components = toolBar.getComponents(); int orientation = ((Integer)evt.getNewValue()).intValue(); JToolBar.Separator separator; for (int i = 0; i < components.length; ++i) { if (components[i] instanceof JToolBar.Separator) { separator = (JToolBar.Separator)components[i]; if ((orientation == JToolBar.HORIZONTAL)) { separator.setOrientation(JSeparator.VERTICAL); } else { separator.setOrientation(JSeparator.HORIZONTAL); } Dimension size = separator.getSeparatorSize(); if (size != null && size.width != size.height) { // Flip the orientation. Dimension newSize = new Dimension(size.height, size.width); separator.setSeparatorSize(newSize); } } } } else if (propertyName == IS_ROLLOVER) { installNormalBorders(toolBar); setRolloverBorders(((Boolean)evt.getNewValue()).booleanValue()); } } } protected class FrameListener extends WindowAdapter { public void windowClosing(WindowEvent w) { if (toolBar.isFloatable() == true) { if (dragWindow != null) dragWindow.setVisible(false); floating = false; if (floatingToolBar == null) floatingToolBar = createFloatingWindow(toolBar); if (floatingToolBar instanceof Window) ((Window)floatingToolBar).setVisible(false); floatingToolBar.getContentPane().remove(toolBar); String constraint = constraintBeforeFloating; if (toolBar.getOrientation() == JToolBar.HORIZONTAL) { if (constraint == "West" || constraint == "East") { constraint = "North"; } } else { if (constraint == "North" || constraint == "South") { constraint = "West"; } } if (dockingSource == null) dockingSource = toolBar.getParent(); if (propertyListener != null) UIManager.removePropertyChangeListener(propertyListener); dockingSource.add(toolBar, constraint); dockingSource.invalidate(); Container dockingSourceParent = dockingSource.getParent(); if (dockingSourceParent != null) dockingSourceParent.validate(); dockingSource.repaint(); } } } protected class ToolBarContListener implements ContainerListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void componentAdded( ContainerEvent e ) { getHandler().componentAdded(e); } public void componentRemoved( ContainerEvent e ) { getHandler().componentRemoved(e); } } protected class ToolBarFocusListener implements FocusListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void focusGained( FocusEvent e ) { getHandler().focusGained(e); } public void focusLost( FocusEvent e ) { getHandler().focusLost(e); } } protected class PropertyListener implements PropertyChangeListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void propertyChange( PropertyChangeEvent e ) { getHandler().propertyChange(e); } } /** {@collect.stats} * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicToolBarUI. */ public class DockingListener implements MouseInputListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. protected JToolBar toolBar; protected boolean isDragging = false; protected Point origin = null; public DockingListener(JToolBar t) { this.toolBar = t; getHandler().tb = t; } public void mouseClicked(MouseEvent e) { getHandler().mouseClicked(e); } public void mousePressed(MouseEvent e) { getHandler().tb = toolBar; getHandler().mousePressed(e); isDragging = getHandler().isDragging; } public void mouseReleased(MouseEvent e) { getHandler().tb = toolBar; getHandler().isDragging = isDragging; getHandler().origin = origin; getHandler().mouseReleased(e); isDragging = getHandler().isDragging; origin = getHandler().origin; } public void mouseEntered(MouseEvent e) { getHandler().mouseEntered(e); } public void mouseExited(MouseEvent e) { getHandler().mouseExited(e); } public void mouseDragged(MouseEvent e) { getHandler().tb = toolBar; getHandler().origin = origin; getHandler().mouseDragged(e); isDragging = getHandler().isDragging; origin = getHandler().origin; } public void mouseMoved(MouseEvent e) { getHandler().mouseMoved(e); } } protected class DragWindow extends Window { Color borderColor = Color.gray; int orientation = toolBar.getOrientation(); Point offset; // offset of the mouse cursor inside the DragWindow DragWindow(Window w) { super(w); } /** {@collect.stats} * Returns the orientation of the toolbar window when the toolbar is * floating. The orientation is either one of <code>JToolBar.HORIZONTAL</code> * or <code>JToolBar.VERTICAL</code>. * * @return the orientation of the toolbar window * @since 1.6 */ public int getOrientation() { return orientation; } public void setOrientation(int o) { if(isShowing()) { if (o == this.orientation) return; this.orientation = o; Dimension size = getSize(); setSize(new Dimension(size.height, size.width)); if (offset!=null) { if( BasicGraphicsUtils.isLeftToRight(toolBar) ) { setOffset(new Point(offset.y, offset.x)); } else if( o == JToolBar.HORIZONTAL ) { setOffset(new Point( size.height-offset.y, offset.x)); } else { setOffset(new Point(offset.y, size.width-offset.x)); } } repaint(); } } public Point getOffset() { return offset; } public void setOffset(Point p) { this.offset = p; } public void setBorderColor(Color c) { if (this.borderColor == c) return; this.borderColor = c; repaint(); } public Color getBorderColor() { return this.borderColor; } public void paint(Graphics g) { paintDragWindow(g); // Paint the children super.paint(g); } public Insets getInsets() { return new Insets(1,1,1,1); } } }
Java
/* * Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import sun.swing.DefaultLookup; import sun.swing.UIAction; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.*; import javax.swing.text.Position; import java.awt.*; import java.awt.event.*; import java.awt.datatransfer.Transferable; import java.awt.geom.Point2D; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import sun.swing.SwingUtilities2; import javax.swing.plaf.basic.DragRecognitionSupport.BeforeDrag; /** {@collect.stats} * An extensible implementation of {@code ListUI}. * <p> * {@code BasicListUI} instances cannot be shared between multiple * lists. * * @author Hans Muller * @author Philip Milne * @author Shannon Hickey (drag and drop) */ public class BasicListUI extends ListUI { private static final Object BASELINE_COMPONENT_KEY = new Object(); // List.baselineComponent protected JList list = null; protected CellRendererPane rendererPane; // Listeners that this UI attaches to the JList protected FocusListener focusListener; protected MouseInputListener mouseInputListener; protected ListSelectionListener listSelectionListener; protected ListDataListener listDataListener; protected PropertyChangeListener propertyChangeListener; private Handler handler; protected int[] cellHeights = null; protected int cellHeight = -1; protected int cellWidth = -1; protected int updateLayoutStateNeeded = modelChanged; /** {@collect.stats} * Height of the list. When asked to paint, if the current size of * the list differs, this will update the layout state. */ private int listHeight; /** {@collect.stats} * Width of the list. When asked to paint, if the current size of * the list differs, this will update the layout state. */ private int listWidth; /** {@collect.stats} * The layout orientation of the list. */ private int layoutOrientation; // Following ivars are used if the list is laying out horizontally /** {@collect.stats} * Number of columns to create. */ private int columnCount; /** {@collect.stats} * Preferred height to make the list, this is only used if the * the list is layed out horizontally. */ private int preferredHeight; /** {@collect.stats} * Number of rows per column. This is only used if the row height is * fixed. */ private int rowsPerColumn; /** {@collect.stats} * The time factor to treate the series of typed alphanumeric key * as prefix for first letter navigation. */ private long timeFactor = 1000L; /** {@collect.stats} * Local cache of JList's client property "List.isFileList" */ private boolean isFileList = false; /** {@collect.stats} * Local cache of JList's component orientation property */ private boolean isLeftToRight = true; /* The bits below define JList property changes that affect layout. * When one of these properties changes we set a bit in * updateLayoutStateNeeded. The change is dealt with lazily, see * maybeUpdateLayoutState. Changes to the JLists model, e.g. the * models length changed, are handled similarly, see DataListener. */ protected final static int modelChanged = 1 << 0; protected final static int selectionModelChanged = 1 << 1; protected final static int fontChanged = 1 << 2; protected final static int fixedCellWidthChanged = 1 << 3; protected final static int fixedCellHeightChanged = 1 << 4; protected final static int prototypeCellValueChanged = 1 << 5; protected final static int cellRendererChanged = 1 << 6; private final static int layoutOrientationChanged = 1 << 7; private final static int heightChanged = 1 << 8; private final static int widthChanged = 1 << 9; private final static int componentOrientationChanged = 1 << 10; private static final int DROP_LINE_THICKNESS = 2; static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.SELECT_PREVIOUS_COLUMN)); map.put(new Actions(Actions.SELECT_PREVIOUS_COLUMN_EXTEND)); map.put(new Actions(Actions.SELECT_PREVIOUS_COLUMN_CHANGE_LEAD)); map.put(new Actions(Actions.SELECT_NEXT_COLUMN)); map.put(new Actions(Actions.SELECT_NEXT_COLUMN_EXTEND)); map.put(new Actions(Actions.SELECT_NEXT_COLUMN_CHANGE_LEAD)); map.put(new Actions(Actions.SELECT_PREVIOUS_ROW)); map.put(new Actions(Actions.SELECT_PREVIOUS_ROW_EXTEND)); map.put(new Actions(Actions.SELECT_PREVIOUS_ROW_CHANGE_LEAD)); map.put(new Actions(Actions.SELECT_NEXT_ROW)); map.put(new Actions(Actions.SELECT_NEXT_ROW_EXTEND)); map.put(new Actions(Actions.SELECT_NEXT_ROW_CHANGE_LEAD)); map.put(new Actions(Actions.SELECT_FIRST_ROW)); map.put(new Actions(Actions.SELECT_FIRST_ROW_EXTEND)); map.put(new Actions(Actions.SELECT_FIRST_ROW_CHANGE_LEAD)); map.put(new Actions(Actions.SELECT_LAST_ROW)); map.put(new Actions(Actions.SELECT_LAST_ROW_EXTEND)); map.put(new Actions(Actions.SELECT_LAST_ROW_CHANGE_LEAD)); map.put(new Actions(Actions.SCROLL_UP)); map.put(new Actions(Actions.SCROLL_UP_EXTEND)); map.put(new Actions(Actions.SCROLL_UP_CHANGE_LEAD)); map.put(new Actions(Actions.SCROLL_DOWN)); map.put(new Actions(Actions.SCROLL_DOWN_EXTEND)); map.put(new Actions(Actions.SCROLL_DOWN_CHANGE_LEAD)); map.put(new Actions(Actions.SELECT_ALL)); map.put(new Actions(Actions.CLEAR_SELECTION)); map.put(new Actions(Actions.ADD_TO_SELECTION)); map.put(new Actions(Actions.TOGGLE_AND_ANCHOR)); map.put(new Actions(Actions.EXTEND_TO)); map.put(new Actions(Actions.MOVE_SELECTION_TO)); map.put(TransferHandler.getCutAction().getValue(Action.NAME), TransferHandler.getCutAction()); map.put(TransferHandler.getCopyAction().getValue(Action.NAME), TransferHandler.getCopyAction()); map.put(TransferHandler.getPasteAction().getValue(Action.NAME), TransferHandler.getPasteAction()); } /** {@collect.stats} * Paint one List cell: compute the relevant state, get the "rubber stamp" * cell renderer component, and then use the CellRendererPane to paint it. * Subclasses may want to override this method rather than paint(). * * @see #paint */ protected void paintCell( Graphics g, int row, Rectangle rowBounds, ListCellRenderer cellRenderer, ListModel dataModel, ListSelectionModel selModel, int leadIndex) { Object value = dataModel.getElementAt(row); boolean cellHasFocus = list.hasFocus() && (row == leadIndex); boolean isSelected = selModel.isSelectedIndex(row); Component rendererComponent = cellRenderer.getListCellRendererComponent(list, value, row, isSelected, cellHasFocus); int cx = rowBounds.x; int cy = rowBounds.y; int cw = rowBounds.width; int ch = rowBounds.height; if (isFileList) { // Shrink renderer to preferred size. This is mostly used on Windows // where selection is only shown around the file name, instead of // across the whole list cell. int w = Math.min(cw, rendererComponent.getPreferredSize().width + 4); if (!isLeftToRight) { cx += (cw - w); } cw = w; } rendererPane.paintComponent(g, rendererComponent, list, cx, cy, cw, ch, true); } /** {@collect.stats} * Paint the rows that intersect the Graphics objects clipRect. This * method calls paintCell as necessary. Subclasses * may want to override these methods. * * @see #paintCell */ public void paint(Graphics g, JComponent c) { Shape clip = g.getClip(); paintImpl(g, c); g.setClip(clip); paintDropLine(g); } private void paintImpl(Graphics g, JComponent c) { switch (layoutOrientation) { case JList.VERTICAL_WRAP: if (list.getHeight() != listHeight) { updateLayoutStateNeeded |= heightChanged; redrawList(); } break; case JList.HORIZONTAL_WRAP: if (list.getWidth() != listWidth) { updateLayoutStateNeeded |= widthChanged; redrawList(); } break; default: break; } maybeUpdateLayoutState(); ListCellRenderer renderer = list.getCellRenderer(); ListModel dataModel = list.getModel(); ListSelectionModel selModel = list.getSelectionModel(); int size; if ((renderer == null) || (size = dataModel.getSize()) == 0) { return; } // Determine how many columns we need to paint Rectangle paintBounds = g.getClipBounds(); int startColumn, endColumn; if (c.getComponentOrientation().isLeftToRight()) { startColumn = convertLocationToColumn(paintBounds.x, paintBounds.y); endColumn = convertLocationToColumn(paintBounds.x + paintBounds.width, paintBounds.y); } else { startColumn = convertLocationToColumn(paintBounds.x + paintBounds.width, paintBounds.y); endColumn = convertLocationToColumn(paintBounds.x, paintBounds.y); } int maxY = paintBounds.y + paintBounds.height; int leadIndex = adjustIndex(list.getLeadSelectionIndex(), list); int rowIncrement = (layoutOrientation == JList.HORIZONTAL_WRAP) ? columnCount : 1; for (int colCounter = startColumn; colCounter <= endColumn; colCounter++) { // And then how many rows in this columnn int row = convertLocationToRowInColumn(paintBounds.y, colCounter); int rowCount = getRowCount(colCounter); int index = getModelIndex(colCounter, row); Rectangle rowBounds = getCellBounds(list, index, index); if (rowBounds == null) { // Not valid, bail! return; } while (row < rowCount && rowBounds.y < maxY && index < size) { rowBounds.height = getHeight(colCounter, row); g.setClip(rowBounds.x, rowBounds.y, rowBounds.width, rowBounds.height); g.clipRect(paintBounds.x, paintBounds.y, paintBounds.width, paintBounds.height); paintCell(g, index, rowBounds, renderer, dataModel, selModel, leadIndex); rowBounds.y += rowBounds.height; index += rowIncrement; row++; } } // Empty out the renderer pane, allowing renderers to be gc'ed. rendererPane.removeAll(); } private void paintDropLine(Graphics g) { JList.DropLocation loc = list.getDropLocation(); if (loc == null || !loc.isInsert()) { return; } Color c = DefaultLookup.getColor(list, this, "List.dropLineColor", null); if (c != null) { g.setColor(c); Rectangle rect = getDropLineRect(loc); g.fillRect(rect.x, rect.y, rect.width, rect.height); } } private Rectangle getDropLineRect(JList.DropLocation loc) { int size = list.getModel().getSize(); if (size == 0) { Insets insets = list.getInsets(); if (layoutOrientation == JList.HORIZONTAL_WRAP) { if (isLeftToRight) { return new Rectangle(insets.left, insets.top, DROP_LINE_THICKNESS, 20); } else { return new Rectangle(list.getWidth() - DROP_LINE_THICKNESS - insets.right, insets.top, DROP_LINE_THICKNESS, 20); } } else { return new Rectangle(insets.left, insets.top, list.getWidth() - insets.left - insets.right, DROP_LINE_THICKNESS); } } Rectangle rect = null; int index = loc.getIndex(); boolean decr = false; if (layoutOrientation == JList.HORIZONTAL_WRAP) { if (index == size) { decr = true; } else if (index != 0 && convertModelToRow(index) != convertModelToRow(index - 1)) { Rectangle prev = getCellBounds(list, index - 1); Rectangle me = getCellBounds(list, index); Point p = loc.getDropPoint(); if (isLeftToRight) { decr = Point2D.distance(prev.x + prev.width, prev.y + (int)(prev.height / 2.0), p.x, p.y) < Point2D.distance(me.x, me.y + (int)(me.height / 2.0), p.x, p.y); } else { decr = Point2D.distance(prev.x, prev.y + (int)(prev.height / 2.0), p.x, p.y) < Point2D.distance(me.x + me.width, me.y + (int)(prev.height / 2.0), p.x, p.y); } } if (decr) { index--; rect = getCellBounds(list, index); if (isLeftToRight) { rect.x += rect.width; } else { rect.x -= DROP_LINE_THICKNESS; } } else { rect = getCellBounds(list, index); if (!isLeftToRight) { rect.x += rect.width - DROP_LINE_THICKNESS; } } if (rect.x >= list.getWidth()) { rect.x = list.getWidth() - DROP_LINE_THICKNESS; } else if (rect.x < 0) { rect.x = 0; } rect.width = DROP_LINE_THICKNESS; } else if (layoutOrientation == JList.VERTICAL_WRAP) { if (index == size) { index--; rect = getCellBounds(list, index); rect.y += rect.height; } else if (index != 0 && convertModelToColumn(index) != convertModelToColumn(index - 1)) { Rectangle prev = getCellBounds(list, index - 1); Rectangle me = getCellBounds(list, index); Point p = loc.getDropPoint(); if (Point2D.distance(prev.x + (int)(prev.width / 2.0), prev.y + prev.height, p.x, p.y) < Point2D.distance(me.x + (int)(me.width / 2.0), me.y, p.x, p.y)) { index--; rect = getCellBounds(list, index); rect.y += rect.height; } else { rect = getCellBounds(list, index); } } else { rect = getCellBounds(list, index); } if (rect.y >= list.getHeight()) { rect.y = list.getHeight() - DROP_LINE_THICKNESS; } rect.height = DROP_LINE_THICKNESS; } else { if (index == size) { index--; rect = getCellBounds(list, index); rect.y += rect.height; } else { rect = getCellBounds(list, index); } if (rect.y >= list.getHeight()) { rect.y = list.getHeight() - DROP_LINE_THICKNESS; } rect.height = DROP_LINE_THICKNESS; } return rect; } /** {@collect.stats} * Returns the baseline. * * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public int getBaseline(JComponent c, int width, int height) { super.getBaseline(c, width, height); int rowHeight = list.getFixedCellHeight(); UIDefaults lafDefaults = UIManager.getLookAndFeelDefaults(); Component renderer = (Component)lafDefaults.get( BASELINE_COMPONENT_KEY); if (renderer == null) { ListCellRenderer lcr = (ListCellRenderer)UIManager.get( "List.cellRenderer"); // fix for 6711072 some LAFs like Nimbus do not provide this // UIManager key and we should not through a NPE here because of it if (lcr == null) { lcr = new DefaultListCellRenderer(); } renderer = lcr.getListCellRendererComponent( list, "a", -1, false, false); lafDefaults.put(BASELINE_COMPONENT_KEY, renderer); } renderer.setFont(list.getFont()); // JList actually has much more complex behavior here. // If rowHeight != -1 the rowHeight is either the max of all cell // heights (layout orientation != VERTICAL), or is variable depending // upon the cell. We assume a default size. // We could theoretically query the real renderer, but that would // not work for an empty model and the results may vary with // the content. if (rowHeight == -1) { rowHeight = renderer.getPreferredSize().height; } return renderer.getBaseline(Integer.MAX_VALUE, rowHeight) + list.getInsets().top; } /** {@collect.stats} * Returns an enum indicating how the baseline of the component * changes as the size changes. * * @throws NullPointerException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public Component.BaselineResizeBehavior getBaselineResizeBehavior( JComponent c) { super.getBaselineResizeBehavior(c); return Component.BaselineResizeBehavior.CONSTANT_ASCENT; } /** {@collect.stats} * The preferredSize of the list depends upon the layout orientation. * <table summary="Describes the preferred size for each layout orientation"> * <tr><th>Layout Orientation</th><th>Preferred Size</th></tr> * <tr> * <td>JList.VERTICAL * <td>The preferredSize of the list is total height of the rows * and the maximum width of the cells. If JList.fixedCellHeight * is specified then the total height of the rows is just * (cellVerticalMargins + fixedCellHeight) * model.getSize() where * rowVerticalMargins is the space we allocate for drawing * the yellow focus outline. Similarly if fixedCellWidth is * specified then we just use that. * </td> * <tr> * <td>JList.VERTICAL_WRAP * <td>If the visible row count is greater than zero, the preferredHeight * is the maximum cell height * visibleRowCount. If the visible row * count is <= 0, the preferred height is either the current height * of the list, or the maximum cell height, whichever is * bigger. The preferred width is than the maximum cell width * * number of columns needed. Where the number of columns needs is * list.height / max cell height. Max cell height is either the fixed * cell height, or is determined by iterating through all the cells * to find the maximum height from the ListCellRenderer. * <tr> * <td>JList.HORIZONTAL_WRAP * <td>If the visible row count is greater than zero, the preferredHeight * is the maximum cell height * adjustedRowCount. Where * visibleRowCount is used to determine the number of columns. * Because this lays out horizontally the number of rows is * then determined from the column count. For example, lets say * you have a model with 10 items and the visible row count is 8. * The number of columns needed to display this is 2, but you no * longer need 8 rows to display this, you only need 5, thus * the adjustedRowCount is 5. * <p>If the visible row * count is <= 0, the preferred height is dictated by the * number of columns, which will be as many as can fit in the width * of the <code>JList</code> (width / max cell width), with at * least one column. The preferred height then becomes the * model size / number of columns * maximum cell height. * Max cell height is either the fixed * cell height, or is determined by iterating through all the cells * to find the maximum height from the ListCellRenderer. * </table> * The above specifies the raw preferred width and height. The resulting * preferred width is the above width + insets.left + insets.right and * the resulting preferred height is the above height + insets.top + * insets.bottom. Where the <code>Insets</code> are determined from * <code>list.getInsets()</code>. * * @param c The JList component. * @return The total size of the list. */ public Dimension getPreferredSize(JComponent c) { maybeUpdateLayoutState(); int lastRow = list.getModel().getSize() - 1; if (lastRow < 0) { return new Dimension(0, 0); } Insets insets = list.getInsets(); int width = cellWidth * columnCount + insets.left + insets.right; int height; if (layoutOrientation != JList.VERTICAL) { height = preferredHeight; } else { Rectangle bounds = getCellBounds(list, lastRow); if (bounds != null) { height = bounds.y + bounds.height + insets.bottom; } else { height = 0; } } return new Dimension(width, height); } /** {@collect.stats} * Selected the previous row and force it to be visible. * * @see JList#ensureIndexIsVisible */ protected void selectPreviousIndex() { int s = list.getSelectedIndex(); if(s > 0) { s -= 1; list.setSelectedIndex(s); list.ensureIndexIsVisible(s); } } /** {@collect.stats} * Selected the previous row and force it to be visible. * * @see JList#ensureIndexIsVisible */ protected void selectNextIndex() { int s = list.getSelectedIndex(); if((s + 1) < list.getModel().getSize()) { s += 1; list.setSelectedIndex(s); list.ensureIndexIsVisible(s); } } /** {@collect.stats} * Registers the keyboard bindings on the <code>JList</code> that the * <code>BasicListUI</code> is associated with. This method is called at * installUI() time. * * @see #installUI */ protected void installKeyboardActions() { InputMap inputMap = getInputMap(JComponent.WHEN_FOCUSED); SwingUtilities.replaceUIInputMap(list, JComponent.WHEN_FOCUSED, inputMap); LazyActionMap.installLazyActionMap(list, BasicListUI.class, "List.actionMap"); } InputMap getInputMap(int condition) { if (condition == JComponent.WHEN_FOCUSED) { InputMap keyMap = (InputMap)DefaultLookup.get( list, this, "List.focusInputMap"); InputMap rtlKeyMap; if (isLeftToRight || ((rtlKeyMap = (InputMap)DefaultLookup.get(list, this, "List.focusInputMap.RightToLeft")) == null)) { return keyMap; } else { rtlKeyMap.setParent(keyMap); return rtlKeyMap; } } return null; } /** {@collect.stats} * Unregisters keyboard actions installed from * <code>installKeyboardActions</code>. * This method is called at uninstallUI() time - subclassess should * ensure that all of the keyboard actions registered at installUI * time are removed here. * * @see #installUI */ protected void uninstallKeyboardActions() { SwingUtilities.replaceUIActionMap(list, null); SwingUtilities.replaceUIInputMap(list, JComponent.WHEN_FOCUSED, null); } /** {@collect.stats} * Create and install the listeners for the JList, its model, and its * selectionModel. This method is called at installUI() time. * * @see #installUI * @see #uninstallListeners */ protected void installListeners() { TransferHandler th = list.getTransferHandler(); if (th == null || th instanceof UIResource) { list.setTransferHandler(defaultTransferHandler); // default TransferHandler doesn't support drop // so we don't want drop handling if (list.getDropTarget() instanceof UIResource) { list.setDropTarget(null); } } focusListener = createFocusListener(); mouseInputListener = createMouseInputListener(); propertyChangeListener = createPropertyChangeListener(); listSelectionListener = createListSelectionListener(); listDataListener = createListDataListener(); list.addFocusListener(focusListener); list.addMouseListener(mouseInputListener); list.addMouseMotionListener(mouseInputListener); list.addPropertyChangeListener(propertyChangeListener); list.addKeyListener(getHandler()); ListModel model = list.getModel(); if (model != null) { model.addListDataListener(listDataListener); } ListSelectionModel selectionModel = list.getSelectionModel(); if (selectionModel != null) { selectionModel.addListSelectionListener(listSelectionListener); } } /** {@collect.stats} * Remove the listeners for the JList, its model, and its * selectionModel. All of the listener fields, are reset to * null here. This method is called at uninstallUI() time, * it should be kept in sync with installListeners. * * @see #uninstallUI * @see #installListeners */ protected void uninstallListeners() { list.removeFocusListener(focusListener); list.removeMouseListener(mouseInputListener); list.removeMouseMotionListener(mouseInputListener); list.removePropertyChangeListener(propertyChangeListener); list.removeKeyListener(getHandler()); ListModel model = list.getModel(); if (model != null) { model.removeListDataListener(listDataListener); } ListSelectionModel selectionModel = list.getSelectionModel(); if (selectionModel != null) { selectionModel.removeListSelectionListener(listSelectionListener); } focusListener = null; mouseInputListener = null; listSelectionListener = null; listDataListener = null; propertyChangeListener = null; handler = null; } /** {@collect.stats} * Initialize JList properties, e.g. font, foreground, and background, * and add the CellRendererPane. The font, foreground, and background * properties are only set if their current value is either null * or a UIResource, other properties are set if the current * value is null. * * @see #uninstallDefaults * @see #installUI * @see CellRendererPane */ protected void installDefaults() { list.setLayout(null); LookAndFeel.installBorder(list, "List.border"); LookAndFeel.installColorsAndFont(list, "List.background", "List.foreground", "List.font"); LookAndFeel.installProperty(list, "opaque", Boolean.TRUE); if (list.getCellRenderer() == null) { list.setCellRenderer((ListCellRenderer)(UIManager.get("List.cellRenderer"))); } Color sbg = list.getSelectionBackground(); if (sbg == null || sbg instanceof UIResource) { list.setSelectionBackground(UIManager.getColor("List.selectionBackground")); } Color sfg = list.getSelectionForeground(); if (sfg == null || sfg instanceof UIResource) { list.setSelectionForeground(UIManager.getColor("List.selectionForeground")); } Long l = (Long)UIManager.get("List.timeFactor"); timeFactor = (l!=null) ? l.longValue() : 1000L; updateIsFileList(); } private void updateIsFileList() { boolean b = Boolean.TRUE.equals(list.getClientProperty("List.isFileList")); if (b != isFileList) { isFileList = b; Font oldFont = list.getFont(); if (oldFont == null || oldFont instanceof UIResource) { Font newFont = UIManager.getFont(b ? "FileChooser.listFont" : "List.font"); if (newFont != null && newFont != oldFont) { list.setFont(newFont); } } } } /** {@collect.stats} * Set the JList properties that haven't been explicitly overridden to * null. A property is considered overridden if its current value * is not a UIResource. * * @see #installDefaults * @see #uninstallUI * @see CellRendererPane */ protected void uninstallDefaults() { LookAndFeel.uninstallBorder(list); if (list.getFont() instanceof UIResource) { list.setFont(null); } if (list.getForeground() instanceof UIResource) { list.setForeground(null); } if (list.getBackground() instanceof UIResource) { list.setBackground(null); } if (list.getSelectionBackground() instanceof UIResource) { list.setSelectionBackground(null); } if (list.getSelectionForeground() instanceof UIResource) { list.setSelectionForeground(null); } if (list.getCellRenderer() instanceof UIResource) { list.setCellRenderer(null); } if (list.getTransferHandler() instanceof UIResource) { list.setTransferHandler(null); } } /** {@collect.stats} * Initializes <code>this.list</code> by calling <code>installDefaults()</code>, * <code>installListeners()</code>, and <code>installKeyboardActions()</code> * in order. * * @see #installDefaults * @see #installListeners * @see #installKeyboardActions */ public void installUI(JComponent c) { list = (JList)c; layoutOrientation = list.getLayoutOrientation(); rendererPane = new CellRendererPane(); list.add(rendererPane); columnCount = 1; updateLayoutStateNeeded = modelChanged; isLeftToRight = list.getComponentOrientation().isLeftToRight(); installDefaults(); installListeners(); installKeyboardActions(); } /** {@collect.stats} * Uninitializes <code>this.list</code> by calling <code>uninstallListeners()</code>, * <code>uninstallKeyboardActions()</code>, and <code>uninstallDefaults()</code> * in order. Sets this.list to null. * * @see #uninstallListeners * @see #uninstallKeyboardActions * @see #uninstallDefaults */ public void uninstallUI(JComponent c) { uninstallListeners(); uninstallDefaults(); uninstallKeyboardActions(); cellWidth = cellHeight = -1; cellHeights = null; listWidth = listHeight = -1; list.remove(rendererPane); rendererPane = null; list = null; } /** {@collect.stats} * Returns a new instance of BasicListUI. BasicListUI delegates are * allocated one per JList. * * @return A new ListUI implementation for the Windows look and feel. */ public static ComponentUI createUI(JComponent list) { return new BasicListUI(); } /** {@collect.stats} * {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public int locationToIndex(JList list, Point location) { maybeUpdateLayoutState(); return convertLocationToModel(location.x, location.y); } /** {@collect.stats} * {@inheritDoc} */ public Point indexToLocation(JList list, int index) { maybeUpdateLayoutState(); Rectangle rect = getCellBounds(list, index, index); if (rect != null) { return new Point(rect.x, rect.y); } return null; } /** {@collect.stats} * {@inheritDoc} */ public Rectangle getCellBounds(JList list, int index1, int index2) { maybeUpdateLayoutState(); int minIndex = Math.min(index1, index2); int maxIndex = Math.max(index1, index2); if (minIndex >= list.getModel().getSize()) { return null; } Rectangle minBounds = getCellBounds(list, minIndex); if (minBounds == null) { return null; } if (minIndex == maxIndex) { return minBounds; } Rectangle maxBounds = getCellBounds(list, maxIndex); if (maxBounds != null) { if (layoutOrientation == JList.HORIZONTAL_WRAP) { int minRow = convertModelToRow(minIndex); int maxRow = convertModelToRow(maxIndex); if (minRow != maxRow) { minBounds.x = 0; minBounds.width = list.getWidth(); } } else if (minBounds.x != maxBounds.x) { // Different columns minBounds.y = 0; minBounds.height = list.getHeight(); } minBounds.add(maxBounds); } return minBounds; } /** {@collect.stats} * Gets the bounds of the specified model index, returning the resulting * bounds, or null if <code>index</code> is not valid. */ private Rectangle getCellBounds(JList list, int index) { maybeUpdateLayoutState(); int row = convertModelToRow(index); int column = convertModelToColumn(index); if (row == -1 || column == -1) { return null; } Insets insets = list.getInsets(); int x; int w = cellWidth; int y = insets.top; int h; switch (layoutOrientation) { case JList.VERTICAL_WRAP: case JList.HORIZONTAL_WRAP: if (isLeftToRight) { x = insets.left + column * cellWidth; } else { x = list.getWidth() - insets.right - (column+1) * cellWidth; } y += cellHeight * row; h = cellHeight; break; default: x = insets.left; if (cellHeights == null) { y += (cellHeight * row); } else if (row >= cellHeights.length) { y = 0; } else { for(int i = 0; i < row; i++) { y += cellHeights[i]; } } w = list.getWidth() - (insets.left + insets.right); h = getRowHeight(index); break; } return new Rectangle(x, y, w, h); } /** {@collect.stats} * Returns the height of the specified row based on the current layout. * * @return The specified row height or -1 if row isn't valid. * @see #convertYToRow * @see #convertRowToY * @see #updateLayoutState */ protected int getRowHeight(int row) { return getHeight(0, row); } /** {@collect.stats} * Convert the JList relative coordinate to the row that contains it, * based on the current layout. If y0 doesn't fall within any row, * return -1. * * @return The row that contains y0, or -1. * @see #getRowHeight * @see #updateLayoutState */ protected int convertYToRow(int y0) { return convertLocationToRow(0, y0, false); } /** {@collect.stats} * Return the JList relative Y coordinate of the origin of the specified * row or -1 if row isn't valid. * * @return The Y coordinate of the origin of row, or -1. * @see #getRowHeight * @see #updateLayoutState */ protected int convertRowToY(int row) { if (row >= getRowCount(0) || row < 0) { return -1; } Rectangle bounds = getCellBounds(list, row, row); return bounds.y; } /** {@collect.stats} * Returns the height of the cell at the passed in location. */ private int getHeight(int column, int row) { if (column < 0 || column > columnCount || row < 0) { return -1; } if (layoutOrientation != JList.VERTICAL) { return cellHeight; } if (row >= list.getModel().getSize()) { return -1; } return (cellHeights == null) ? cellHeight : ((row < cellHeights.length) ? cellHeights[row] : -1); } /** {@collect.stats} * Returns the row at location x/y. * * @param closest If true and the location doesn't exactly match a * particular location, this will return the closest row. */ private int convertLocationToRow(int x, int y0, boolean closest) { int size = list.getModel().getSize(); if (size <= 0) { return -1; } Insets insets = list.getInsets(); if (cellHeights == null) { int row = (cellHeight == 0) ? 0 : ((y0 - insets.top) / cellHeight); if (closest) { if (row < 0) { row = 0; } else if (row >= size) { row = size - 1; } } return row; } else if (size > cellHeights.length) { return -1; } else { int y = insets.top; int row = 0; if (closest && y0 < y) { return 0; } int i; for (i = 0; i < size; i++) { if ((y0 >= y) && (y0 < y + cellHeights[i])) { return row; } y += cellHeights[i]; row += 1; } return i - 1; } } /** {@collect.stats} * Returns the closest row that starts at the specified y-location * in the passed in column. */ private int convertLocationToRowInColumn(int y, int column) { int x = 0; if (layoutOrientation != JList.VERTICAL) { if (isLeftToRight) { x = column * cellWidth; } else { x = list.getWidth() - (column+1)*cellWidth - list.getInsets().right; } } return convertLocationToRow(x, y, true); } /** {@collect.stats} * Returns the closest location to the model index of the passed in * location. */ private int convertLocationToModel(int x, int y) { int row = convertLocationToRow(x, y, true); int column = convertLocationToColumn(x, y); if (row >= 0 && column >= 0) { return getModelIndex(column, row); } return -1; } /** {@collect.stats} * Returns the number of rows in the given column. */ private int getRowCount(int column) { if (column < 0 || column >= columnCount) { return -1; } if (layoutOrientation == JList.VERTICAL || (column == 0 && columnCount == 1)) { return list.getModel().getSize(); } if (column >= columnCount) { return -1; } if (layoutOrientation == JList.VERTICAL_WRAP) { if (column < (columnCount - 1)) { return rowsPerColumn; } return list.getModel().getSize() - (columnCount - 1) * rowsPerColumn; } // JList.HORIZONTAL_WRAP int diff = columnCount - (columnCount * rowsPerColumn - list.getModel().getSize()); if (column >= diff) { return Math.max(0, rowsPerColumn - 1); } return rowsPerColumn; } /** {@collect.stats} * Returns the model index for the specified display location. * If <code>column</code>x<code>row</code> is beyond the length of the * model, this will return the model size - 1. */ private int getModelIndex(int column, int row) { switch (layoutOrientation) { case JList.VERTICAL_WRAP: return Math.min(list.getModel().getSize() - 1, rowsPerColumn * column + Math.min(row, rowsPerColumn-1)); case JList.HORIZONTAL_WRAP: return Math.min(list.getModel().getSize() - 1, row * columnCount + column); default: return row; } } /** {@collect.stats} * Returns the closest column to the passed in location. */ private int convertLocationToColumn(int x, int y) { if (cellWidth > 0) { if (layoutOrientation == JList.VERTICAL) { return 0; } Insets insets = list.getInsets(); int col; if (isLeftToRight) { col = (x - insets.left) / cellWidth; } else { col = (list.getWidth() - x - insets.right - 1) / cellWidth; } if (col < 0) { return 0; } else if (col >= columnCount) { return columnCount - 1; } return col; } return 0; } /** {@collect.stats} * Returns the row that the model index <code>index</code> will be * displayed in.. */ private int convertModelToRow(int index) { int size = list.getModel().getSize(); if ((index < 0) || (index >= size)) { return -1; } if (layoutOrientation != JList.VERTICAL && columnCount > 1 && rowsPerColumn > 0) { if (layoutOrientation == JList.VERTICAL_WRAP) { return index % rowsPerColumn; } return index / columnCount; } return index; } /** {@collect.stats} * Returns the column that the model index <code>index</code> will be * displayed in. */ private int convertModelToColumn(int index) { int size = list.getModel().getSize(); if ((index < 0) || (index >= size)) { return -1; } if (layoutOrientation != JList.VERTICAL && rowsPerColumn > 0 && columnCount > 1) { if (layoutOrientation == JList.VERTICAL_WRAP) { return index / rowsPerColumn; } return index % columnCount; } return 0; } /** {@collect.stats} * If updateLayoutStateNeeded is non zero, call updateLayoutState() and reset * updateLayoutStateNeeded. This method should be called by methods * before doing any computation based on the geometry of the list. * For example it's the first call in paint() and getPreferredSize(). * * @see #updateLayoutState */ protected void maybeUpdateLayoutState() { if (updateLayoutStateNeeded != 0) { updateLayoutState(); updateLayoutStateNeeded = 0; } } /** {@collect.stats} * Recompute the value of cellHeight or cellHeights based * and cellWidth, based on the current font and the current * values of fixedCellWidth, fixedCellHeight, and prototypeCellValue. * * @see #maybeUpdateLayoutState */ protected void updateLayoutState() { /* If both JList fixedCellWidth and fixedCellHeight have been * set, then initialize cellWidth and cellHeight, and set * cellHeights to null. */ int fixedCellHeight = list.getFixedCellHeight(); int fixedCellWidth = list.getFixedCellWidth(); cellWidth = (fixedCellWidth != -1) ? fixedCellWidth : -1; if (fixedCellHeight != -1) { cellHeight = fixedCellHeight; cellHeights = null; } else { cellHeight = -1; cellHeights = new int[list.getModel().getSize()]; } /* If either of JList fixedCellWidth and fixedCellHeight haven't * been set, then initialize cellWidth and cellHeights by * scanning through the entire model. Note: if the renderer is * null, we just set cellWidth and cellHeights[*] to zero, * if they're not set already. */ if ((fixedCellWidth == -1) || (fixedCellHeight == -1)) { ListModel dataModel = list.getModel(); int dataModelSize = dataModel.getSize(); ListCellRenderer renderer = list.getCellRenderer(); if (renderer != null) { for(int index = 0; index < dataModelSize; index++) { Object value = dataModel.getElementAt(index); Component c = renderer.getListCellRendererComponent(list, value, index, false, false); rendererPane.add(c); Dimension cellSize = c.getPreferredSize(); if (fixedCellWidth == -1) { cellWidth = Math.max(cellSize.width, cellWidth); } if (fixedCellHeight == -1) { cellHeights[index] = cellSize.height; } } } else { if (cellWidth == -1) { cellWidth = 0; } if (cellHeights == null) { cellHeights = new int[dataModelSize]; } for(int index = 0; index < dataModelSize; index++) { cellHeights[index] = 0; } } } columnCount = 1; if (layoutOrientation != JList.VERTICAL) { updateHorizontalLayoutState(fixedCellWidth, fixedCellHeight); } } /** {@collect.stats} * Invoked when the list is layed out horizontally to determine how * many columns to create. * <p> * This updates the <code>rowsPerColumn, </code><code>columnCount</code>, * <code>preferredHeight</code> and potentially <code>cellHeight</code> * instance variables. */ private void updateHorizontalLayoutState(int fixedCellWidth, int fixedCellHeight) { int visRows = list.getVisibleRowCount(); int dataModelSize = list.getModel().getSize(); Insets insets = list.getInsets(); listHeight = list.getHeight(); listWidth = list.getWidth(); if (dataModelSize == 0) { rowsPerColumn = columnCount = 0; preferredHeight = insets.top + insets.bottom; return; } int height; if (fixedCellHeight != -1) { height = fixedCellHeight; } else { // Determine the max of the renderer heights. int maxHeight = 0; if (cellHeights.length > 0) { maxHeight = cellHeights[cellHeights.length - 1]; for (int counter = cellHeights.length - 2; counter >= 0; counter--) { maxHeight = Math.max(maxHeight, cellHeights[counter]); } } height = cellHeight = maxHeight; cellHeights = null; } // The number of rows is either determined by the visible row // count, or by the height of the list. rowsPerColumn = dataModelSize; if (visRows > 0) { rowsPerColumn = visRows; columnCount = Math.max(1, dataModelSize / rowsPerColumn); if (dataModelSize > 0 && dataModelSize > rowsPerColumn && dataModelSize % rowsPerColumn != 0) { columnCount++; } if (layoutOrientation == JList.HORIZONTAL_WRAP) { // Because HORIZONTAL_WRAP flows differently, the // rowsPerColumn needs to be adjusted. rowsPerColumn = (dataModelSize / columnCount); if (dataModelSize % columnCount > 0) { rowsPerColumn++; } } } else if (layoutOrientation == JList.VERTICAL_WRAP && height != 0) { rowsPerColumn = Math.max(1, (listHeight - insets.top - insets.bottom) / height); columnCount = Math.max(1, dataModelSize / rowsPerColumn); if (dataModelSize > 0 && dataModelSize > rowsPerColumn && dataModelSize % rowsPerColumn != 0) { columnCount++; } } else if (layoutOrientation == JList.HORIZONTAL_WRAP && cellWidth > 0 && listWidth > 0) { columnCount = Math.max(1, (listWidth - insets.left - insets.right) / cellWidth); rowsPerColumn = dataModelSize / columnCount; if (dataModelSize % columnCount > 0) { rowsPerColumn++; } } preferredHeight = rowsPerColumn * cellHeight + insets.top + insets.bottom; } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } /** {@collect.stats} * Mouse input, and focus handling for JList. An instance of this * class is added to the appropriate java.awt.Component lists * at installUI() time. Note keyboard input is handled with JComponent * KeyboardActions, see installKeyboardActions(). * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @see #createMouseInputListener * @see #installKeyboardActions * @see #installUI */ public class MouseInputHandler implements MouseInputListener { public void mouseClicked(MouseEvent e) { getHandler().mouseClicked(e); } public void mouseEntered(MouseEvent e) { getHandler().mouseEntered(e); } public void mouseExited(MouseEvent e) { getHandler().mouseExited(e); } public void mousePressed(MouseEvent e) { getHandler().mousePressed(e); } public void mouseDragged(MouseEvent e) { getHandler().mouseDragged(e); } public void mouseMoved(MouseEvent e) { getHandler().mouseMoved(e); } public void mouseReleased(MouseEvent e) { getHandler().mouseReleased(e); } } /** {@collect.stats} * Creates a delegate that implements MouseInputListener. * The delegate is added to the corresponding java.awt.Component listener * lists at installUI() time. Subclasses can override this method to return * a custom MouseInputListener, e.g. * <pre> * class MyListUI extends BasicListUI { * protected MouseInputListener <b>createMouseInputListener</b>() { * return new MyMouseInputHandler(); * } * public class MyMouseInputHandler extends MouseInputHandler { * public void mouseMoved(MouseEvent e) { * // do some extra work when the mouse moves * super.mouseMoved(e); * } * } * } * </pre> * * @see MouseInputHandler * @see #installUI */ protected MouseInputListener createMouseInputListener() { return getHandler(); } /** {@collect.stats} * This inner class is marked &quot;public&quot; due to a compiler bug. * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of BasicTableUI. */ public class FocusHandler implements FocusListener { protected void repaintCellFocus() { getHandler().repaintCellFocus(); } /* The focusGained() focusLost() methods run when the JList * focus changes. */ public void focusGained(FocusEvent e) { getHandler().focusGained(e); } public void focusLost(FocusEvent e) { getHandler().focusLost(e); } } protected FocusListener createFocusListener() { return getHandler(); } /** {@collect.stats} * The ListSelectionListener that's added to the JLists selection * model at installUI time, and whenever the JList.selectionModel property * changes. When the selection changes we repaint the affected rows. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @see #createListSelectionListener * @see #getCellBounds * @see #installUI */ public class ListSelectionHandler implements ListSelectionListener { public void valueChanged(ListSelectionEvent e) { getHandler().valueChanged(e); } } /** {@collect.stats} * Creates an instance of ListSelectionHandler that's added to * the JLists by selectionModel as needed. Subclasses can override * this method to return a custom ListSelectionListener, e.g. * <pre> * class MyListUI extends BasicListUI { * protected ListSelectionListener <b>createListSelectionListener</b>() { * return new MySelectionListener(); * } * public class MySelectionListener extends ListSelectionHandler { * public void valueChanged(ListSelectionEvent e) { * // do some extra work when the selection changes * super.valueChange(e); * } * } * } * </pre> * * @see ListSelectionHandler * @see #installUI */ protected ListSelectionListener createListSelectionListener() { return getHandler(); } private void redrawList() { list.revalidate(); list.repaint(); } /** {@collect.stats} * The ListDataListener that's added to the JLists model at * installUI time, and whenever the JList.model property changes. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @see JList#getModel * @see #maybeUpdateLayoutState * @see #createListDataListener * @see #installUI */ public class ListDataHandler implements ListDataListener { public void intervalAdded(ListDataEvent e) { getHandler().intervalAdded(e); } public void intervalRemoved(ListDataEvent e) { getHandler().intervalRemoved(e); } public void contentsChanged(ListDataEvent e) { getHandler().contentsChanged(e); } } /** {@collect.stats} * Creates an instance of ListDataListener that's added to * the JLists by model as needed. Subclasses can override * this method to return a custom ListDataListener, e.g. * <pre> * class MyListUI extends BasicListUI { * protected ListDataListener <b>createListDataListener</b>() { * return new MyListDataListener(); * } * public class MyListDataListener extends ListDataHandler { * public void contentsChanged(ListDataEvent e) { * // do some extra work when the models contents change * super.contentsChange(e); * } * } * } * </pre> * * @see ListDataListener * @see JList#getModel * @see #installUI */ protected ListDataListener createListDataListener() { return getHandler(); } /** {@collect.stats} * The PropertyChangeListener that's added to the JList at * installUI time. When the value of a JList property that * affects layout changes, we set a bit in updateLayoutStateNeeded. * If the JLists model changes we additionally remove our listeners * from the old model. Likewise for the JList selectionModel. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @see #maybeUpdateLayoutState * @see #createPropertyChangeListener * @see #installUI */ public class PropertyChangeHandler implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent e) { getHandler().propertyChange(e); } } /** {@collect.stats} * Creates an instance of PropertyChangeHandler that's added to * the JList by installUI(). Subclasses can override this method * to return a custom PropertyChangeListener, e.g. * <pre> * class MyListUI extends BasicListUI { * protected PropertyChangeListener <b>createPropertyChangeListener</b>() { * return new MyPropertyChangeListener(); * } * public class MyPropertyChangeListener extends PropertyChangeHandler { * public void propertyChange(PropertyChangeEvent e) { * if (e.getPropertyName().equals("model")) { * // do some extra work when the model changes * } * super.propertyChange(e); * } * } * } * </pre> * * @see PropertyChangeListener * @see #installUI */ protected PropertyChangeListener createPropertyChangeListener() { return getHandler(); } /** {@collect.stats} Used by IncrementLeadSelectionAction. Indicates the action should * change the lead, and not select it. */ private static final int CHANGE_LEAD = 0; /** {@collect.stats} Used by IncrementLeadSelectionAction. Indicates the action should * change the selection and lead. */ private static final int CHANGE_SELECTION = 1; /** {@collect.stats} Used by IncrementLeadSelectionAction. Indicates the action should * extend the selection from the anchor to the next index. */ private static final int EXTEND_SELECTION = 2; private static class Actions extends UIAction { private static final String SELECT_PREVIOUS_COLUMN = "selectPreviousColumn"; private static final String SELECT_PREVIOUS_COLUMN_EXTEND = "selectPreviousColumnExtendSelection"; private static final String SELECT_PREVIOUS_COLUMN_CHANGE_LEAD = "selectPreviousColumnChangeLead"; private static final String SELECT_NEXT_COLUMN = "selectNextColumn"; private static final String SELECT_NEXT_COLUMN_EXTEND = "selectNextColumnExtendSelection"; private static final String SELECT_NEXT_COLUMN_CHANGE_LEAD = "selectNextColumnChangeLead"; private static final String SELECT_PREVIOUS_ROW = "selectPreviousRow"; private static final String SELECT_PREVIOUS_ROW_EXTEND = "selectPreviousRowExtendSelection"; private static final String SELECT_PREVIOUS_ROW_CHANGE_LEAD = "selectPreviousRowChangeLead"; private static final String SELECT_NEXT_ROW = "selectNextRow"; private static final String SELECT_NEXT_ROW_EXTEND = "selectNextRowExtendSelection"; private static final String SELECT_NEXT_ROW_CHANGE_LEAD = "selectNextRowChangeLead"; private static final String SELECT_FIRST_ROW = "selectFirstRow"; private static final String SELECT_FIRST_ROW_EXTEND = "selectFirstRowExtendSelection"; private static final String SELECT_FIRST_ROW_CHANGE_LEAD = "selectFirstRowChangeLead"; private static final String SELECT_LAST_ROW = "selectLastRow"; private static final String SELECT_LAST_ROW_EXTEND = "selectLastRowExtendSelection"; private static final String SELECT_LAST_ROW_CHANGE_LEAD = "selectLastRowChangeLead"; private static final String SCROLL_UP = "scrollUp"; private static final String SCROLL_UP_EXTEND = "scrollUpExtendSelection"; private static final String SCROLL_UP_CHANGE_LEAD = "scrollUpChangeLead"; private static final String SCROLL_DOWN = "scrollDown"; private static final String SCROLL_DOWN_EXTEND = "scrollDownExtendSelection"; private static final String SCROLL_DOWN_CHANGE_LEAD = "scrollDownChangeLead"; private static final String SELECT_ALL = "selectAll"; private static final String CLEAR_SELECTION = "clearSelection"; // add the lead item to the selection without changing lead or anchor private static final String ADD_TO_SELECTION = "addToSelection"; // toggle the selected state of the lead item and move the anchor to it private static final String TOGGLE_AND_ANCHOR = "toggleAndAnchor"; // extend the selection to the lead item private static final String EXTEND_TO = "extendTo"; // move the anchor to the lead and ensure only that item is selected private static final String MOVE_SELECTION_TO = "moveSelectionTo"; Actions(String name) { super(name); } public void actionPerformed(ActionEvent e) { String name = getName(); JList list = (JList)e.getSource(); BasicListUI ui = (BasicListUI)BasicLookAndFeel.getUIOfType( list.getUI(), BasicListUI.class); if (name == SELECT_PREVIOUS_COLUMN) { changeSelection(list, CHANGE_SELECTION, getNextColumnIndex(list, ui, -1), -1); } else if (name == SELECT_PREVIOUS_COLUMN_EXTEND) { changeSelection(list, EXTEND_SELECTION, getNextColumnIndex(list, ui, -1), -1); } else if (name == SELECT_PREVIOUS_COLUMN_CHANGE_LEAD) { changeSelection(list, CHANGE_LEAD, getNextColumnIndex(list, ui, -1), -1); } else if (name == SELECT_NEXT_COLUMN) { changeSelection(list, CHANGE_SELECTION, getNextColumnIndex(list, ui, 1), 1); } else if (name == SELECT_NEXT_COLUMN_EXTEND) { changeSelection(list, EXTEND_SELECTION, getNextColumnIndex(list, ui, 1), 1); } else if (name == SELECT_NEXT_COLUMN_CHANGE_LEAD) { changeSelection(list, CHANGE_LEAD, getNextColumnIndex(list, ui, 1), 1); } else if (name == SELECT_PREVIOUS_ROW) { changeSelection(list, CHANGE_SELECTION, getNextIndex(list, ui, -1), -1); } else if (name == SELECT_PREVIOUS_ROW_EXTEND) { changeSelection(list, EXTEND_SELECTION, getNextIndex(list, ui, -1), -1); } else if (name == SELECT_PREVIOUS_ROW_CHANGE_LEAD) { changeSelection(list, CHANGE_LEAD, getNextIndex(list, ui, -1), -1); } else if (name == SELECT_NEXT_ROW) { changeSelection(list, CHANGE_SELECTION, getNextIndex(list, ui, 1), 1); } else if (name == SELECT_NEXT_ROW_EXTEND) { changeSelection(list, EXTEND_SELECTION, getNextIndex(list, ui, 1), 1); } else if (name == SELECT_NEXT_ROW_CHANGE_LEAD) { changeSelection(list, CHANGE_LEAD, getNextIndex(list, ui, 1), 1); } else if (name == SELECT_FIRST_ROW) { changeSelection(list, CHANGE_SELECTION, 0, -1); } else if (name == SELECT_FIRST_ROW_EXTEND) { changeSelection(list, EXTEND_SELECTION, 0, -1); } else if (name == SELECT_FIRST_ROW_CHANGE_LEAD) { changeSelection(list, CHANGE_LEAD, 0, -1); } else if (name == SELECT_LAST_ROW) { changeSelection(list, CHANGE_SELECTION, list.getModel().getSize() - 1, 1); } else if (name == SELECT_LAST_ROW_EXTEND) { changeSelection(list, EXTEND_SELECTION, list.getModel().getSize() - 1, 1); } else if (name == SELECT_LAST_ROW_CHANGE_LEAD) { changeSelection(list, CHANGE_LEAD, list.getModel().getSize() - 1, 1); } else if (name == SCROLL_UP) { changeSelection(list, CHANGE_SELECTION, getNextPageIndex(list, -1), -1); } else if (name == SCROLL_UP_EXTEND) { changeSelection(list, EXTEND_SELECTION, getNextPageIndex(list, -1), -1); } else if (name == SCROLL_UP_CHANGE_LEAD) { changeSelection(list, CHANGE_LEAD, getNextPageIndex(list, -1), -1); } else if (name == SCROLL_DOWN) { changeSelection(list, CHANGE_SELECTION, getNextPageIndex(list, 1), 1); } else if (name == SCROLL_DOWN_EXTEND) { changeSelection(list, EXTEND_SELECTION, getNextPageIndex(list, 1), 1); } else if (name == SCROLL_DOWN_CHANGE_LEAD) { changeSelection(list, CHANGE_LEAD, getNextPageIndex(list, 1), 1); } else if (name == SELECT_ALL) { selectAll(list); } else if (name == CLEAR_SELECTION) { clearSelection(list); } else if (name == ADD_TO_SELECTION) { int index = adjustIndex( list.getSelectionModel().getLeadSelectionIndex(), list); if (!list.isSelectedIndex(index)) { int oldAnchor = list.getSelectionModel().getAnchorSelectionIndex(); list.setValueIsAdjusting(true); list.addSelectionInterval(index, index); list.getSelectionModel().setAnchorSelectionIndex(oldAnchor); list.setValueIsAdjusting(false); } } else if (name == TOGGLE_AND_ANCHOR) { int index = adjustIndex( list.getSelectionModel().getLeadSelectionIndex(), list); if (list.isSelectedIndex(index)) { list.removeSelectionInterval(index, index); } else { list.addSelectionInterval(index, index); } } else if (name == EXTEND_TO) { changeSelection( list, EXTEND_SELECTION, adjustIndex(list.getSelectionModel().getLeadSelectionIndex(), list), 0); } else if (name == MOVE_SELECTION_TO) { changeSelection( list, CHANGE_SELECTION, adjustIndex(list.getSelectionModel().getLeadSelectionIndex(), list), 0); } } public boolean isEnabled(Object c) { Object name = getName(); if (name == SELECT_PREVIOUS_COLUMN_CHANGE_LEAD || name == SELECT_NEXT_COLUMN_CHANGE_LEAD || name == SELECT_PREVIOUS_ROW_CHANGE_LEAD || name == SELECT_NEXT_ROW_CHANGE_LEAD || name == SELECT_FIRST_ROW_CHANGE_LEAD || name == SELECT_LAST_ROW_CHANGE_LEAD || name == SCROLL_UP_CHANGE_LEAD || name == SCROLL_DOWN_CHANGE_LEAD) { // discontinuous selection actions are only enabled for // DefaultListSelectionModel return c != null && ((JList)c).getSelectionModel() instanceof DefaultListSelectionModel; } return true; } private void clearSelection(JList list) { list.clearSelection(); } private void selectAll(JList list) { int size = list.getModel().getSize(); if (size > 0) { ListSelectionModel lsm = list.getSelectionModel(); int lead = adjustIndex(lsm.getLeadSelectionIndex(), list); if (lsm.getSelectionMode() == ListSelectionModel.SINGLE_SELECTION) { if (lead == -1) { int min = adjustIndex(list.getMinSelectionIndex(), list); lead = (min == -1 ? 0 : min); } list.setSelectionInterval(lead, lead); list.ensureIndexIsVisible(lead); } else { list.setValueIsAdjusting(true); int anchor = adjustIndex(lsm.getAnchorSelectionIndex(), list); list.setSelectionInterval(0, size - 1); // this is done to restore the anchor and lead SwingUtilities2.setLeadAnchorWithoutSelection(lsm, anchor, lead); list.setValueIsAdjusting(false); } } } private int getNextPageIndex(JList list, int direction) { if (list.getModel().getSize() == 0) { return -1; } int index = -1; Rectangle visRect = list.getVisibleRect(); ListSelectionModel lsm = list.getSelectionModel(); int lead = adjustIndex(lsm.getLeadSelectionIndex(), list); Rectangle leadRect = (lead==-1) ? new Rectangle() : list.getCellBounds(lead, lead); if (list.getLayoutOrientation() == JList.VERTICAL_WRAP && list.getVisibleRowCount() <= 0) { if (!list.getComponentOrientation().isLeftToRight()) { direction = -direction; } // apply for horizontal scrolling: the step for next // page index is number of visible columns if (direction < 0) { // left visRect.x = leadRect.x + leadRect.width - visRect.width; Point p = new Point(visRect.x - 1, leadRect.y); index = list.locationToIndex(p); Rectangle cellBounds = list.getCellBounds(index, index); if (visRect.intersects(cellBounds)) { p.x = cellBounds.x - 1; index = list.locationToIndex(p); cellBounds = list.getCellBounds(index, index); } // this is necessary for right-to-left orientation only if (cellBounds.y != leadRect.y) { p.x = cellBounds.x + cellBounds.width; index = list.locationToIndex(p); } } else { // right visRect.x = leadRect.x; Point p = new Point(visRect.x + visRect.width, leadRect.y); index = list.locationToIndex(p); Rectangle cellBounds = list.getCellBounds(index, index); if (visRect.intersects(cellBounds)) { p.x = cellBounds.x + cellBounds.width; index = list.locationToIndex(p); cellBounds = list.getCellBounds(index, index); } if (cellBounds.y != leadRect.y) { p.x = cellBounds.x - 1; index = list.locationToIndex(p); } } } else { if (direction < 0) { // up // go to the first visible cell Point p = new Point(leadRect.x, visRect.y); index = list.locationToIndex(p); if (lead <= index) { // if lead is the first visible cell (or above it) // adjust the visible rect up visRect.y = leadRect.y + leadRect.height - visRect.height; p.y = visRect.y; index = list.locationToIndex(p); Rectangle cellBounds = list.getCellBounds(index, index); // go one cell down if first visible cell doesn't fit // into adjasted visible rectangle if (cellBounds.y < visRect.y) { p.y = cellBounds.y + cellBounds.height; index = list.locationToIndex(p); cellBounds = list.getCellBounds(index, index); } // if index isn't less then lead // try to go to cell previous to lead if (cellBounds.y >= leadRect.y) { p.y = leadRect.y - 1; index = list.locationToIndex(p); } } } else { // down // go to the last completely visible cell Point p = new Point(leadRect.x, visRect.y + visRect.height - 1); index = list.locationToIndex(p); Rectangle cellBounds = list.getCellBounds(index, index); // go up one cell if last visible cell doesn't fit // into visible rectangle if (cellBounds.y + cellBounds.height > visRect.y + visRect.height) { p.y = cellBounds.y - 1; index = list.locationToIndex(p); cellBounds = list.getCellBounds(index, index); index = Math.max(index, lead); } if (lead >= index) { // if lead is the last completely visible index // (or below it) adjust the visible rect down visRect.y = leadRect.y; p.y = visRect.y + visRect.height - 1; index = list.locationToIndex(p); cellBounds = list.getCellBounds(index, index); // go one cell up if last visible cell doesn't fit // into adjasted visible rectangle if (cellBounds.y + cellBounds.height > visRect.y + visRect.height) { p.y = cellBounds.y - 1; index = list.locationToIndex(p); cellBounds = list.getCellBounds(index, index); } // if index isn't greater then lead // try to go to cell next after lead if (cellBounds.y <= leadRect.y) { p.y = leadRect.y + leadRect.height; index = list.locationToIndex(p); } } } } return index; } private void changeSelection(JList list, int type, int index, int direction) { if (index >= 0 && index < list.getModel().getSize()) { ListSelectionModel lsm = list.getSelectionModel(); // CHANGE_LEAD is only valid with multiple interval selection if (type == CHANGE_LEAD && list.getSelectionMode() != ListSelectionModel.MULTIPLE_INTERVAL_SELECTION) { type = CHANGE_SELECTION; } // IMPORTANT - This needs to happen before the index is changed. // This is because JFileChooser, which uses JList, also scrolls // the selected item into view. If that happens first, then // this method becomes a no-op. adjustScrollPositionIfNecessary(list, index, direction); if (type == EXTEND_SELECTION) { int anchor = adjustIndex(lsm.getAnchorSelectionIndex(), list); if (anchor == -1) { anchor = 0; } list.setSelectionInterval(anchor, index); } else if (type == CHANGE_SELECTION) { list.setSelectedIndex(index); } else { // casting should be safe since the action is only enabled // for DefaultListSelectionModel ((DefaultListSelectionModel)lsm).moveLeadSelectionIndex(index); } } } /** {@collect.stats} * When scroll down makes selected index the last completely visible * index. When scroll up makes selected index the first visible index. * Adjust visible rectangle respect to list's component orientation. */ private void adjustScrollPositionIfNecessary(JList list, int index, int direction) { if (direction == 0) { return; } Rectangle cellBounds = list.getCellBounds(index, index); Rectangle visRect = list.getVisibleRect(); if (cellBounds != null && !visRect.contains(cellBounds)) { if (list.getLayoutOrientation() == JList.VERTICAL_WRAP && list.getVisibleRowCount() <= 0) { // horizontal if (list.getComponentOrientation().isLeftToRight()) { if (direction > 0) { // right for left-to-right int x =Math.max(0, cellBounds.x + cellBounds.width - visRect.width); int startIndex = list.locationToIndex(new Point(x, cellBounds.y)); Rectangle startRect = list.getCellBounds(startIndex, startIndex); if (startRect.x < x && startRect.x < cellBounds.x) { startRect.x += startRect.width; startIndex = list.locationToIndex(startRect.getLocation()); startRect = list.getCellBounds(startIndex, startIndex); } cellBounds = startRect; } cellBounds.width = visRect.width; } else { if (direction > 0) { // left for right-to-left int x = cellBounds.x + visRect.width; int rightIndex = list.locationToIndex(new Point(x, cellBounds.y)); Rectangle rightRect = list.getCellBounds(rightIndex, rightIndex); if (rightRect.x + rightRect.width > x && rightRect.x > cellBounds.x) { rightRect.width = 0; } cellBounds.x = Math.max(0, rightRect.x + rightRect.width - visRect.width); cellBounds.width = visRect.width; } else { cellBounds.x += Math.max(0, cellBounds.width - visRect.width); // adjust width to fit into visible rectangle cellBounds.width = Math.min(cellBounds.width, visRect.width); } } } else { // vertical if (direction > 0) { //down int y = Math.max(0, cellBounds.y + cellBounds.height - visRect.height); int startIndex = list.locationToIndex(new Point(cellBounds.x, y)); Rectangle startRect = list.getCellBounds(startIndex, startIndex); if (startRect.y < y && startRect.y < cellBounds.y) { startRect.y += startRect.height; startIndex = list.locationToIndex(startRect.getLocation()); startRect = list.getCellBounds(startIndex, startIndex); } cellBounds = startRect; cellBounds.height = visRect.height; } else { // adjust height to fit into visible rectangle cellBounds.height = Math.min(cellBounds.height, visRect.height); } } list.scrollRectToVisible(cellBounds); } } private int getNextColumnIndex(JList list, BasicListUI ui, int amount) { if (list.getLayoutOrientation() != JList.VERTICAL) { int index = adjustIndex(list.getLeadSelectionIndex(), list); int size = list.getModel().getSize(); if (index == -1) { return 0; } else if (size == 1) { // there's only one item so we should select it return 0; } else if (ui == null || ui.columnCount <= 1) { return -1; } int column = ui.convertModelToColumn(index); int row = ui.convertModelToRow(index); column += amount; if (column >= ui.columnCount || column < 0) { // No wrapping. return -1; } int maxRowCount = ui.getRowCount(column); if (row >= maxRowCount) { return -1; } return ui.getModelIndex(column, row); } // Won't change the selection. return -1; } private int getNextIndex(JList list, BasicListUI ui, int amount) { int index = adjustIndex(list.getLeadSelectionIndex(), list); int size = list.getModel().getSize(); if (index == -1) { if (size > 0) { if (amount > 0) { index = 0; } else { index = size - 1; } } } else if (size == 1) { // there's only one item so we should select it index = 0; } else if (list.getLayoutOrientation() == JList.HORIZONTAL_WRAP) { if (ui != null) { index += ui.columnCount * amount; } } else { index += amount; } return index; } } private class Handler implements FocusListener, KeyListener, ListDataListener, ListSelectionListener, MouseInputListener, PropertyChangeListener, BeforeDrag { // // KeyListener // private String prefix = ""; private String typedString = ""; private long lastTime = 0L; /** {@collect.stats} * Invoked when a key has been typed. * * Moves the keyboard focus to the first element whose prefix matches the * sequence of alphanumeric keys pressed by the user with delay less * than value of <code>timeFactor</code> property (or 1000 milliseconds * if it is not defined). Subsequent same key presses move the keyboard * focus to the next object that starts with the same letter until another * key is pressed, then it is treated as the prefix with appropriate number * of the same letters followed by first typed another letter. */ public void keyTyped(KeyEvent e) { JList src = (JList)e.getSource(); ListModel model = src.getModel(); if (model.getSize() == 0 || e.isAltDown() || e.isControlDown() || e.isMetaDown() || isNavigationKey(e)) { // Nothing to select return; } boolean startingFromSelection = true; char c = e.getKeyChar(); long time = e.getWhen(); int startIndex = adjustIndex(src.getLeadSelectionIndex(), list); if (time - lastTime < timeFactor) { typedString += c; if((prefix.length() == 1) && (c == prefix.charAt(0))) { // Subsequent same key presses move the keyboard focus to the next // object that starts with the same letter. startIndex++; } else { prefix = typedString; } } else { startIndex++; typedString = "" + c; prefix = typedString; } lastTime = time; if (startIndex < 0 || startIndex >= model.getSize()) { startingFromSelection = false; startIndex = 0; } int index = src.getNextMatch(prefix, startIndex, Position.Bias.Forward); if (index >= 0) { src.setSelectedIndex(index); src.ensureIndexIsVisible(index); } else if (startingFromSelection) { // wrap index = src.getNextMatch(prefix, 0, Position.Bias.Forward); if (index >= 0) { src.setSelectedIndex(index); src.ensureIndexIsVisible(index); } } } /** {@collect.stats} * Invoked when a key has been pressed. * * Checks to see if the key event is a navigation key to prevent * dispatching these keys for the first letter navigation. */ public void keyPressed(KeyEvent e) { if ( isNavigationKey(e) ) { prefix = ""; typedString = ""; lastTime = 0L; } } /** {@collect.stats} * Invoked when a key has been released. * See the class description for {@link KeyEvent} for a definition of * a key released event. */ public void keyReleased(KeyEvent e) { } /** {@collect.stats} * Returns whether or not the supplied key event maps to a key that is used for * navigation. This is used for optimizing key input by only passing non- * navigation keys to the first letter navigation mechanism. */ private boolean isNavigationKey(KeyEvent event) { InputMap inputMap = list.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); KeyStroke key = KeyStroke.getKeyStrokeForEvent(event); if (inputMap != null && inputMap.get(key) != null) { return true; } return false; } // // PropertyChangeListener // public void propertyChange(PropertyChangeEvent e) { String propertyName = e.getPropertyName(); /* If the JList.model property changes, remove our listener, * listDataListener from the old model and add it to the new one. */ if (propertyName == "model") { ListModel oldModel = (ListModel)e.getOldValue(); ListModel newModel = (ListModel)e.getNewValue(); if (oldModel != null) { oldModel.removeListDataListener(listDataListener); } if (newModel != null) { newModel.addListDataListener(listDataListener); } updateLayoutStateNeeded |= modelChanged; redrawList(); } /* If the JList.selectionModel property changes, remove our listener, * listSelectionListener from the old selectionModel and add it to the new one. */ else if (propertyName == "selectionModel") { ListSelectionModel oldModel = (ListSelectionModel)e.getOldValue(); ListSelectionModel newModel = (ListSelectionModel)e.getNewValue(); if (oldModel != null) { oldModel.removeListSelectionListener(listSelectionListener); } if (newModel != null) { newModel.addListSelectionListener(listSelectionListener); } updateLayoutStateNeeded |= modelChanged; redrawList(); } else if (propertyName == "cellRenderer") { updateLayoutStateNeeded |= cellRendererChanged; redrawList(); } else if (propertyName == "font") { updateLayoutStateNeeded |= fontChanged; redrawList(); } else if (propertyName == "prototypeCellValue") { updateLayoutStateNeeded |= prototypeCellValueChanged; redrawList(); } else if (propertyName == "fixedCellHeight") { updateLayoutStateNeeded |= fixedCellHeightChanged; redrawList(); } else if (propertyName == "fixedCellWidth") { updateLayoutStateNeeded |= fixedCellWidthChanged; redrawList(); } else if (propertyName == "selectionForeground") { list.repaint(); } else if (propertyName == "selectionBackground") { list.repaint(); } else if ("layoutOrientation" == propertyName) { updateLayoutStateNeeded |= layoutOrientationChanged; layoutOrientation = list.getLayoutOrientation(); redrawList(); } else if ("visibleRowCount" == propertyName) { if (layoutOrientation != JList.VERTICAL) { updateLayoutStateNeeded |= layoutOrientationChanged; redrawList(); } } else if ("componentOrientation" == propertyName) { isLeftToRight = list.getComponentOrientation().isLeftToRight(); updateLayoutStateNeeded |= componentOrientationChanged; redrawList(); InputMap inputMap = getInputMap(JComponent.WHEN_FOCUSED); SwingUtilities.replaceUIInputMap(list, JComponent.WHEN_FOCUSED, inputMap); } else if ("List.isFileList" == propertyName) { updateIsFileList(); redrawList(); } else if ("dropLocation" == propertyName) { JList.DropLocation oldValue = (JList.DropLocation)e.getOldValue(); repaintDropLocation(oldValue); repaintDropLocation(list.getDropLocation()); } } private void repaintDropLocation(JList.DropLocation loc) { if (loc == null) { return; } Rectangle r; if (loc.isInsert()) { r = getDropLineRect(loc); } else { r = getCellBounds(list, loc.getIndex()); } if (r != null) { list.repaint(r); } } // // ListDataListener // public void intervalAdded(ListDataEvent e) { updateLayoutStateNeeded = modelChanged; int minIndex = Math.min(e.getIndex0(), e.getIndex1()); int maxIndex = Math.max(e.getIndex0(), e.getIndex1()); /* Sync the SelectionModel with the DataModel. */ ListSelectionModel sm = list.getSelectionModel(); if (sm != null) { sm.insertIndexInterval(minIndex, maxIndex - minIndex+1, true); } /* Repaint the entire list, from the origin of * the first added cell, to the bottom of the * component. */ redrawList(); } public void intervalRemoved(ListDataEvent e) { updateLayoutStateNeeded = modelChanged; /* Sync the SelectionModel with the DataModel. */ ListSelectionModel sm = list.getSelectionModel(); if (sm != null) { sm.removeIndexInterval(e.getIndex0(), e.getIndex1()); } /* Repaint the entire list, from the origin of * the first removed cell, to the bottom of the * component. */ redrawList(); } public void contentsChanged(ListDataEvent e) { updateLayoutStateNeeded = modelChanged; redrawList(); } // // ListSelectionListener // public void valueChanged(ListSelectionEvent e) { maybeUpdateLayoutState(); int size = list.getModel().getSize(); int firstIndex = Math.min(size - 1, Math.max(e.getFirstIndex(), 0)); int lastIndex = Math.min(size - 1, Math.max(e.getLastIndex(), 0)); Rectangle bounds = getCellBounds(list, firstIndex, lastIndex); if (bounds != null) { list.repaint(bounds.x, bounds.y, bounds.width, bounds.height); } } // // MouseListener // public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } // Whether or not the mouse press (which is being considered as part // of a drag sequence) also caused the selection change to be fully // processed. private boolean dragPressDidSelection; public void mousePressed(MouseEvent e) { if (SwingUtilities2.shouldIgnore(e, list)) { return; } boolean dragEnabled = list.getDragEnabled(); boolean grabFocus = true; // different behavior if drag is enabled if (dragEnabled) { int row = SwingUtilities2.loc2IndexFileList(list, e.getPoint()); // if we have a valid row and this is a drag initiating event if (row != -1 && DragRecognitionSupport.mousePressed(e)) { dragPressDidSelection = false; if (e.isControlDown()) { // do nothing for control - will be handled on release // or when drag starts return; } else if (!e.isShiftDown() && list.isSelectedIndex(row)) { // clicking on something that's already selected // and need to make it the lead now list.addSelectionInterval(row, row); return; } // could be a drag initiating event - don't grab focus grabFocus = false; dragPressDidSelection = true; } } else { // When drag is enabled mouse drags won't change the selection // in the list, so we only set the isAdjusting flag when it's // not enabled list.setValueIsAdjusting(true); } if (grabFocus) { SwingUtilities2.adjustFocus(list); } adjustSelection(e); } private void adjustSelection(MouseEvent e) { int row = SwingUtilities2.loc2IndexFileList(list, e.getPoint()); if (row < 0) { // If shift is down in multi-select, we should do nothing. // For single select or non-shift-click, clear the selection if (isFileList && e.getID() == MouseEvent.MOUSE_PRESSED && (!e.isShiftDown() || list.getSelectionMode() == ListSelectionModel.SINGLE_SELECTION)) { list.clearSelection(); } } else { int anchorIndex = adjustIndex(list.getAnchorSelectionIndex(), list); boolean anchorSelected; if (anchorIndex == -1) { anchorIndex = 0; anchorSelected = false; } else { anchorSelected = list.isSelectedIndex(anchorIndex); } if (e.isControlDown()) { if (e.isShiftDown()) { if (anchorSelected) { list.addSelectionInterval(anchorIndex, row); } else { list.removeSelectionInterval(anchorIndex, row); if (isFileList) { list.addSelectionInterval(row, row); list.getSelectionModel().setAnchorSelectionIndex(anchorIndex); } } } else if (list.isSelectedIndex(row)) { list.removeSelectionInterval(row, row); } else { list.addSelectionInterval(row, row); } } else if (e.isShiftDown()) { list.setSelectionInterval(anchorIndex, row); } else { list.setSelectionInterval(row, row); } } } public void dragStarting(MouseEvent me) { if (me.isControlDown()) { int row = SwingUtilities2.loc2IndexFileList(list, me.getPoint()); list.addSelectionInterval(row, row); } } public void mouseDragged(MouseEvent e) { if (SwingUtilities2.shouldIgnore(e, list)) { return; } if (list.getDragEnabled()) { DragRecognitionSupport.mouseDragged(e, this); return; } if (e.isShiftDown() || e.isControlDown()) { return; } int row = locationToIndex(list, e.getPoint()); if (row != -1) { // 4835633. Dragging onto a File should not select it. if (isFileList) { return; } Rectangle cellBounds = getCellBounds(list, row, row); if (cellBounds != null) { list.scrollRectToVisible(cellBounds); list.setSelectionInterval(row, row); } } } public void mouseMoved(MouseEvent e) { } public void mouseReleased(MouseEvent e) { if (SwingUtilities2.shouldIgnore(e, list)) { return; } if (list.getDragEnabled()) { MouseEvent me = DragRecognitionSupport.mouseReleased(e); if (me != null) { SwingUtilities2.adjustFocus(list); if (!dragPressDidSelection) { adjustSelection(me); } } } else { list.setValueIsAdjusting(false); } } // // FocusListener // protected void repaintCellFocus() { int leadIndex = adjustIndex(list.getLeadSelectionIndex(), list); if (leadIndex != -1) { Rectangle r = getCellBounds(list, leadIndex, leadIndex); if (r != null) { list.repaint(r.x, r.y, r.width, r.height); } } } /* The focusGained() focusLost() methods run when the JList * focus changes. */ public void focusGained(FocusEvent e) { repaintCellFocus(); } public void focusLost(FocusEvent e) { repaintCellFocus(); } } private static int adjustIndex(int index, JList list) { return index < list.getModel().getSize() ? index : -1; } private static final TransferHandler defaultTransferHandler = new ListTransferHandler(); static class ListTransferHandler extends TransferHandler implements UIResource { /** {@collect.stats} * Create a Transferable to use as the source for a data transfer. * * @param c The component holding the data to be transfered. This * argument is provided to enable sharing of TransferHandlers by * multiple components. * @return The representation of the data to be transfered. * */ protected Transferable createTransferable(JComponent c) { if (c instanceof JList) { JList list = (JList) c; Object[] values = list.getSelectedValues(); if (values == null || values.length == 0) { return null; } StringBuffer plainBuf = new StringBuffer(); StringBuffer htmlBuf = new StringBuffer(); htmlBuf.append("<html>\n<body>\n<ul>\n"); for (int i = 0; i < values.length; i++) { Object obj = values[i]; String val = ((obj == null) ? "" : obj.toString()); plainBuf.append(val + "\n"); htmlBuf.append(" <li>" + val + "\n"); } // remove the last newline plainBuf.deleteCharAt(plainBuf.length() - 1); htmlBuf.append("</ul>\n</body>\n</html>"); return new BasicTransferable(plainBuf.toString(), htmlBuf.toString()); } return null; } public int getSourceActions(JComponent c) { return COPY; } } }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import sun.swing.SwingUtilities2; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.*; import javax.swing.BorderFactory; import javax.swing.border.Border; import javax.swing.plaf.ToolTipUI; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.UIResource; import javax.swing.text.View; /** {@collect.stats} * Standard tool tip L&F. * <p> * * @author Dave Moore */ public class BasicToolTipUI extends ToolTipUI { static BasicToolTipUI sharedInstance = new BasicToolTipUI(); /** {@collect.stats} * Global <code>PropertyChangeListener</code> that * <code>createPropertyChangeListener</code> returns. */ private static PropertyChangeListener sharedPropertyChangedListener; private PropertyChangeListener propertyChangeListener; public static ComponentUI createUI(JComponent c) { return sharedInstance; } public BasicToolTipUI() { super(); } public void installUI(JComponent c) { installDefaults(c); installComponents(c); installListeners(c); } public void uninstallUI(JComponent c) { // REMIND: this is NOT getting called uninstallDefaults(c); uninstallComponents(c); uninstallListeners(c); } protected void installDefaults(JComponent c){ LookAndFeel.installColorsAndFont(c, "ToolTip.background", "ToolTip.foreground", "ToolTip.font"); LookAndFeel.installProperty(c, "opaque", Boolean.TRUE); componentChanged(c); } protected void uninstallDefaults(JComponent c){ LookAndFeel.uninstallBorder(c); } /* Unfortunately this has to remain private until we can make API additions. */ private void installComponents(JComponent c){ BasicHTML.updateRenderer(c, ((JToolTip)c).getTipText()); } /* Unfortunately this has to remain private until we can make API additions. */ private void uninstallComponents(JComponent c){ BasicHTML.updateRenderer(c, ""); } protected void installListeners(JComponent c) { propertyChangeListener = createPropertyChangeListener(c); c.addPropertyChangeListener(propertyChangeListener); } protected void uninstallListeners(JComponent c) { c.removePropertyChangeListener(propertyChangeListener); propertyChangeListener = null; } /* Unfortunately this has to remain private until we can make API additions. */ private PropertyChangeListener createPropertyChangeListener(JComponent c) { if (sharedPropertyChangedListener == null) { sharedPropertyChangedListener = new PropertyChangeHandler(); } return sharedPropertyChangedListener; } public void paint(Graphics g, JComponent c) { Font font = c.getFont(); FontMetrics metrics = SwingUtilities2.getFontMetrics(c, g, font); Dimension size = c.getSize(); g.setColor(c.getForeground()); // fix for bug 4153892 String tipText = ((JToolTip)c).getTipText(); if (tipText == null) { tipText = ""; } Insets insets = c.getInsets(); Rectangle paintTextR = new Rectangle( insets.left + 3, insets.top, size.width - (insets.left + insets.right) - 6, size.height - (insets.top + insets.bottom)); View v = (View) c.getClientProperty(BasicHTML.propertyKey); if (v != null) { v.paint(g, paintTextR); } else { g.setFont(font); SwingUtilities2.drawString(c, g, tipText, paintTextR.x, paintTextR.y + metrics.getAscent()); } } public Dimension getPreferredSize(JComponent c) { Font font = c.getFont(); FontMetrics fm = c.getFontMetrics(font); Insets insets = c.getInsets(); Dimension prefSize = new Dimension(insets.left+insets.right, insets.top+insets.bottom); String text = ((JToolTip)c).getTipText(); if ((text == null) || text.equals("")) { text = ""; } else { View v = (c != null) ? (View) c.getClientProperty("html") : null; if (v != null) { prefSize.width += (int) v.getPreferredSpan(View.X_AXIS) + 6; prefSize.height += (int) v.getPreferredSpan(View.Y_AXIS); } else { prefSize.width += SwingUtilities2.stringWidth(c,fm,text) + 6; prefSize.height += fm.getHeight(); } } return prefSize; } public Dimension getMinimumSize(JComponent c) { Dimension d = getPreferredSize(c); View v = (View) c.getClientProperty(BasicHTML.propertyKey); if (v != null) { d.width -= v.getPreferredSpan(View.X_AXIS) - v.getMinimumSpan(View.X_AXIS); } return d; } public Dimension getMaximumSize(JComponent c) { Dimension d = getPreferredSize(c); View v = (View) c.getClientProperty(BasicHTML.propertyKey); if (v != null) { d.width += v.getMaximumSpan(View.X_AXIS) - v.getPreferredSpan(View.X_AXIS); } return d; } /** {@collect.stats} * Invoked when the <code>JCompoment</code> associated with the * <code>JToolTip</code> has changed, or at initialization time. This * should update any state dependant upon the <code>JComponent</code>. * * @param c the JToolTip the JComponent has changed on. */ private void componentChanged(JComponent c) { JComponent comp = ((JToolTip)c).getComponent(); if (comp != null && !(comp.isEnabled())) { // For better backward compatability, only install inactive // properties if they are defined. if (UIManager.getBorder("ToolTip.borderInactive") != null) { LookAndFeel.installBorder(c, "ToolTip.borderInactive"); } else { LookAndFeel.installBorder(c, "ToolTip.border"); } if (UIManager.getColor("ToolTip.backgroundInactive") != null) { LookAndFeel.installColors(c,"ToolTip.backgroundInactive", "ToolTip.foregroundInactive"); } else { LookAndFeel.installColors(c,"ToolTip.background", "ToolTip.foreground"); } } else { LookAndFeel.installBorder(c, "ToolTip.border"); LookAndFeel.installColors(c, "ToolTip.background", "ToolTip.foreground"); } } private static class PropertyChangeHandler implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent e) { String name = e.getPropertyName(); if (name.equals("tiptext") || "font".equals(name) || "foreground".equals(name)) { // remove the old html view client property if one // existed, and install a new one if the text installed // into the JLabel is html source. JToolTip tip = ((JToolTip) e.getSource()); String text = tip.getTipText(); BasicHTML.updateRenderer(tip, text); } else if ("component".equals(name)) { JToolTip tip = ((JToolTip) e.getSource()); if (tip.getUI() instanceof BasicToolTipUI) { ((BasicToolTipUI)tip.getUI()).componentChanged(tip); } } } } }
Java
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.swing.*; import javax.swing.plaf.UIResource; import java.awt.Graphics; import java.awt.Color; import java.awt.Component; import java.awt.Polygon; import java.io.Serializable; /** {@collect.stats} * Factory object that can vend Icons appropriate for the basic L & F. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author David Kloba * @author Georges Saab */ public class BasicIconFactory implements Serializable { private static Icon frame_icon; private static Icon checkBoxIcon; private static Icon radioButtonIcon; private static Icon checkBoxMenuItemIcon; private static Icon radioButtonMenuItemIcon; private static Icon menuItemCheckIcon; private static Icon menuItemArrowIcon; private static Icon menuArrowIcon; public static Icon getMenuItemCheckIcon() { if (menuItemCheckIcon == null) { menuItemCheckIcon = new MenuItemCheckIcon(); } return menuItemCheckIcon; } public static Icon getMenuItemArrowIcon() { if (menuItemArrowIcon == null) { menuItemArrowIcon = new MenuItemArrowIcon(); } return menuItemArrowIcon; } public static Icon getMenuArrowIcon() { if (menuArrowIcon == null) { menuArrowIcon = new MenuArrowIcon(); } return menuArrowIcon; } public static Icon getCheckBoxIcon() { if (checkBoxIcon == null) { checkBoxIcon = new CheckBoxIcon(); } return checkBoxIcon; } public static Icon getRadioButtonIcon() { if (radioButtonIcon == null) { radioButtonIcon = new RadioButtonIcon(); } return radioButtonIcon; } public static Icon getCheckBoxMenuItemIcon() { if (checkBoxMenuItemIcon == null) { checkBoxMenuItemIcon = new CheckBoxMenuItemIcon(); } return checkBoxMenuItemIcon; } public static Icon getRadioButtonMenuItemIcon() { if (radioButtonMenuItemIcon == null) { radioButtonMenuItemIcon = new RadioButtonMenuItemIcon(); } return radioButtonMenuItemIcon; } public static Icon createEmptyFrameIcon() { if(frame_icon == null) frame_icon = new EmptyFrameIcon(); return frame_icon; } private static class EmptyFrameIcon implements Icon, Serializable { int height = 16; int width = 14; public void paintIcon(Component c, Graphics g, int x, int y) { } public int getIconWidth() { return width; } public int getIconHeight() { return height; } }; private static class CheckBoxIcon implements Icon, Serializable { final static int csize = 13; public void paintIcon(Component c, Graphics g, int x, int y) { } public int getIconWidth() { return csize; } public int getIconHeight() { return csize; } } private static class RadioButtonIcon implements Icon, UIResource, Serializable { public void paintIcon(Component c, Graphics g, int x, int y) { } public int getIconWidth() { return 13; } public int getIconHeight() { return 13; } } // end class RadioButtonIcon private static class CheckBoxMenuItemIcon implements Icon, UIResource, Serializable { public void paintIcon(Component c, Graphics g, int x, int y) { AbstractButton b = (AbstractButton) c; ButtonModel model = b.getModel(); boolean isSelected = model.isSelected(); if (isSelected) { g.drawLine(x+7, y+1, x+7, y+3); g.drawLine(x+6, y+2, x+6, y+4); g.drawLine(x+5, y+3, x+5, y+5); g.drawLine(x+4, y+4, x+4, y+6); g.drawLine(x+3, y+5, x+3, y+7); g.drawLine(x+2, y+4, x+2, y+6); g.drawLine(x+1, y+3, x+1, y+5); } } public int getIconWidth() { return 9; } public int getIconHeight() { return 9; } } // End class CheckBoxMenuItemIcon private static class RadioButtonMenuItemIcon implements Icon, UIResource, Serializable { public void paintIcon(Component c, Graphics g, int x, int y) { AbstractButton b = (AbstractButton) c; ButtonModel model = b.getModel(); if (b.isSelected() == true) { g.fillOval(x+1, y+1, getIconWidth(), getIconHeight()); } } public int getIconWidth() { return 6; } public int getIconHeight() { return 6; } } // End class RadioButtonMenuItemIcon private static class MenuItemCheckIcon implements Icon, UIResource, Serializable{ public void paintIcon(Component c, Graphics g, int x, int y) { } public int getIconWidth() { return 9; } public int getIconHeight() { return 9; } } // End class MenuItemCheckIcon private static class MenuItemArrowIcon implements Icon, UIResource, Serializable { public void paintIcon(Component c, Graphics g, int x, int y) { } public int getIconWidth() { return 4; } public int getIconHeight() { return 8; } } // End class MenuItemArrowIcon private static class MenuArrowIcon implements Icon, UIResource, Serializable { public void paintIcon(Component c, Graphics g, int x, int y) { Polygon p = new Polygon(); p.addPoint(x, y); p.addPoint(x+getIconWidth(), y+getIconHeight()/2); p.addPoint(x, y+getIconHeight()); g.fillPolygon(p); } public int getIconWidth() { return 4; } public int getIconHeight() { return 8; } } // End class MenuArrowIcon }
Java
/* * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.io.*; import java.awt.*; import java.net.URL; import javax.swing.*; import javax.swing.text.*; import javax.swing.text.html.*; import sun.swing.SwingUtilities2; /** {@collect.stats} * Support for providing html views for the swing components. * This translates a simple html string to a javax.swing.text.View * implementation that can render the html and provide the necessary * layout semantics. * * @author Timothy Prinzing * @since 1.3 */ public class BasicHTML { /** {@collect.stats} * Create an html renderer for the given component and * string of html. */ public static View createHTMLView(JComponent c, String html) { BasicEditorKit kit = getFactory(); Document doc = kit.createDefaultDocument(c.getFont(), c.getForeground()); Object base = c.getClientProperty(documentBaseKey); if (base instanceof URL) { ((HTMLDocument)doc).setBase((URL)base); } Reader r = new StringReader(html); try { kit.read(r, doc, 0); } catch (Throwable e) { } ViewFactory f = kit.getViewFactory(); View hview = f.create(doc.getDefaultRootElement()); View v = new Renderer(c, f, hview); return v; } /** {@collect.stats} * Returns the baseline for the html renderer. * * @param view the View to get the baseline for * @param w the width to get the baseline for * @param h the height to get the baseline for * @throws IllegalArgumentException if width or height is &lt; 0 * @return baseline or a value &lt; 0 indicating there is no reasonable * baseline * @see java.awt.FontMetrics * @see javax.swing.JComponent#getBaseline(int,int) * @since 1.6 */ public static int getHTMLBaseline(View view, int w, int h) { if (w < 0 || h < 0) { throw new IllegalArgumentException( "Width and height must be >= 0"); } if (view instanceof Renderer) { return getBaseline(view.getView(0), w, h); } return -1; } /** {@collect.stats} * Gets the baseline for the specified component. This digs out * the View client property, and if non-null the baseline is calculated * from it. Otherwise the baseline is the value <code>y + ascent</code>. */ static int getBaseline(JComponent c, int y, int ascent, int w, int h) { View view = (View)c.getClientProperty(BasicHTML.propertyKey); if (view != null) { int baseline = getHTMLBaseline(view, w, h); if (baseline < 0) { return baseline; } return y + baseline; } return y + ascent; } /** {@collect.stats} * Gets the baseline for the specified View. */ static int getBaseline(View view, int w, int h) { if (hasParagraph(view)) { view.setSize(w, h); return getBaseline(view, new Rectangle(0, 0, w, h)); } return -1; } private static int getBaseline(View view, Shape bounds) { if (view.getViewCount() == 0) { return -1; } AttributeSet attributes = view.getElement().getAttributes(); Object name = null; if (attributes != null) { name = attributes.getAttribute(StyleConstants.NameAttribute); } int index = 0; if (name == HTML.Tag.HTML && view.getViewCount() > 1) { // For html on widgets the header is not visible, skip it. index++; } bounds = view.getChildAllocation(index, bounds); if (bounds == null) { return -1; } View child = view.getView(index); if (view instanceof javax.swing.text.ParagraphView) { Rectangle rect; if (bounds instanceof Rectangle) { rect = (Rectangle)bounds; } else { rect = bounds.getBounds(); } return rect.y + (int)(rect.height * child.getAlignment(View.Y_AXIS)); } return getBaseline(child, bounds); } private static boolean hasParagraph(View view) { if (view instanceof javax.swing.text.ParagraphView) { return true; } if (view.getViewCount() == 0) { return false; } AttributeSet attributes = view.getElement().getAttributes(); Object name = null; if (attributes != null) { name = attributes.getAttribute(StyleConstants.NameAttribute); } int index = 0; if (name == HTML.Tag.HTML && view.getViewCount() > 1) { // For html on widgets the header is not visible, skip it. index = 1; } return hasParagraph(view.getView(index)); } /** {@collect.stats} * Check the given string to see if it should trigger the * html rendering logic in a non-text component that supports * html rendering. */ public static boolean isHTMLString(String s) { if (s != null) { if ((s.length() >= 6) && (s.charAt(0) == '<') && (s.charAt(5) == '>')) { String tag = s.substring(1,5); return tag.equalsIgnoreCase(propertyKey); } } return false; } /** {@collect.stats} * Stash the HTML render for the given text into the client * properties of the given JComponent. If the given text is * <em>NOT HTML</em> the property will be cleared of any * renderer. * <p> * This method is useful for ComponentUI implementations * that are static (i.e. shared) and get their state * entirely from the JComponent. */ public static void updateRenderer(JComponent c, String text) { View value = null; View oldValue = (View)c.getClientProperty(BasicHTML.propertyKey); Boolean htmlDisabled = (Boolean) c.getClientProperty(htmlDisable); if (htmlDisabled != Boolean.TRUE && BasicHTML.isHTMLString(text)) { value = BasicHTML.createHTMLView(c, text); } if (value != oldValue && oldValue != null) { for (int i = 0; i < oldValue.getViewCount(); i++) { oldValue.getView(i).setParent(null); } } c.putClientProperty(BasicHTML.propertyKey, value); } /** {@collect.stats} * If this client property of a JComponent is set to Boolean.TRUE * the component's 'text' property is never treated as HTML. */ private static final String htmlDisable = "html.disable"; /** {@collect.stats} * Key to use for the html renderer when stored as a * client property of a JComponent. */ public static final String propertyKey = "html"; /** {@collect.stats} * Key stored as a client property to indicate the base that relative * references are resolved against. For example, lets say you keep * your images in the directory resources relative to the code path, * you would use the following the set the base: * <pre> * jComponent.putClientProperty(documentBaseKey, * xxx.class.getResource("resources/")); * </pre> */ public static final String documentBaseKey = "html.base"; static BasicEditorKit getFactory() { if (basicHTMLFactory == null) { basicHTMLViewFactory = new BasicHTMLViewFactory(); basicHTMLFactory = new BasicEditorKit(); } return basicHTMLFactory; } /** {@collect.stats} * The source of the html renderers */ private static BasicEditorKit basicHTMLFactory; /** {@collect.stats} * Creates the Views that visually represent the model. */ private static ViewFactory basicHTMLViewFactory; /** {@collect.stats} * Overrides to the default stylesheet. Should consider * just creating a completely fresh stylesheet. */ private static final String styleChanges = "p { margin-top: 0; margin-bottom: 0; margin-left: 0; margin-right: 0 }" + "body { margin-top: 0; margin-bottom: 0; margin-left: 0; margin-right: 0 }"; /** {@collect.stats} * The views produced for the ComponentUI implementations aren't * going to be edited and don't need full html support. This kit * alters the HTMLEditorKit to try and trim things down a bit. * It does the following: * <ul> * <li>It doesn't produce Views for things like comments, * head, title, unknown tags, etc. * <li>It installs a different set of css settings from the default * provided by HTMLEditorKit. * </ul> */ static class BasicEditorKit extends HTMLEditorKit { /** {@collect.stats} Shared base style for all documents created by us use. */ private static StyleSheet defaultStyles; /** {@collect.stats} * Overriden to return our own slimmed down style sheet. */ public StyleSheet getStyleSheet() { if (defaultStyles == null) { defaultStyles = new StyleSheet(); StringReader r = new StringReader(styleChanges); try { defaultStyles.loadRules(r, null); } catch (Throwable e) { // don't want to die in static initialization... // just display things wrong. } r.close(); defaultStyles.addStyleSheet(super.getStyleSheet()); } return defaultStyles; } /** {@collect.stats} * Sets the async policy to flush everything in one chunk, and * to not display unknown tags. */ public Document createDefaultDocument(Font defaultFont, Color foreground) { StyleSheet styles = getStyleSheet(); StyleSheet ss = new StyleSheet(); ss.addStyleSheet(styles); BasicDocument doc = new BasicDocument(ss, defaultFont, foreground); doc.setAsynchronousLoadPriority(Integer.MAX_VALUE); doc.setPreservesUnknownTags(false); return doc; } /** {@collect.stats} * Returns the ViewFactory that is used to make sure the Views don't * load in the background. */ public ViewFactory getViewFactory() { return basicHTMLViewFactory; } } /** {@collect.stats} * BasicHTMLViewFactory extends HTMLFactory to force images to be loaded * synchronously. */ static class BasicHTMLViewFactory extends HTMLEditorKit.HTMLFactory { public View create(Element elem) { View view = super.create(elem); if (view instanceof ImageView) { ((ImageView)view).setLoadsSynchronously(true); } return view; } } /** {@collect.stats} * The subclass of HTMLDocument that is used as the model. getForeground * is overridden to return the foreground property from the Component this * was created for. */ static class BasicDocument extends HTMLDocument { /** {@collect.stats} The host, that is where we are rendering. */ // private JComponent host; BasicDocument(StyleSheet s, Font defaultFont, Color foreground) { super(s); setPreservesUnknownTags(false); setFontAndColor(defaultFont, foreground); } /** {@collect.stats} * Sets the default font and default color. These are set by * adding a rule for the body that specifies the font and color. * This allows the html to override these should it wish to have * a custom font or color. */ private void setFontAndColor(Font font, Color fg) { getStyleSheet().addRule(sun.swing.SwingUtilities2. displayPropertiesToCSS(font,fg)); } } /** {@collect.stats} * Root text view that acts as an HTML renderer. */ static class Renderer extends View { Renderer(JComponent c, ViewFactory f, View v) { super(null); host = c; factory = f; view = v; view.setParent(this); // initially layout to the preferred size setSize(view.getPreferredSpan(X_AXIS), view.getPreferredSpan(Y_AXIS)); } /** {@collect.stats} * Fetches the attributes to use when rendering. At the root * level there are no attributes. If an attribute is resolved * up the view hierarchy this is the end of the line. */ public AttributeSet getAttributes() { return null; } /** {@collect.stats} * Determines the preferred span for this view along an axis. * * @param axis may be either X_AXIS or Y_AXIS * @return the span the view would like to be rendered into. * Typically the view is told to render into the span * that is returned, although there is no guarantee. * The parent may choose to resize or break the view. */ public float getPreferredSpan(int axis) { if (axis == X_AXIS) { // width currently laid out to return width; } return view.getPreferredSpan(axis); } /** {@collect.stats} * Determines the minimum span for this view along an axis. * * @param axis may be either X_AXIS or Y_AXIS * @return the span the view would like to be rendered into. * Typically the view is told to render into the span * that is returned, although there is no guarantee. * The parent may choose to resize or break the view. */ public float getMinimumSpan(int axis) { return view.getMinimumSpan(axis); } /** {@collect.stats} * Determines the maximum span for this view along an axis. * * @param axis may be either X_AXIS or Y_AXIS * @return the span the view would like to be rendered into. * Typically the view is told to render into the span * that is returned, although there is no guarantee. * The parent may choose to resize or break the view. */ public float getMaximumSpan(int axis) { return Integer.MAX_VALUE; } /** {@collect.stats} * Specifies that a preference has changed. * Child views can call this on the parent to indicate that * the preference has changed. The root view routes this to * invalidate on the hosting component. * <p> * This can be called on a different thread from the * event dispatching thread and is basically unsafe to * propagate into the component. To make this safe, * the operation is transferred over to the event dispatching * thread for completion. It is a design goal that all view * methods be safe to call without concern for concurrency, * and this behavior helps make that true. * * @param child the child view * @param width true if the width preference has changed * @param height true if the height preference has changed */ public void preferenceChanged(View child, boolean width, boolean height) { host.revalidate(); host.repaint(); } /** {@collect.stats} * Determines the desired alignment for this view along an axis. * * @param axis may be either X_AXIS or Y_AXIS * @return the desired alignment, where 0.0 indicates the origin * and 1.0 the full span away from the origin */ public float getAlignment(int axis) { return view.getAlignment(axis); } /** {@collect.stats} * Renders the view. * * @param g the graphics context * @param allocation the region to render into */ public void paint(Graphics g, Shape allocation) { Rectangle alloc = allocation.getBounds(); view.setSize(alloc.width, alloc.height); view.paint(g, allocation); } /** {@collect.stats} * Sets the view parent. * * @param parent the parent view */ public void setParent(View parent) { throw new Error("Can't set parent on root view"); } /** {@collect.stats} * Returns the number of views in this view. Since * this view simply wraps the root of the view hierarchy * it has exactly one child. * * @return the number of views * @see #getView */ public int getViewCount() { return 1; } /** {@collect.stats} * Gets the n-th view in this container. * * @param n the number of the view to get * @return the view */ public View getView(int n) { return view; } /** {@collect.stats} * Provides a mapping from the document model coordinate space * to the coordinate space of the view mapped to it. * * @param pos the position to convert * @param a the allocated region to render into * @return the bounding box of the given position */ public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException { return view.modelToView(pos, a, b); } /** {@collect.stats} * Provides a mapping from the document model coordinate space * to the coordinate space of the view mapped to it. * * @param p0 the position to convert >= 0 * @param b0 the bias toward the previous character or the * next character represented by p0, in case the * position is a boundary of two views. * @param p1 the position to convert >= 0 * @param b1 the bias toward the previous character or the * next character represented by p1, in case the * position is a boundary of two views. * @param a the allocated region to render into * @return the bounding box of the given position is returned * @exception BadLocationException if the given position does * not represent a valid location in the associated document * @exception IllegalArgumentException for an invalid bias argument * @see View#viewToModel */ public Shape modelToView(int p0, Position.Bias b0, int p1, Position.Bias b1, Shape a) throws BadLocationException { return view.modelToView(p0, b0, p1, b1, a); } /** {@collect.stats} * Provides a mapping from the view coordinate space to the logical * coordinate space of the model. * * @param x x coordinate of the view location to convert * @param y y coordinate of the view location to convert * @param a the allocated region to render into * @return the location within the model that best represents the * given point in the view */ public int viewToModel(float x, float y, Shape a, Position.Bias[] bias) { return view.viewToModel(x, y, a, bias); } /** {@collect.stats} * Returns the document model underlying the view. * * @return the model */ public Document getDocument() { return view.getDocument(); } /** {@collect.stats} * Returns the starting offset into the model for this view. * * @return the starting offset */ public int getStartOffset() { return view.getStartOffset(); } /** {@collect.stats} * Returns the ending offset into the model for this view. * * @return the ending offset */ public int getEndOffset() { return view.getEndOffset(); } /** {@collect.stats} * Gets the element that this view is mapped to. * * @return the view */ public Element getElement() { return view.getElement(); } /** {@collect.stats} * Sets the view size. * * @param width the width * @param height the height */ public void setSize(float width, float height) { this.width = (int) width; view.setSize(width, height); } /** {@collect.stats} * Fetches the container hosting the view. This is useful for * things like scheduling a repaint, finding out the host * components font, etc. The default implementation * of this is to forward the query to the parent view. * * @return the container */ public Container getContainer() { return host; } /** {@collect.stats} * Fetches the factory to be used for building the * various view fragments that make up the view that * represents the model. This is what determines * how the model will be represented. This is implemented * to fetch the factory provided by the associated * EditorKit. * * @return the factory */ public ViewFactory getViewFactory() { return factory; } private int width; private View view; private ViewFactory factory; private JComponent host; } }
Java
/* * Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.swing.*; import javax.swing.plaf.ComponentUI; /** {@collect.stats} * Provides the look and feel implementation for * <code>JFormattedTextField</code>. * * @since 1.4 */ public class BasicFormattedTextFieldUI extends BasicTextFieldUI { /** {@collect.stats} * Creates a UI for a JFormattedTextField. * * @param c the formatted text field * @return the UI */ public static ComponentUI createUI(JComponent c) { return new BasicFormattedTextFieldUI(); } /** {@collect.stats} * Fetches the name used as a key to lookup properties through the * UIManager. This is used as a prefix to all the standard * text properties. * * @return the name "FormattedTextField" */ protected String getPropertyPrefix() { return "FormattedTextField"; } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import sun.swing.DefaultLookup; import sun.swing.UIAction; import java.awt.*; import java.awt.event.*; import java.beans.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.ActionMapUIResource; import javax.swing.plaf.ButtonUI; import javax.swing.plaf.ComponentInputMapUIResource; /** {@collect.stats} * Button Listener * * @author Jeff Dinkins * @author Arnaud Weber (keyboard UI support) */ public class BasicButtonListener implements MouseListener, MouseMotionListener, FocusListener, ChangeListener, PropertyChangeListener { private long lastPressedTimestamp = -1; private boolean shouldDiscardRelease = false; /** {@collect.stats} * Populates Buttons actions. */ static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.PRESS)); map.put(new Actions(Actions.RELEASE)); } public BasicButtonListener(AbstractButton b) { } public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); if(prop == AbstractButton.MNEMONIC_CHANGED_PROPERTY) { updateMnemonicBinding((AbstractButton)e.getSource()); } else if(prop == AbstractButton.CONTENT_AREA_FILLED_CHANGED_PROPERTY) { checkOpacity((AbstractButton) e.getSource() ); } else if(prop == AbstractButton.TEXT_CHANGED_PROPERTY || "font" == prop || "foreground" == prop) { AbstractButton b = (AbstractButton) e.getSource(); BasicHTML.updateRenderer(b, b.getText()); } } protected void checkOpacity(AbstractButton b) { b.setOpaque( b.isContentAreaFilled() ); } /** {@collect.stats} * Register default key actions: pressing space to "click" a * button and registring the keyboard mnemonic (if any). */ public void installKeyboardActions(JComponent c) { AbstractButton b = (AbstractButton)c; // Update the mnemonic binding. updateMnemonicBinding(b); LazyActionMap.installLazyActionMap(c, BasicButtonListener.class, "Button.actionMap"); InputMap km = getInputMap(JComponent.WHEN_FOCUSED, c); SwingUtilities.replaceUIInputMap(c, JComponent.WHEN_FOCUSED, km); } /** {@collect.stats} * Unregister's default key actions */ public void uninstallKeyboardActions(JComponent c) { SwingUtilities.replaceUIInputMap(c, JComponent. WHEN_IN_FOCUSED_WINDOW, null); SwingUtilities.replaceUIInputMap(c, JComponent.WHEN_FOCUSED, null); SwingUtilities.replaceUIActionMap(c, null); } /** {@collect.stats} * Returns the InputMap for condition <code>condition</code>. Called as * part of <code>installKeyboardActions</code>. */ InputMap getInputMap(int condition, JComponent c) { if (condition == JComponent.WHEN_FOCUSED) { BasicButtonUI ui = (BasicButtonUI)BasicLookAndFeel.getUIOfType( ((AbstractButton)c).getUI(), BasicButtonUI.class); if (ui != null) { return (InputMap)DefaultLookup.get( c, ui, ui.getPropertyPrefix() + "focusInputMap"); } } return null; } /** {@collect.stats} * Resets the binding for the mnemonic in the WHEN_IN_FOCUSED_WINDOW * UI InputMap. */ void updateMnemonicBinding(AbstractButton b) { int m = b.getMnemonic(); if(m != 0) { InputMap map = SwingUtilities.getUIInputMap( b, JComponent.WHEN_IN_FOCUSED_WINDOW); if (map == null) { map = new ComponentInputMapUIResource(b); SwingUtilities.replaceUIInputMap(b, JComponent.WHEN_IN_FOCUSED_WINDOW, map); } map.clear(); map.put(KeyStroke.getKeyStroke(m, InputEvent.ALT_MASK, false), "pressed"); map.put(KeyStroke.getKeyStroke(m, InputEvent.ALT_MASK, true), "released"); map.put(KeyStroke.getKeyStroke(m, 0, true), "released"); } else { InputMap map = SwingUtilities.getUIInputMap(b, JComponent. WHEN_IN_FOCUSED_WINDOW); if (map != null) { map.clear(); } } } public void stateChanged(ChangeEvent e) { AbstractButton b = (AbstractButton) e.getSource(); b.repaint(); } public void focusGained(FocusEvent e) { AbstractButton b = (AbstractButton) e.getSource(); if (b instanceof JButton && ((JButton)b).isDefaultCapable()) { JRootPane root = b.getRootPane(); if (root != null) { BasicButtonUI ui = (BasicButtonUI)BasicLookAndFeel.getUIOfType( ((AbstractButton)b).getUI(), BasicButtonUI.class); if (ui != null && DefaultLookup.getBoolean(b, ui, ui.getPropertyPrefix() + "defaultButtonFollowsFocus", true)) { root.putClientProperty("temporaryDefaultButton", b); root.setDefaultButton((JButton)b); root.putClientProperty("temporaryDefaultButton", null); } } } b.repaint(); } public void focusLost(FocusEvent e) { AbstractButton b = (AbstractButton) e.getSource(); JRootPane root = b.getRootPane(); if (root != null) { JButton initialDefault = (JButton)root.getClientProperty("initialDefaultButton"); if (b != initialDefault) { BasicButtonUI ui = (BasicButtonUI)BasicLookAndFeel.getUIOfType( ((AbstractButton)b).getUI(), BasicButtonUI.class); if (ui != null && DefaultLookup.getBoolean(b, ui, ui.getPropertyPrefix() + "defaultButtonFollowsFocus", true)) { root.setDefaultButton(initialDefault); } } } ButtonModel model = b.getModel(); model.setArmed(false); model.setPressed(false); b.repaint(); } public void mouseMoved(MouseEvent e) { } public void mouseDragged(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e) ) { AbstractButton b = (AbstractButton) e.getSource(); if(b.contains(e.getX(), e.getY())) { long multiClickThreshhold = b.getMultiClickThreshhold(); long lastTime = lastPressedTimestamp; long currentTime = lastPressedTimestamp = e.getWhen(); if (lastTime != -1 && currentTime - lastTime < multiClickThreshhold) { shouldDiscardRelease = true; return; } ButtonModel model = b.getModel(); if (!model.isEnabled()) { // Disabled buttons ignore all input... return; } if (!model.isArmed()) { // button not armed, should be model.setArmed(true); } model.setPressed(true); if(!b.hasFocus() && b.isRequestFocusEnabled()) { b.requestFocus(); } } } }; public void mouseReleased(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { // Support for multiClickThreshhold if (shouldDiscardRelease) { shouldDiscardRelease = false; return; } AbstractButton b = (AbstractButton) e.getSource(); ButtonModel model = b.getModel(); model.setPressed(false); model.setArmed(false); } }; public void mouseEntered(MouseEvent e) { AbstractButton b = (AbstractButton) e.getSource(); ButtonModel model = b.getModel(); if (b.isRolloverEnabled() && !SwingUtilities.isLeftMouseButton(e)) { model.setRollover(true); } if (model.isPressed()) model.setArmed(true); }; public void mouseExited(MouseEvent e) { AbstractButton b = (AbstractButton) e.getSource(); ButtonModel model = b.getModel(); if(b.isRolloverEnabled()) { model.setRollover(false); } model.setArmed(false); }; /** {@collect.stats} * Actions for Buttons. Two types of action are supported: * pressed: Moves the button to a pressed state * released: Disarms the button. */ private static class Actions extends UIAction { private static final String PRESS = "pressed"; private static final String RELEASE = "released"; Actions(String name) { super(name); } public void actionPerformed(ActionEvent e) { AbstractButton b = (AbstractButton)e.getSource(); String key = getName(); if (key == PRESS) { ButtonModel model = b.getModel(); model.setArmed(true); model.setPressed(true); if(!b.hasFocus()) { b.requestFocus(); } } else if (key == RELEASE) { ButtonModel model = b.getModel(); model.setPressed(false); model.setArmed(false); } } public boolean isEnabled(Object sender) { if(sender != null && (sender instanceof AbstractButton) && !((AbstractButton)sender).getModel().isEnabled()) { return false; } else { return true; } } } }
Java
/* * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import javax.swing.plaf.*; import java.beans.*; import java.util.EventListener; import java.io.Serializable; /** {@collect.stats} * Basic L&F for a minimized window on a desktop. * * @author David Kloba * @author Steve Wilson * @author Rich Schiavi */ public class BasicDesktopIconUI extends DesktopIconUI { protected JInternalFrame.JDesktopIcon desktopIcon; protected JInternalFrame frame; /** {@collect.stats} * The title pane component used in the desktop icon. * * @since 1.5 */ protected JComponent iconPane; MouseInputListener mouseInputListener; public static ComponentUI createUI(JComponent c) { return new BasicDesktopIconUI(); } public BasicDesktopIconUI() { } public void installUI(JComponent c) { desktopIcon = (JInternalFrame.JDesktopIcon)c; frame = desktopIcon.getInternalFrame(); installDefaults(); installComponents(); // Update icon layout if frame is already iconified JInternalFrame f = desktopIcon.getInternalFrame(); if (f.isIcon() && f.getParent() == null) { JDesktopPane desktop = desktopIcon.getDesktopPane(); if (desktop != null) { DesktopManager desktopManager = desktop.getDesktopManager(); if (desktopManager instanceof DefaultDesktopManager) { desktopManager.iconifyFrame(f); } } } installListeners(); JLayeredPane.putLayer(desktopIcon, JLayeredPane.getLayer(frame)); } public void uninstallUI(JComponent c) { uninstallDefaults(); uninstallComponents(); // Force future UI to relayout icon JInternalFrame f = desktopIcon.getInternalFrame(); if (f.isIcon()) { JDesktopPane desktop = desktopIcon.getDesktopPane(); if (desktop != null) { DesktopManager desktopManager = desktop.getDesktopManager(); if (desktopManager instanceof DefaultDesktopManager) { // This will cause DefaultDesktopManager to layout the icon f.putClientProperty("wasIconOnce", null); // Move aside to allow fresh layout of all icons desktopIcon.setLocation(Integer.MIN_VALUE, 0); } } } uninstallListeners(); frame = null; desktopIcon = null; } protected void installComponents() { iconPane = new BasicInternalFrameTitlePane(frame); desktopIcon.setLayout(new BorderLayout()); desktopIcon.add(iconPane, BorderLayout.CENTER); } protected void uninstallComponents() { desktopIcon.remove(iconPane); desktopIcon.setLayout(null); iconPane = null; } protected void installListeners() { mouseInputListener = createMouseInputListener(); desktopIcon.addMouseMotionListener(mouseInputListener); desktopIcon.addMouseListener(mouseInputListener); } protected void uninstallListeners() { desktopIcon.removeMouseMotionListener(mouseInputListener); desktopIcon.removeMouseListener(mouseInputListener); mouseInputListener = null; } protected void installDefaults() { LookAndFeel.installBorder(desktopIcon, "DesktopIcon.border"); LookAndFeel.installProperty(desktopIcon, "opaque", Boolean.TRUE); } protected void uninstallDefaults() { LookAndFeel.uninstallBorder(desktopIcon); } protected MouseInputListener createMouseInputListener() { return new MouseInputHandler(); } public Dimension getPreferredSize(JComponent c) { return desktopIcon.getLayout().preferredLayoutSize(desktopIcon); } public Dimension getMinimumSize(JComponent c) { Dimension dim = new Dimension(iconPane.getMinimumSize()); Border border = frame.getBorder(); if (border != null) { dim.height += border.getBorderInsets(frame).bottom + border.getBorderInsets(frame).top; } return dim; } /** {@collect.stats} * Desktop icons can not be resized. Therefore, we should always * return the minimum size of the desktop icon. * * @see #getMinimumSize */ public Dimension getMaximumSize(JComponent c){ return iconPane.getMaximumSize(); } public Insets getInsets(JComponent c) { JInternalFrame iframe = desktopIcon.getInternalFrame(); Border border = iframe.getBorder(); if(border != null) return border.getBorderInsets(iframe); return new Insets(0,0,0,0); } public void deiconize() { try { frame.setIcon(false); } catch (PropertyVetoException e2) { } } /** {@collect.stats} * Listens for mouse movements and acts on them. * * This inner class is marked &quot;public&quot; due to a compiler bug. * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of <Foo>. */ public class MouseInputHandler extends MouseInputAdapter { // _x & _y are the mousePressed location in absolute coordinate system int _x, _y; // __x & __y are the mousePressed location in source view's coordinate system int __x, __y; Rectangle startingBounds; public void mouseReleased(MouseEvent e) { _x = 0; _y = 0; __x = 0; __y = 0; startingBounds = null; JDesktopPane d; if((d = desktopIcon.getDesktopPane()) != null) { DesktopManager dm = d.getDesktopManager(); dm.endDraggingFrame(desktopIcon); } } public void mousePressed(MouseEvent e) { Point p = SwingUtilities.convertPoint((Component)e.getSource(), e.getX(), e.getY(), null); __x = e.getX(); __y = e.getY(); _x = p.x; _y = p.y; startingBounds = desktopIcon.getBounds(); JDesktopPane d; if((d = desktopIcon.getDesktopPane()) != null) { DesktopManager dm = d.getDesktopManager(); dm.beginDraggingFrame(desktopIcon); } try { frame.setSelected(true); } catch (PropertyVetoException e1) { } if(desktopIcon.getParent() instanceof JLayeredPane) { ((JLayeredPane)desktopIcon.getParent()).moveToFront(desktopIcon); } if(e.getClickCount() > 1) { if(frame.isIconifiable() && frame.isIcon()) { deiconize(); } } } public void mouseMoved(MouseEvent e) {} public void mouseDragged(MouseEvent e) { Point p; int newX, newY, newW, newH; int deltaX; int deltaY; Dimension min; Dimension max; p = SwingUtilities.convertPoint((Component)e.getSource(), e.getX(), e.getY(), null); Insets i = desktopIcon.getInsets(); int pWidth, pHeight; pWidth = ((JComponent)desktopIcon.getParent()).getWidth(); pHeight = ((JComponent)desktopIcon.getParent()).getHeight(); if (startingBounds == null) { // (STEVE) Yucky work around for bug ID 4106552 return; } newX = startingBounds.x - (_x - p.x); newY = startingBounds.y - (_y - p.y); // Make sure we stay in-bounds if(newX + i.left <= -__x) newX = -__x - i.left; if(newY + i.top <= -__y) newY = -__y - i.top; if(newX + __x + i.right > pWidth) newX = pWidth - __x - i.right; if(newY + __y + i.bottom > pHeight) newY = pHeight - __y - i.bottom; JDesktopPane d; if((d = desktopIcon.getDesktopPane()) != null) { DesktopManager dm = d.getDesktopManager(); dm.dragFrame(desktopIcon, newX, newY); } else { moveAndRepaint(desktopIcon, newX, newY, desktopIcon.getWidth(), desktopIcon.getHeight()); } return; } public void moveAndRepaint(JComponent f, int newX, int newY, int newWidth, int newHeight) { Rectangle r = f.getBounds(); f.setBounds(newX, newY, newWidth, newHeight); SwingUtilities.computeUnion(newX, newY, newWidth, newHeight, r); f.getParent().repaint(r.x, r.y, r.width, r.height); } }; /// End MotionListener }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import java.awt.*; import java.io.Serializable; /** {@collect.stats} * ComboBox renderer * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Arnaud Weber */ public class BasicComboBoxRenderer extends JLabel implements ListCellRenderer, Serializable { /** {@collect.stats} * An empty <code>Border</code>. This field might not be used. To change the * <code>Border</code> used by this renderer directly set it using * the <code>setBorder</code> method. */ protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1); private final static Border SAFE_NO_FOCUS_BORDER = new EmptyBorder(1, 1, 1, 1); public BasicComboBoxRenderer() { super(); setOpaque(true); setBorder(getNoFocusBorder()); } private static Border getNoFocusBorder() { if (System.getSecurityManager() != null) { return SAFE_NO_FOCUS_BORDER; } else { return noFocusBorder; } } public Dimension getPreferredSize() { Dimension size; if ((this.getText() == null) || (this.getText().equals( "" ))) { setText( " " ); size = super.getPreferredSize(); setText( "" ); } else { size = super.getPreferredSize(); } return size; } public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { /** {@collect.stats}if (isSelected) { setBackground(UIManager.getColor("ComboBox.selectionBackground")); setForeground(UIManager.getColor("ComboBox.selectionForeground")); } else { setBackground(UIManager.getColor("ComboBox.background")); setForeground(UIManager.getColor("ComboBox.foreground")); }**/ if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } setFont(list.getFont()); if (value instanceof Icon) { setIcon((Icon)value); } else { setText((value == null) ? "" : value.toString()); } return this; } /** {@collect.stats} * A subclass of BasicComboBoxRenderer that implements UIResource. * BasicComboBoxRenderer doesn't implement UIResource * directly so that applications can safely override the * cellRenderer property with BasicListCellRenderer subclasses. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. */ public static class UIResource extends BasicComboBoxRenderer implements javax.swing.plaf.UIResource { } }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.swing.*; import java.awt.Component; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.KeyEvent; import sun.swing.SwingUtilities2; /* * @author Hans Muller */ public class BasicGraphicsUtils { private static final Insets GROOVE_INSETS = new Insets(2, 2, 2, 2); private static final Insets ETCHED_INSETS = new Insets(2, 2, 2, 2); public static void drawEtchedRect(Graphics g, int x, int y, int w, int h, Color shadow, Color darkShadow, Color highlight, Color lightHighlight) { Color oldColor = g.getColor(); // Make no net change to g g.translate(x, y); g.setColor(shadow); g.drawLine(0, 0, w-1, 0); // outer border, top g.drawLine(0, 1, 0, h-2); // outer border, left g.setColor(darkShadow); g.drawLine(1, 1, w-3, 1); // inner border, top g.drawLine(1, 2, 1, h-3); // inner border, left g.setColor(lightHighlight); g.drawLine(w-1, 0, w-1, h-1); // outer border, bottom g.drawLine(0, h-1, w-1, h-1); // outer border, right g.setColor(highlight); g.drawLine(w-2, 1, w-2, h-3); // inner border, right g.drawLine(1, h-2, w-2, h-2); // inner border, bottom g.translate(-x, -y); g.setColor(oldColor); } /** {@collect.stats} * Returns the amount of space taken up by a border drawn by * <code>drawEtchedRect()</code> * * @return the inset of an etched rect */ public static Insets getEtchedInsets() { return ETCHED_INSETS; } public static void drawGroove(Graphics g, int x, int y, int w, int h, Color shadow, Color highlight) { Color oldColor = g.getColor(); // Make no net change to g g.translate(x, y); g.setColor(shadow); g.drawRect(0, 0, w-2, h-2); g.setColor(highlight); g.drawLine(1, h-3, 1, 1); g.drawLine(1, 1, w-3, 1); g.drawLine(0, h-1, w-1, h-1); g.drawLine(w-1, h-1, w-1, 0); g.translate(-x, -y); g.setColor(oldColor); } /** {@collect.stats} * Returns the amount of space taken up by a border drawn by * <code>drawGroove()</code> * * @return the inset of a groove border */ public static Insets getGrooveInsets() { return GROOVE_INSETS; } public static void drawBezel(Graphics g, int x, int y, int w, int h, boolean isPressed, boolean isDefault, Color shadow, Color darkShadow, Color highlight, Color lightHighlight) { Color oldColor = g.getColor(); // Make no net change to g g.translate(x, y); if (isPressed && isDefault) { g.setColor(darkShadow); g.drawRect(0, 0, w - 1, h - 1); g.setColor(shadow); g.drawRect(1, 1, w - 3, h - 3); } else if (isPressed) { drawLoweredBezel(g, x, y, w, h, shadow, darkShadow, highlight, lightHighlight); } else if (isDefault) { g.setColor(darkShadow); g.drawRect(0, 0, w-1, h-1); g.setColor(lightHighlight); g.drawLine(1, 1, 1, h-3); g.drawLine(2, 1, w-3, 1); g.setColor(highlight); g.drawLine(2, 2, 2, h-4); g.drawLine(3, 2, w-4, 2); g.setColor(shadow); g.drawLine(2, h-3, w-3, h-3); g.drawLine(w-3, 2, w-3, h-4); g.setColor(darkShadow); g.drawLine(1, h-2, w-2, h-2); g.drawLine(w-2, h-2, w-2, 1); } else { g.setColor(lightHighlight); g.drawLine(0, 0, 0, h-1); g.drawLine(1, 0, w-2, 0); g.setColor(highlight); g.drawLine(1, 1, 1, h-3); g.drawLine(2, 1, w-3, 1); g.setColor(shadow); g.drawLine(1, h-2, w-2, h-2); g.drawLine(w-2, 1, w-2, h-3); g.setColor(darkShadow); g.drawLine(0, h-1, w-1, h-1); g.drawLine(w-1, h-1, w-1, 0); } g.translate(-x, -y); g.setColor(oldColor); } public static void drawLoweredBezel(Graphics g, int x, int y, int w, int h, Color shadow, Color darkShadow, Color highlight, Color lightHighlight) { g.setColor(darkShadow); g.drawLine(0, 0, 0, h-1); g.drawLine(1, 0, w-2, 0); g.setColor(shadow); g.drawLine(1, 1, 1, h-2); g.drawLine(1, 1, w-3, 1); g.setColor(lightHighlight); g.drawLine(0, h-1, w-1, h-1); g.drawLine(w-1, h-1, w-1, 0); g.setColor(highlight); g.drawLine(1, h-2, w-2, h-2); g.drawLine(w-2, h-2, w-2, 1); } /** {@collect.stats} Draw a string with the graphics <code>g</code> at location (x,y) * just like <code>g.drawString</code> would. * The first occurrence of <code>underlineChar</code> * in text will be underlined. The matching algorithm is * not case sensitive. */ public static void drawString(Graphics g,String text,int underlinedChar,int x,int y) { int index=-1; if (underlinedChar != '\0') { char uc = Character.toUpperCase((char)underlinedChar); char lc = Character.toLowerCase((char)underlinedChar); int uci = text.indexOf(uc); int lci = text.indexOf(lc); if(uci == -1) { index = lci; } else if(lci == -1) { index = uci; } else { index = (lci < uci) ? lci : uci; } } drawStringUnderlineCharAt(g, text, index, x, y); } /** {@collect.stats} * Draw a string with the graphics <code>g</code> at location * (<code>x</code>, <code>y</code>) * just like <code>g.drawString</code> would. * The character at index <code>underlinedIndex</code> * in text will be underlined. If <code>index</code> is beyond the * bounds of <code>text</code> (including < 0), nothing will be * underlined. * * @param g Graphics to draw with * @param text String to draw * @param underlinedIndex Index of character in text to underline * @param x x coordinate to draw at * @param y y coordinate to draw at * @since 1.4 */ public static void drawStringUnderlineCharAt(Graphics g, String text, int underlinedIndex, int x,int y) { SwingUtilities2.drawStringUnderlineCharAt(null, g, text, underlinedIndex, x, y); } public static void drawDashedRect(Graphics g,int x,int y,int width,int height) { int vx,vy; // draw upper and lower horizontal dashes for (vx = x; vx < (x + width); vx+=2) { g.fillRect(vx, y, 1, 1); g.fillRect(vx, y + height-1, 1, 1); } // draw left and right vertical dashes for (vy = y; vy < (y + height); vy+=2) { g.fillRect(x, vy, 1, 1); g.fillRect(x+width-1, vy, 1, 1); } } public static Dimension getPreferredButtonSize(AbstractButton b, int textIconGap) { if(b.getComponentCount() > 0) { return null; } Icon icon = (Icon) b.getIcon(); String text = b.getText(); Font font = b.getFont(); FontMetrics fm = b.getFontMetrics(font); Rectangle iconR = new Rectangle(); Rectangle textR = new Rectangle(); Rectangle viewR = new Rectangle(Short.MAX_VALUE, Short.MAX_VALUE); SwingUtilities.layoutCompoundLabel( (JComponent) b, fm, text, icon, b.getVerticalAlignment(), b.getHorizontalAlignment(), b.getVerticalTextPosition(), b.getHorizontalTextPosition(), viewR, iconR, textR, (text == null ? 0 : textIconGap) ); /* The preferred size of the button is the size of * the text and icon rectangles plus the buttons insets. */ Rectangle r = iconR.union(textR); Insets insets = b.getInsets(); r.width += insets.left + insets.right; r.height += insets.top + insets.bottom; return r.getSize(); } /* * Convenience function for determining ComponentOrientation. Helps us * avoid having Munge directives throughout the code. */ static boolean isLeftToRight( Component c ) { return c.getComponentOrientation().isLeftToRight(); } }
Java
/* * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.io.File; import java.util.*; import javax.swing.*; import javax.swing.filechooser.*; import javax.swing.event.*; import java.beans.*; import sun.awt.shell.ShellFolder; /** {@collect.stats} * Basic implementation of a file list. * * @author Jeff Dinkins */ public class BasicDirectoryModel extends AbstractListModel implements PropertyChangeListener { private JFileChooser filechooser = null; // PENDING(jeff) pick the size more sensibly private Vector fileCache = new Vector(50); private LoadFilesThread loadThread = null; private Vector files = null; private Vector directories = null; private int fetchID = 0; private PropertyChangeSupport changeSupport; private boolean busy = false; public BasicDirectoryModel(JFileChooser filechooser) { this.filechooser = filechooser; validateFileCache(); } public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); if(prop == JFileChooser.DIRECTORY_CHANGED_PROPERTY || prop == JFileChooser.FILE_VIEW_CHANGED_PROPERTY || prop == JFileChooser.FILE_FILTER_CHANGED_PROPERTY || prop == JFileChooser.FILE_HIDING_CHANGED_PROPERTY || prop == JFileChooser.FILE_SELECTION_MODE_CHANGED_PROPERTY) { validateFileCache(); } else if ("UI".equals(prop)) { Object old = e.getOldValue(); if (old instanceof BasicFileChooserUI) { BasicFileChooserUI ui = (BasicFileChooserUI) old; BasicDirectoryModel model = ui.getModel(); if (model != null) { model.invalidateFileCache(); } } } else if ("JFileChooserDialogIsClosingProperty".equals(prop)) { invalidateFileCache(); } } /** {@collect.stats} * This method is used to interrupt file loading thread. */ public void invalidateFileCache() { if (loadThread != null) { loadThread.interrupt(); loadThread.cancelRunnables(); loadThread = null; } } public Vector<File> getDirectories() { synchronized(fileCache) { if (directories != null) { return directories; } Vector fls = getFiles(); return directories; } } public Vector<File> getFiles() { synchronized(fileCache) { if (files != null) { return files; } files = new Vector(); directories = new Vector(); directories.addElement(filechooser.getFileSystemView().createFileObject( filechooser.getCurrentDirectory(), "..") ); for (int i = 0; i < getSize(); i++) { File f = (File)fileCache.get(i); if (filechooser.isTraversable(f)) { directories.add(f); } else { files.add(f); } } return files; } } public void validateFileCache() { File currentDirectory = filechooser.getCurrentDirectory(); if (currentDirectory == null) { return; } if (loadThread != null) { loadThread.interrupt(); loadThread.cancelRunnables(); } setBusy(true, ++fetchID); loadThread = new LoadFilesThread(currentDirectory, fetchID); loadThread.start(); } /** {@collect.stats} * Renames a file in the underlying file system. * * @param oldFile a <code>File</code> object representing * the existing file * @param newFile a <code>File</code> object representing * the desired new file name * @return <code>true</code> if rename succeeded, * otherwise <code>false</code> * @since 1.4 */ public boolean renameFile(File oldFile, File newFile) { synchronized(fileCache) { if (oldFile.renameTo(newFile)) { validateFileCache(); return true; } return false; } } public void fireContentsChanged() { // System.out.println("BasicDirectoryModel: firecontentschanged"); fireContentsChanged(this, 0, getSize()-1); } public int getSize() { return fileCache.size(); } public boolean contains(Object o) { return fileCache.contains(o); } public int indexOf(Object o) { return fileCache.indexOf(o); } public Object getElementAt(int index) { return fileCache.get(index); } /** {@collect.stats} * Obsolete - not used. */ public void intervalAdded(ListDataEvent e) { } /** {@collect.stats} * Obsolete - not used. */ public void intervalRemoved(ListDataEvent e) { } protected void sort(Vector<? extends File> v){ ShellFolder.sortFiles(v); } // Obsolete - not used protected boolean lt(File a, File b) { // First ignore case when comparing int diff = a.getName().toLowerCase().compareTo(b.getName().toLowerCase()); if (diff != 0) { return diff < 0; } else { // May differ in case (e.g. "mail" vs. "Mail") return a.getName().compareTo(b.getName()) < 0; } } class LoadFilesThread extends Thread { File currentDirectory = null; int fid; Vector runnables = new Vector(10); public LoadFilesThread(File currentDirectory, int fid) { super("Basic L&F File Loading Thread"); this.currentDirectory = currentDirectory; this.fid = fid; } private void invokeLater(Runnable runnable) { runnables.addElement(runnable); SwingUtilities.invokeLater(runnable); } public void run() { run0(); setBusy(false, fid); } public void run0() { try { FileSystemView fileSystem = filechooser.getFileSystemView(); File[] list = fileSystem.getFiles(currentDirectory, filechooser.isFileHidingEnabled()); Vector<File> acceptsList = new Vector<File>(); if (isInterrupted()) { return; } // run through the file list, add directories and selectable files to fileCache for (int i = 0; i < list.length; i++) { if(filechooser.accept(list[i])) { acceptsList.addElement(list[i]); } } if (isInterrupted()) { return; } // First sort alphabetically by filename sort(acceptsList); Vector newDirectories = new Vector(50); Vector newFiles = new Vector(); // run through list grabbing directories in chunks of ten for(int i = 0; i < acceptsList.size(); i++) { File f = (File) acceptsList.elementAt(i); boolean isTraversable = filechooser.isTraversable(f); if (isTraversable) { newDirectories.addElement(f); } else if (!isTraversable && filechooser.isFileSelectionEnabled()) { newFiles.addElement(f); } if(isInterrupted()) { return; } } Vector newFileCache = new Vector(newDirectories); newFileCache.addAll(newFiles); int newSize = newFileCache.size(); int oldSize = fileCache.size(); if (newSize > oldSize) { //see if interval is added int start = oldSize; int end = newSize; for (int i = 0; i < oldSize; i++) { if (!newFileCache.get(i).equals(fileCache.get(i))) { start = i; for (int j = i; j < newSize; j++) { if (newFileCache.get(j).equals(fileCache.get(i))) { end = j; break; } } break; } } if (start >= 0 && end > start && newFileCache.subList(end, newSize).equals(fileCache.subList(start, oldSize))) { if(isInterrupted()) { return; } invokeLater(new DoChangeContents(newFileCache.subList(start, end), start, null, 0, fid)); newFileCache = null; } } else if (newSize < oldSize) { //see if interval is removed int start = -1; int end = -1; for (int i = 0; i < newSize; i++) { if (!newFileCache.get(i).equals(fileCache.get(i))) { start = i; end = i + oldSize - newSize; break; } } if (start >= 0 && end > start && fileCache.subList(end, oldSize).equals(newFileCache.subList(start, newSize))) { if(isInterrupted()) { return; } invokeLater(new DoChangeContents(null, 0, new Vector(fileCache.subList(start, end)), start, fid)); newFileCache = null; } } if (newFileCache != null && !fileCache.equals(newFileCache)) { if (isInterrupted()) { cancelRunnables(runnables); } invokeLater(new DoChangeContents(newFileCache, 0, fileCache, 0, fid)); } } catch (RuntimeException e) { if (!(e.getCause() instanceof InterruptedException /* just exit on interruption */)) { throw e; } } } public void cancelRunnables(Vector runnables) { for(int i = 0; i < runnables.size(); i++) { ((DoChangeContents)runnables.elementAt(i)).cancel(); } } public void cancelRunnables() { cancelRunnables(runnables); } } /** {@collect.stats} * Adds a PropertyChangeListener to the listener list. The listener is * registered for all bound properties of this class. * <p> * If <code>listener</code> is <code>null</code>, * no exception is thrown and no action is performed. * * @param listener the property change listener to be added * * @see #removePropertyChangeListener * @see #getPropertyChangeListeners * * @since 1.6 */ public void addPropertyChangeListener(PropertyChangeListener listener) { if (changeSupport == null) { changeSupport = new PropertyChangeSupport(this); } changeSupport.addPropertyChangeListener(listener); } /** {@collect.stats} * Removes a PropertyChangeListener from the listener list. * <p> * If listener is null, no exception is thrown and no action is performed. * * @param listener the PropertyChangeListener to be removed * * @see #addPropertyChangeListener * @see #getPropertyChangeListeners * * @since 1.6 */ public void removePropertyChangeListener(PropertyChangeListener listener) { if (changeSupport != null) { changeSupport.removePropertyChangeListener(listener); } } /** {@collect.stats} * Returns an array of all the property change listeners * registered on this component. * * @return all of this component's <code>PropertyChangeListener</code>s * or an empty array if no property change * listeners are currently registered * * @see #addPropertyChangeListener * @see #removePropertyChangeListener * @see java.beans.PropertyChangeSupport#getPropertyChangeListeners * * @since 1.6 */ public PropertyChangeListener[] getPropertyChangeListeners() { if (changeSupport == null) { return new PropertyChangeListener[0]; } return changeSupport.getPropertyChangeListeners(); } /** {@collect.stats} * Support for reporting bound property changes for boolean properties. * This method can be called when a bound property has changed and it will * send the appropriate PropertyChangeEvent to any registered * PropertyChangeListeners. * * @param propertyName the property whose value has changed * @param oldValue the property's previous value * @param newValue the property's new value * * @since 1.6 */ protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { if (changeSupport != null) { changeSupport.firePropertyChange(propertyName, oldValue, newValue); } } /** {@collect.stats} * Set the busy state for the model. The model is considered * busy when it is running a separate (interruptable) * thread in order to load the contents of a directory. */ private synchronized void setBusy(final boolean busy, int fid) { if (fid == fetchID) { boolean oldValue = this.busy; this.busy = busy; if (changeSupport != null && busy != oldValue) { SwingUtilities.invokeLater(new Runnable() { public void run() { firePropertyChange("busy", !busy, busy); } }); } } } class DoChangeContents implements Runnable { private List addFiles; private List remFiles; private boolean doFire = true; private int fid; private int addStart = 0; private int remStart = 0; private int change; public DoChangeContents(List addFiles, int addStart, List remFiles, int remStart, int fid) { this.addFiles = addFiles; this.addStart = addStart; this.remFiles = remFiles; this.remStart = remStart; this.fid = fid; } synchronized void cancel() { doFire = false; } public synchronized void run() { if (fetchID == fid && doFire) { int remSize = (remFiles == null) ? 0 : remFiles.size(); int addSize = (addFiles == null) ? 0 : addFiles.size(); synchronized(fileCache) { if (remSize > 0) { fileCache.removeAll(remFiles); } if (addSize > 0) { fileCache.addAll(addStart, addFiles); } files = null; directories = null; } if (remSize > 0 && addSize == 0) { fireIntervalRemoved(BasicDirectoryModel.this, remStart, remStart + remSize - 1); } else if (addSize > 0 && remSize == 0 && fileCache.size() > addSize) { fireIntervalAdded(BasicDirectoryModel.this, addStart, addStart + addSize - 1); } else { fireContentsChanged(); } } } } }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.plaf.*; import javax.swing.text.View; import sun.swing.SwingUtilities2; import sun.awt.AppContext; /** {@collect.stats} * RadioButtonUI implementation for BasicRadioButtonUI * * @author Jeff Dinkins */ public class BasicRadioButtonUI extends BasicToggleButtonUI { private static final Object BASIC_RADIO_BUTTON_UI_KEY = new Object(); protected Icon icon; private boolean defaults_initialized = false; private final static String propertyPrefix = "RadioButton" + "."; // ******************************** // Create PLAF // ******************************** public static ComponentUI createUI(JComponent b) { AppContext appContext = AppContext.getAppContext(); BasicRadioButtonUI radioButtonUI = (BasicRadioButtonUI) appContext.get(BASIC_RADIO_BUTTON_UI_KEY); if (radioButtonUI == null) { radioButtonUI = new BasicRadioButtonUI(); appContext.put(BASIC_RADIO_BUTTON_UI_KEY, radioButtonUI); } return radioButtonUI; } protected String getPropertyPrefix() { return propertyPrefix; } // ******************************** // Install PLAF // ******************************** protected void installDefaults(AbstractButton b){ super.installDefaults(b); if(!defaults_initialized) { icon = UIManager.getIcon(getPropertyPrefix() + "icon"); defaults_initialized = true; } } // ******************************** // Uninstall PLAF // ******************************** protected void uninstallDefaults(AbstractButton b){ super.uninstallDefaults(b); defaults_initialized = false; } public Icon getDefaultIcon() { return icon; } /* These Dimensions/Rectangles are allocated once for all * RadioButtonUI.paint() calls. Re-using rectangles * rather than allocating them in each paint call substantially * reduced the time it took paint to run. Obviously, this * method can't be re-entered. */ private static Dimension size = new Dimension(); private static Rectangle viewRect = new Rectangle(); private static Rectangle iconRect = new Rectangle(); private static Rectangle textRect = new Rectangle(); /** {@collect.stats} * paint the radio button */ public synchronized void paint(Graphics g, JComponent c) { AbstractButton b = (AbstractButton) c; ButtonModel model = b.getModel(); Font f = c.getFont(); g.setFont(f); FontMetrics fm = SwingUtilities2.getFontMetrics(c, g, f); Insets i = c.getInsets(); size = b.getSize(size); viewRect.x = i.left; viewRect.y = i.top; viewRect.width = size.width - (i.right + viewRect.x); viewRect.height = size.height - (i.bottom + viewRect.y); iconRect.x = iconRect.y = iconRect.width = iconRect.height = 0; textRect.x = textRect.y = textRect.width = textRect.height = 0; Icon altIcon = b.getIcon(); Icon selectedIcon = null; Icon disabledIcon = null; String text = SwingUtilities.layoutCompoundLabel( c, fm, b.getText(), altIcon != null ? altIcon : getDefaultIcon(), b.getVerticalAlignment(), b.getHorizontalAlignment(), b.getVerticalTextPosition(), b.getHorizontalTextPosition(), viewRect, iconRect, textRect, b.getText() == null ? 0 : b.getIconTextGap()); // fill background if(c.isOpaque()) { g.setColor(b.getBackground()); g.fillRect(0,0, size.width, size.height); } // Paint the radio button if(altIcon != null) { if(!model.isEnabled()) { if(model.isSelected()) { altIcon = b.getDisabledSelectedIcon(); } else { altIcon = b.getDisabledIcon(); } } else if(model.isPressed() && model.isArmed()) { altIcon = b.getPressedIcon(); if(altIcon == null) { // Use selected icon altIcon = b.getSelectedIcon(); } } else if(model.isSelected()) { if(b.isRolloverEnabled() && model.isRollover()) { altIcon = (Icon) b.getRolloverSelectedIcon(); if (altIcon == null) { altIcon = (Icon) b.getSelectedIcon(); } } else { altIcon = (Icon) b.getSelectedIcon(); } } else if(b.isRolloverEnabled() && model.isRollover()) { altIcon = (Icon) b.getRolloverIcon(); } if(altIcon == null) { altIcon = b.getIcon(); } altIcon.paintIcon(c, g, iconRect.x, iconRect.y); } else { getDefaultIcon().paintIcon(c, g, iconRect.x, iconRect.y); } // Draw the Text if(text != null) { View v = (View) c.getClientProperty(BasicHTML.propertyKey); if (v != null) { v.paint(g, textRect); } else { paintText(g, b, textRect, text); } if(b.hasFocus() && b.isFocusPainted() && textRect.width > 0 && textRect.height > 0 ) { paintFocus(g, textRect, size); } } } protected void paintFocus(Graphics g, Rectangle textRect, Dimension size){ } /* These Insets/Rectangles are allocated once for all * RadioButtonUI.getPreferredSize() calls. Re-using rectangles * rather than allocating them in each call substantially * reduced the time it took getPreferredSize() to run. Obviously, * this method can't be re-entered. */ private static Rectangle prefViewRect = new Rectangle(); private static Rectangle prefIconRect = new Rectangle(); private static Rectangle prefTextRect = new Rectangle(); private static Insets prefInsets = new Insets(0, 0, 0, 0); /** {@collect.stats} * The preferred size of the radio button */ public Dimension getPreferredSize(JComponent c) { if(c.getComponentCount() > 0) { return null; } AbstractButton b = (AbstractButton) c; String text = b.getText(); Icon buttonIcon = (Icon) b.getIcon(); if(buttonIcon == null) { buttonIcon = getDefaultIcon(); } Font font = b.getFont(); FontMetrics fm = b.getFontMetrics(font); prefViewRect.x = prefViewRect.y = 0; prefViewRect.width = Short.MAX_VALUE; prefViewRect.height = Short.MAX_VALUE; prefIconRect.x = prefIconRect.y = prefIconRect.width = prefIconRect.height = 0; prefTextRect.x = prefTextRect.y = prefTextRect.width = prefTextRect.height = 0; SwingUtilities.layoutCompoundLabel( c, fm, text, buttonIcon, b.getVerticalAlignment(), b.getHorizontalAlignment(), b.getVerticalTextPosition(), b.getHorizontalTextPosition(), prefViewRect, prefIconRect, prefTextRect, text == null ? 0 : b.getIconTextGap()); // find the union of the icon and text rects (from Rectangle.java) int x1 = Math.min(prefIconRect.x, prefTextRect.x); int x2 = Math.max(prefIconRect.x + prefIconRect.width, prefTextRect.x + prefTextRect.width); int y1 = Math.min(prefIconRect.y, prefTextRect.y); int y2 = Math.max(prefIconRect.y + prefIconRect.height, prefTextRect.y + prefTextRect.height); int width = x2 - x1; int height = y2 - y1; prefInsets = b.getInsets(prefInsets); width += prefInsets.left + prefInsets.right; height += prefInsets.top + prefInsets.bottom; return new Dimension(width, height); } }
Java
/* * Copyright (c) 1998, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.awt.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.plaf.*; import java.awt.*; import java.awt.event.*; /** {@collect.stats} * BasicViewport implementation * * @author Rich Schiavi */ public class BasicViewportUI extends ViewportUI { // Shared UI object private static ViewportUI viewportUI; public static ComponentUI createUI(JComponent c) { if(viewportUI == null) { viewportUI = new BasicViewportUI(); } return viewportUI; } public void installUI(JComponent c) { super.installUI(c); installDefaults(c); } public void uninstallUI(JComponent c) { super.uninstallUI(c); } protected void installDefaults(JComponent c) { LookAndFeel.installColorsAndFont(c, "Viewport.background", "Viewport.foreground", "Viewport.font"); LookAndFeel.installProperty(c, "opaque", Boolean.TRUE); } protected void uninstallDefaults(JComponent c) { } }
Java
/* * Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import javax.swing.*; import javax.swing.colorchooser.*; import javax.swing.event.*; import javax.swing.border.*; import javax.swing.plaf.*; import java.util.*; import java.awt.*; import java.awt.image.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.Serializable; import sun.swing.DefaultLookup; import sun.swing.UIAction; /** {@collect.stats} * Provides the basic look and feel for a JColorChooser. * <p> * @author Tom Santos * @author Steve Wilson */ public class BasicColorChooserUI extends ColorChooserUI { /** {@collect.stats} * JColorChooser this BasicColorChooserUI is installed on. * * @since 1.5 */ protected JColorChooser chooser; JTabbedPane tabbedPane; JPanel singlePanel; JPanel previewPanelHolder; JComponent previewPanel; boolean isMultiPanel = false; private static TransferHandler defaultTransferHandler = new ColorTransferHandler(); protected AbstractColorChooserPanel[] defaultChoosers; protected ChangeListener previewListener; protected PropertyChangeListener propertyChangeListener; private Handler handler; public static ComponentUI createUI(JComponent c) { return new BasicColorChooserUI(); } protected AbstractColorChooserPanel[] createDefaultChoosers() { AbstractColorChooserPanel[] panels = ColorChooserComponentFactory.getDefaultChooserPanels(); return panels; } protected void uninstallDefaultChoosers() { AbstractColorChooserPanel[] choosers = chooser.getChooserPanels(); for( int i = 0 ; i < choosers.length; i++) { chooser.removeChooserPanel( choosers[i] ); } } public void installUI( JComponent c ) { chooser = (JColorChooser)c; super.installUI( c ); installDefaults(); installListeners(); tabbedPane = new JTabbedPane(); tabbedPane.setName("ColorChooser.tabPane"); tabbedPane.setInheritsPopupMenu(true); singlePanel = new JPanel(new CenterLayout()); singlePanel.setName("ColorChooser.panel"); singlePanel.setInheritsPopupMenu(true); chooser.setLayout( new BorderLayout() ); defaultChoosers = createDefaultChoosers(); chooser.setChooserPanels(defaultChoosers); previewPanelHolder = new JPanel(new CenterLayout()); previewPanelHolder.setName("ColorChooser.previewPanelHolder"); if (DefaultLookup.getBoolean(chooser, this, "ColorChooser.showPreviewPanelText", true)) { String previewString = UIManager.getString( "ColorChooser.previewText", chooser.getLocale()); previewPanelHolder.setBorder(new TitledBorder(previewString)); } previewPanelHolder.setInheritsPopupMenu(true); chooser.add(previewPanelHolder, BorderLayout.SOUTH); installPreviewPanel(); chooser.applyComponentOrientation(c.getComponentOrientation()); } public void uninstallUI( JComponent c ) { chooser.remove(tabbedPane); chooser.remove(singlePanel); chooser.remove(previewPanelHolder); uninstallDefaultChoosers(); uninstallListeners(); uninstallDefaults(); previewPanelHolder.remove(previewPanel); if (previewPanel instanceof UIResource) { chooser.setPreviewPanel(null); } previewPanelHolder = null; previewPanel = null; defaultChoosers = null; chooser = null; tabbedPane = null; handler = null; } protected void installPreviewPanel() { if (previewPanel != null) { previewPanelHolder.remove(previewPanel); previewPanel.removeMouseListener(getHandler()); } previewPanel = chooser.getPreviewPanel(); Dimension layoutSize = new Dimension(); // fix for bug 4759306 if (previewPanel != null) { layoutSize = new BorderLayout().minimumLayoutSize(previewPanel); if ((previewPanelHolder != null) && (chooser != null) && (layoutSize.getWidth() + layoutSize.getHeight() == 0)) { chooser.remove(previewPanelHolder); return; } } if (previewPanel == null || previewPanel instanceof UIResource) { previewPanel = ColorChooserComponentFactory.getPreviewPanel(); // get from table? chooser.setPreviewPanel(previewPanel); } previewPanel.setForeground(chooser.getColor()); previewPanelHolder.add(previewPanel); previewPanel.addMouseListener(getHandler()); previewPanel.setInheritsPopupMenu(true); } protected void installDefaults() { LookAndFeel.installColorsAndFont(chooser, "ColorChooser.background", "ColorChooser.foreground", "ColorChooser.font"); LookAndFeel.installProperty(chooser, "opaque", Boolean.TRUE); TransferHandler th = chooser.getTransferHandler(); if (th == null || th instanceof UIResource) { chooser.setTransferHandler(defaultTransferHandler); } } protected void uninstallDefaults() { if (chooser.getTransferHandler() instanceof UIResource) { chooser.setTransferHandler(null); } } protected void installListeners() { propertyChangeListener = createPropertyChangeListener(); chooser.addPropertyChangeListener( propertyChangeListener ); previewListener = getHandler(); chooser.getSelectionModel().addChangeListener(previewListener); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } protected PropertyChangeListener createPropertyChangeListener() { return getHandler(); } protected void uninstallListeners() { chooser.removePropertyChangeListener( propertyChangeListener ); chooser.getSelectionModel().removeChangeListener(previewListener); previewPanel.removeMouseListener(getHandler()); } private class Handler implements ChangeListener, MouseListener, PropertyChangeListener { // // ChangeListener // public void stateChanged(ChangeEvent evt) { ColorSelectionModel model = (ColorSelectionModel)evt.getSource(); if (previewPanel != null) { previewPanel.setForeground(model.getSelectedColor()); previewPanel.repaint(); } } // // MouseListener public void mousePressed(MouseEvent evt) { if (chooser.getDragEnabled()) { TransferHandler th = chooser.getTransferHandler(); th.exportAsDrag(chooser, evt, TransferHandler.COPY); } } public void mouseReleased(MouseEvent evt) {} public void mouseClicked(MouseEvent evt) {} public void mouseEntered(MouseEvent evt) {} public void mouseExited(MouseEvent evt) {} // // PropertyChangeListener // public void propertyChange(PropertyChangeEvent evt) { String prop = evt.getPropertyName(); if (prop == JColorChooser.CHOOSER_PANELS_PROPERTY) { AbstractColorChooserPanel[] oldPanels = (AbstractColorChooserPanel[])evt.getOldValue(); AbstractColorChooserPanel[] newPanels = (AbstractColorChooserPanel[])evt.getNewValue(); for (int i = 0; i < oldPanels.length; i++) { // remove old panels Container wrapper = oldPanels[i].getParent(); if (wrapper != null) { Container parent = wrapper.getParent(); if (parent != null) parent.remove(wrapper); // remove from hierarchy oldPanels[i].uninstallChooserPanel(chooser); // uninstall } } int numNewPanels = newPanels.length; if (numNewPanels == 0) { // removed all panels and added none chooser.remove(tabbedPane); return; } else if (numNewPanels == 1) { // one panel case chooser.remove(tabbedPane); JPanel centerWrapper = new JPanel( new CenterLayout() ); centerWrapper.setInheritsPopupMenu(true); centerWrapper.add(newPanels[0]); singlePanel.add(centerWrapper, BorderLayout.CENTER); chooser.add(singlePanel); } else { // multi-panel case if ( oldPanels.length < 2 ) {// moving from single to multiple chooser.remove(singlePanel); chooser.add(tabbedPane, BorderLayout.CENTER); } for (int i = 0; i < newPanels.length; i++) { JPanel centerWrapper = new JPanel( new CenterLayout() ); centerWrapper.setInheritsPopupMenu(true); String name = newPanels[i].getDisplayName(); int mnemonic = newPanels[i].getMnemonic(); centerWrapper.add(newPanels[i]); tabbedPane.addTab(name, centerWrapper); if (mnemonic > 0) { tabbedPane.setMnemonicAt(i, mnemonic); tabbedPane.setDisplayedMnemonicIndexAt( i, newPanels[i].getDisplayedMnemonicIndex()); } } } chooser.applyComponentOrientation(chooser.getComponentOrientation()); for (int i = 0; i < newPanels.length; i++) { newPanels[i].installChooserPanel(chooser); } } if (prop == JColorChooser.PREVIEW_PANEL_PROPERTY) { if (evt.getNewValue() != previewPanel) { installPreviewPanel(); } } if (prop == "componentOrientation") { ComponentOrientation o = (ComponentOrientation)evt.getNewValue(); JColorChooser cc = (JColorChooser)evt.getSource(); if (o != (ComponentOrientation)evt.getOldValue()) { cc.applyComponentOrientation(o); cc.updateUI(); } } } } /** {@collect.stats} * This inner class is marked &quot;public&quot; due to a compiler bug. * This class should be treated as a &quot;protected&quot; inner class. * Instantiate it only within subclasses of <Foo>. */ public class PropertyHandler implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent e) { getHandler().propertyChange(e); } } static class ColorTransferHandler extends TransferHandler implements UIResource { ColorTransferHandler() { super("color"); } } }
Java
/* * Copyright (c) 2000, 2002, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import java.io.*; import java.awt.datatransfer.*; import javax.swing.plaf.UIResource; /** {@collect.stats} * A transferable implementation for the default data transfer of some Swing * components. * * @author Timothy Prinzing */ class BasicTransferable implements Transferable, UIResource { protected String plainData; protected String htmlData; private static DataFlavor[] htmlFlavors; private static DataFlavor[] stringFlavors; private static DataFlavor[] plainFlavors; static { try { htmlFlavors = new DataFlavor[3]; htmlFlavors[0] = new DataFlavor("text/html;class=java.lang.String"); htmlFlavors[1] = new DataFlavor("text/html;class=java.io.Reader"); htmlFlavors[2] = new DataFlavor("text/html;charset=unicode;class=java.io.InputStream"); plainFlavors = new DataFlavor[3]; plainFlavors[0] = new DataFlavor("text/plain;class=java.lang.String"); plainFlavors[1] = new DataFlavor("text/plain;class=java.io.Reader"); plainFlavors[2] = new DataFlavor("text/plain;charset=unicode;class=java.io.InputStream"); stringFlavors = new DataFlavor[2]; stringFlavors[0] = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType+";class=java.lang.String"); stringFlavors[1] = DataFlavor.stringFlavor; } catch (ClassNotFoundException cle) { System.err.println("error initializing javax.swing.plaf.basic.BasicTranserable"); } } public BasicTransferable(String plainData, String htmlData) { this.plainData = plainData; this.htmlData = htmlData; } /** {@collect.stats} * Returns an array of DataFlavor objects indicating the flavors the data * can be provided in. The array should be ordered according to preference * for providing the data (from most richly descriptive to least descriptive). * @return an array of data flavors in which this data can be transferred */ public DataFlavor[] getTransferDataFlavors() { DataFlavor[] richerFlavors = getRicherFlavors(); int nRicher = (richerFlavors != null) ? richerFlavors.length : 0; int nHTML = (isHTMLSupported()) ? htmlFlavors.length : 0; int nPlain = (isPlainSupported()) ? plainFlavors.length: 0; int nString = (isPlainSupported()) ? stringFlavors.length : 0; int nFlavors = nRicher + nHTML + nPlain + nString; DataFlavor[] flavors = new DataFlavor[nFlavors]; // fill in the array int nDone = 0; if (nRicher > 0) { System.arraycopy(richerFlavors, 0, flavors, nDone, nRicher); nDone += nRicher; } if (nHTML > 0) { System.arraycopy(htmlFlavors, 0, flavors, nDone, nHTML); nDone += nHTML; } if (nPlain > 0) { System.arraycopy(plainFlavors, 0, flavors, nDone, nPlain); nDone += nPlain; } if (nString > 0) { System.arraycopy(stringFlavors, 0, flavors, nDone, nString); nDone += nString; } return flavors; } /** {@collect.stats} * Returns whether or not the specified data flavor is supported for * this object. * @param flavor the requested flavor for the data * @return boolean indicating whether or not the data flavor is supported */ public boolean isDataFlavorSupported(DataFlavor flavor) { DataFlavor[] flavors = getTransferDataFlavors(); for (int i = 0; i < flavors.length; i++) { if (flavors[i].equals(flavor)) { return true; } } return false; } /** {@collect.stats} * Returns an object which represents the data to be transferred. The class * of the object returned is defined by the representation class of the flavor. * * @param flavor the requested flavor for the data * @see DataFlavor#getRepresentationClass * @exception IOException if the data is no longer available * in the requested flavor. * @exception UnsupportedFlavorException if the requested data flavor is * not supported. */ public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { DataFlavor[] richerFlavors = getRicherFlavors(); if (isRicherFlavor(flavor)) { return getRicherData(flavor); } else if (isHTMLFlavor(flavor)) { String data = getHTMLData(); data = (data == null) ? "" : data; if (String.class.equals(flavor.getRepresentationClass())) { return data; } else if (Reader.class.equals(flavor.getRepresentationClass())) { return new StringReader(data); } else if (InputStream.class.equals(flavor.getRepresentationClass())) { return new StringBufferInputStream(data); } // fall through to unsupported } else if (isPlainFlavor(flavor)) { String data = getPlainData(); data = (data == null) ? "" : data; if (String.class.equals(flavor.getRepresentationClass())) { return data; } else if (Reader.class.equals(flavor.getRepresentationClass())) { return new StringReader(data); } else if (InputStream.class.equals(flavor.getRepresentationClass())) { return new StringBufferInputStream(data); } // fall through to unsupported } else if (isStringFlavor(flavor)) { String data = getPlainData(); data = (data == null) ? "" : data; return data; } throw new UnsupportedFlavorException(flavor); } // --- richer subclass flavors ---------------------------------------------- protected boolean isRicherFlavor(DataFlavor flavor) { DataFlavor[] richerFlavors = getRicherFlavors(); int nFlavors = (richerFlavors != null) ? richerFlavors.length : 0; for (int i = 0; i < nFlavors; i++) { if (richerFlavors[i].equals(flavor)) { return true; } } return false; } /** {@collect.stats} * Some subclasses will have flavors that are more descriptive than HTML * or plain text. If this method returns a non-null value, it will be * placed at the start of the array of supported flavors. */ protected DataFlavor[] getRicherFlavors() { return null; } protected Object getRicherData(DataFlavor flavor) throws UnsupportedFlavorException { return null; } // --- html flavors ---------------------------------------------------------- /** {@collect.stats} * Returns whether or not the specified data flavor is an HTML flavor that * is supported. * @param flavor the requested flavor for the data * @return boolean indicating whether or not the data flavor is supported */ protected boolean isHTMLFlavor(DataFlavor flavor) { DataFlavor[] flavors = htmlFlavors; for (int i = 0; i < flavors.length; i++) { if (flavors[i].equals(flavor)) { return true; } } return false; } /** {@collect.stats} * Should the HTML flavors be offered? If so, the method * getHTMLData should be implemented to provide something reasonable. */ protected boolean isHTMLSupported() { return htmlData != null; } /** {@collect.stats} * Fetch the data in a text/html format */ protected String getHTMLData() { return htmlData; } // --- plain text flavors ---------------------------------------------------- /** {@collect.stats} * Returns whether or not the specified data flavor is an plain flavor that * is supported. * @param flavor the requested flavor for the data * @return boolean indicating whether or not the data flavor is supported */ protected boolean isPlainFlavor(DataFlavor flavor) { DataFlavor[] flavors = plainFlavors; for (int i = 0; i < flavors.length; i++) { if (flavors[i].equals(flavor)) { return true; } } return false; } /** {@collect.stats} * Should the plain text flavors be offered? If so, the method * getPlainData should be implemented to provide something reasonable. */ protected boolean isPlainSupported() { return plainData != null; } /** {@collect.stats} * Fetch the data in a text/plain format. */ protected String getPlainData() { return plainData; } // --- string flavorss -------------------------------------------------------- /** {@collect.stats} * Returns whether or not the specified data flavor is a String flavor that * is supported. * @param flavor the requested flavor for the data * @return boolean indicating whether or not the data flavor is supported */ protected boolean isStringFlavor(DataFlavor flavor) { DataFlavor[] flavors = stringFlavors; for (int i = 0; i < flavors.length; i++) { if (flavors[i].equals(flavor)) { return true; } } return false; } }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.basic; import sun.swing.DefaultLookup; import sun.swing.UIAction; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import javax.swing.plaf.*; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.awt.Component; import java.awt.Container; import java.awt.LayoutManager; import java.awt.Rectangle; import java.awt.Dimension; import java.awt.Point; import java.awt.Insets; import java.awt.Graphics; import java.awt.event.*; import java.io.Serializable; import java.awt.Toolkit; import java.awt.ComponentOrientation; /** {@collect.stats} * A default L&F implementation of ScrollPaneUI. * * @author Hans Muller */ public class BasicScrollPaneUI extends ScrollPaneUI implements ScrollPaneConstants { protected JScrollPane scrollpane; protected ChangeListener vsbChangeListener; protected ChangeListener hsbChangeListener; protected ChangeListener viewportChangeListener; protected PropertyChangeListener spPropertyChangeListener; private MouseWheelListener mouseScrollListener; /** {@collect.stats} * PropertyChangeListener installed on the vertical scrollbar. */ private PropertyChangeListener vsbPropertyChangeListener; /** {@collect.stats} * PropertyChangeListener installed on the horizontal scrollbar. */ private PropertyChangeListener hsbPropertyChangeListener; private Handler handler; /** {@collect.stats} * State flag that shows whether setValue() was called from a user program * before the value of "extent" was set in right-to-left component * orientation. */ private boolean setValueCalled = false; public static ComponentUI createUI(JComponent x) { return new BasicScrollPaneUI(); } static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.SCROLL_UP)); map.put(new Actions(Actions.SCROLL_DOWN)); map.put(new Actions(Actions.SCROLL_HOME)); map.put(new Actions(Actions.SCROLL_END)); map.put(new Actions(Actions.UNIT_SCROLL_UP)); map.put(new Actions(Actions.UNIT_SCROLL_DOWN)); map.put(new Actions(Actions.SCROLL_LEFT)); map.put(new Actions(Actions.SCROLL_RIGHT)); map.put(new Actions(Actions.UNIT_SCROLL_RIGHT)); map.put(new Actions(Actions.UNIT_SCROLL_LEFT)); } public void paint(Graphics g, JComponent c) { Border vpBorder = scrollpane.getViewportBorder(); if (vpBorder != null) { Rectangle r = scrollpane.getViewportBorderBounds(); vpBorder.paintBorder(scrollpane, g, r.x, r.y, r.width, r.height); } } /** {@collect.stats} * @return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE) */ public Dimension getMaximumSize(JComponent c) { return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE); } protected void installDefaults(JScrollPane scrollpane) { LookAndFeel.installBorder(scrollpane, "ScrollPane.border"); LookAndFeel.installColorsAndFont(scrollpane, "ScrollPane.background", "ScrollPane.foreground", "ScrollPane.font"); Border vpBorder = scrollpane.getViewportBorder(); if ((vpBorder == null) ||( vpBorder instanceof UIResource)) { vpBorder = UIManager.getBorder("ScrollPane.viewportBorder"); scrollpane.setViewportBorder(vpBorder); } LookAndFeel.installProperty(scrollpane, "opaque", Boolean.TRUE); } protected void installListeners(JScrollPane c) { vsbChangeListener = createVSBChangeListener(); vsbPropertyChangeListener = createVSBPropertyChangeListener(); hsbChangeListener = createHSBChangeListener(); hsbPropertyChangeListener = createHSBPropertyChangeListener(); viewportChangeListener = createViewportChangeListener(); spPropertyChangeListener = createPropertyChangeListener(); JViewport viewport = scrollpane.getViewport(); JScrollBar vsb = scrollpane.getVerticalScrollBar(); JScrollBar hsb = scrollpane.getHorizontalScrollBar(); if (viewport != null) { viewport.addChangeListener(viewportChangeListener); } if (vsb != null) { vsb.getModel().addChangeListener(vsbChangeListener); vsb.addPropertyChangeListener(vsbPropertyChangeListener); } if (hsb != null) { hsb.getModel().addChangeListener(hsbChangeListener); hsb.addPropertyChangeListener(hsbPropertyChangeListener); } scrollpane.addPropertyChangeListener(spPropertyChangeListener); mouseScrollListener = createMouseWheelListener(); scrollpane.addMouseWheelListener(mouseScrollListener); } protected void installKeyboardActions(JScrollPane c) { InputMap inputMap = getInputMap(JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); SwingUtilities.replaceUIInputMap(c, JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, inputMap); LazyActionMap.installLazyActionMap(c, BasicScrollPaneUI.class, "ScrollPane.actionMap"); } InputMap getInputMap(int condition) { if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) { InputMap keyMap = (InputMap)DefaultLookup.get(scrollpane, this, "ScrollPane.ancestorInputMap"); InputMap rtlKeyMap; if (scrollpane.getComponentOrientation().isLeftToRight() || ((rtlKeyMap = (InputMap)DefaultLookup.get(scrollpane, this, "ScrollPane.ancestorInputMap.RightToLeft")) == null)) { return keyMap; } else { rtlKeyMap.setParent(keyMap); return rtlKeyMap; } } return null; } public void installUI(JComponent x) { scrollpane = (JScrollPane)x; installDefaults(scrollpane); installListeners(scrollpane); installKeyboardActions(scrollpane); } protected void uninstallDefaults(JScrollPane c) { LookAndFeel.uninstallBorder(scrollpane); if (scrollpane.getViewportBorder() instanceof UIResource) { scrollpane.setViewportBorder(null); } } protected void uninstallListeners(JComponent c) { JViewport viewport = scrollpane.getViewport(); JScrollBar vsb = scrollpane.getVerticalScrollBar(); JScrollBar hsb = scrollpane.getHorizontalScrollBar(); if (viewport != null) { viewport.removeChangeListener(viewportChangeListener); } if (vsb != null) { vsb.getModel().removeChangeListener(vsbChangeListener); vsb.removePropertyChangeListener(vsbPropertyChangeListener); } if (hsb != null) { hsb.getModel().removeChangeListener(hsbChangeListener); hsb.removePropertyChangeListener(hsbPropertyChangeListener); } scrollpane.removePropertyChangeListener(spPropertyChangeListener); if (mouseScrollListener != null) { scrollpane.removeMouseWheelListener(mouseScrollListener); } vsbChangeListener = null; hsbChangeListener = null; viewportChangeListener = null; spPropertyChangeListener = null; mouseScrollListener = null; handler = null; } protected void uninstallKeyboardActions(JScrollPane c) { SwingUtilities.replaceUIActionMap(c, null); SwingUtilities.replaceUIInputMap(c, JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null); } public void uninstallUI(JComponent c) { uninstallDefaults(scrollpane); uninstallListeners(scrollpane); uninstallKeyboardActions(scrollpane); scrollpane = null; } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } protected void syncScrollPaneWithViewport() { JViewport viewport = scrollpane.getViewport(); JScrollBar vsb = scrollpane.getVerticalScrollBar(); JScrollBar hsb = scrollpane.getHorizontalScrollBar(); JViewport rowHead = scrollpane.getRowHeader(); JViewport colHead = scrollpane.getColumnHeader(); boolean ltr = scrollpane.getComponentOrientation().isLeftToRight(); if (viewport != null) { Dimension extentSize = viewport.getExtentSize(); Dimension viewSize = viewport.getViewSize(); Point viewPosition = viewport.getViewPosition(); if (vsb != null) { int extent = extentSize.height; int max = viewSize.height; int value = Math.max(0, Math.min(viewPosition.y, max - extent)); vsb.setValues(value, extent, 0, max); } if (hsb != null) { int extent = extentSize.width; int max = viewSize.width; int value; if (ltr) { value = Math.max(0, Math.min(viewPosition.x, max - extent)); } else { int currentValue = hsb.getValue(); /* Use a particular formula to calculate "value" * until effective x coordinate is calculated. */ if (setValueCalled && ((max - currentValue) == viewPosition.x)) { value = Math.max(0, Math.min(max - extent, currentValue)); /* After "extent" is set, turn setValueCalled flag off. */ if (extent != 0) { setValueCalled = false; } } else { if (extent > max) { viewPosition.x = max - extent; viewport.setViewPosition(viewPosition); value = 0; } else { /* The following line can't handle a small value of * viewPosition.x like Integer.MIN_VALUE correctly * because (max - extent - viewPositoiin.x) causes * an overflow. As a result, value becomes zero. * (e.g. setViewPosition(Integer.MAX_VALUE, ...) * in a user program causes a overflow. * Its expected value is (max - extent).) * However, this seems a trivial bug and adding a * fix makes this often-called method slow, so I'll * leave it until someone claims. */ value = Math.max(0, Math.min(max - extent, max - extent - viewPosition.x)); } } } hsb.setValues(value, extent, 0, max); } if (rowHead != null) { Point p = rowHead.getViewPosition(); p.y = viewport.getViewPosition().y; p.x = 0; rowHead.setViewPosition(p); } if (colHead != null) { Point p = colHead.getViewPosition(); if (ltr) { p.x = viewport.getViewPosition().x; } else { p.x = Math.max(0, viewport.getViewPosition().x); } p.y = 0; colHead.setViewPosition(p); } } } /** {@collect.stats} * Returns the baseline. * * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public int getBaseline(JComponent c, int width, int height) { JViewport viewport = scrollpane.getViewport(); Insets spInsets = scrollpane.getInsets(); int y = spInsets.top; height = height - spInsets.top - spInsets.bottom; width = width - spInsets.left - spInsets.right; JViewport columnHeader = scrollpane.getColumnHeader(); if (columnHeader != null && columnHeader.isVisible()) { Component header = columnHeader.getView(); if (header != null && header.isVisible()) { // Header is always given it's preferred size. Dimension headerPref = header.getPreferredSize(); int baseline = header.getBaseline(headerPref.width, headerPref.height); if (baseline >= 0) { return y + baseline; } } Dimension columnPref = columnHeader.getPreferredSize(); height -= columnPref.height; y += columnPref.height; } Component view = (viewport == null) ? null : viewport.getView(); if (view != null && view.isVisible() && view.getBaselineResizeBehavior() == Component.BaselineResizeBehavior.CONSTANT_ASCENT) { Border viewportBorder = scrollpane.getViewportBorder(); if (viewportBorder != null) { Insets vpbInsets = viewportBorder.getBorderInsets(scrollpane); y += vpbInsets.top; height = height - vpbInsets.top - vpbInsets.bottom; width = width - vpbInsets.left - vpbInsets.right; } if (view.getWidth() > 0 && view.getHeight() > 0) { Dimension min = view.getMinimumSize(); width = Math.max(min.width, view.getWidth()); height = Math.max(min.height, view.getHeight()); } if (width > 0 && height > 0) { int baseline = view.getBaseline(width, height); if (baseline > 0) { return y + baseline; } } } return -1; } /** {@collect.stats} * Returns an enum indicating how the baseline of the component * changes as the size changes. * * @throws NullPointerException {@inheritDoc} * @see javax.swing.JComponent#getBaseline(int, int) * @since 1.6 */ public Component.BaselineResizeBehavior getBaselineResizeBehavior( JComponent c) { super.getBaselineResizeBehavior(c); // Baseline is either from the header, in which case it's always // the same size and therefor can be created as CONSTANT_ASCENT. // If the header doesn't have a baseline than the baseline will only // be valid if it's BaselineResizeBehavior is // CONSTANT_ASCENT, so, return CONSTANT_ASCENT. return Component.BaselineResizeBehavior.CONSTANT_ASCENT; } /** {@collect.stats} * Listener for viewport events. */ public class ViewportChangeHandler implements ChangeListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void stateChanged(ChangeEvent e) { getHandler().stateChanged(e); } } protected ChangeListener createViewportChangeListener() { return getHandler(); } /** {@collect.stats} * Horizontal scrollbar listener. */ public class HSBChangeListener implements ChangeListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void stateChanged(ChangeEvent e) { getHandler().stateChanged(e); } } /** {@collect.stats} * Returns a <code>PropertyChangeListener</code> that will be installed * on the horizontal <code>JScrollBar</code>. */ private PropertyChangeListener createHSBPropertyChangeListener() { return getHandler(); } protected ChangeListener createHSBChangeListener() { return getHandler(); } /** {@collect.stats} * Vertical scrollbar listener. */ public class VSBChangeListener implements ChangeListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void stateChanged(ChangeEvent e) { getHandler().stateChanged(e); } } /** {@collect.stats} * Returns a <code>PropertyChangeListener</code> that will be installed * on the vertical <code>JScrollBar</code>. */ private PropertyChangeListener createVSBPropertyChangeListener() { return getHandler(); } protected ChangeListener createVSBChangeListener() { return getHandler(); } /** {@collect.stats} * MouseWheelHandler is an inner class which implements the * MouseWheelListener interface. MouseWheelHandler responds to * MouseWheelEvents by scrolling the JScrollPane appropriately. * If the scroll pane's * <code>isWheelScrollingEnabled</code> * method returns false, no scrolling occurs. * * @see javax.swing.JScrollPane#isWheelScrollingEnabled * @see #createMouseWheelListener * @see java.awt.event.MouseWheelListener * @see java.awt.event.MouseWheelEvent * @since 1.4 */ protected class MouseWheelHandler implements MouseWheelListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. /** {@collect.stats} * Called when the mouse wheel is rotated while over a * JScrollPane. * * @param e MouseWheelEvent to be handled * @since 1.4 */ public void mouseWheelMoved(MouseWheelEvent e) { getHandler().mouseWheelMoved(e); } } /** {@collect.stats} * Creates an instance of MouseWheelListener, which is added to the * JScrollPane by installUI(). The returned MouseWheelListener is used * to handle mouse wheel-driven scrolling. * * @return MouseWheelListener which implements wheel-driven scrolling * @see #installUI * @see MouseWheelHandler * @since 1.4 */ protected MouseWheelListener createMouseWheelListener() { return getHandler(); } protected void updateScrollBarDisplayPolicy(PropertyChangeEvent e) { scrollpane.revalidate(); scrollpane.repaint(); } protected void updateViewport(PropertyChangeEvent e) { JViewport oldViewport = (JViewport)(e.getOldValue()); JViewport newViewport = (JViewport)(e.getNewValue()); if (oldViewport != null) { oldViewport.removeChangeListener(viewportChangeListener); } if (newViewport != null) { Point p = newViewport.getViewPosition(); if (scrollpane.getComponentOrientation().isLeftToRight()) { p.x = Math.max(p.x, 0); } else { int max = newViewport.getViewSize().width; int extent = newViewport.getExtentSize().width; if (extent > max) { p.x = max - extent; } else { p.x = Math.max(0, Math.min(max - extent, p.x)); } } p.y = Math.max(p.y, 0); newViewport.setViewPosition(p); newViewport.addChangeListener(viewportChangeListener); } } protected void updateRowHeader(PropertyChangeEvent e) { JViewport newRowHead = (JViewport)(e.getNewValue()); if (newRowHead != null) { JViewport viewport = scrollpane.getViewport(); Point p = newRowHead.getViewPosition(); p.y = (viewport != null) ? viewport.getViewPosition().y : 0; newRowHead.setViewPosition(p); } } protected void updateColumnHeader(PropertyChangeEvent e) { JViewport newColHead = (JViewport)(e.getNewValue()); if (newColHead != null) { JViewport viewport = scrollpane.getViewport(); Point p = newColHead.getViewPosition(); if (viewport == null) { p.x = 0; } else { if (scrollpane.getComponentOrientation().isLeftToRight()) { p.x = viewport.getViewPosition().x; } else { p.x = Math.max(0, viewport.getViewPosition().x); } } newColHead.setViewPosition(p); scrollpane.add(newColHead, COLUMN_HEADER); } } private void updateHorizontalScrollBar(PropertyChangeEvent pce) { updateScrollBar(pce, hsbChangeListener, hsbPropertyChangeListener); } private void updateVerticalScrollBar(PropertyChangeEvent pce) { updateScrollBar(pce, vsbChangeListener, vsbPropertyChangeListener); } private void updateScrollBar(PropertyChangeEvent pce, ChangeListener cl, PropertyChangeListener pcl) { JScrollBar sb = (JScrollBar)pce.getOldValue(); if (sb != null) { if (cl != null) { sb.getModel().removeChangeListener(cl); } if (pcl != null) { sb.removePropertyChangeListener(pcl); } } sb = (JScrollBar)pce.getNewValue(); if (sb != null) { if (cl != null) { sb.getModel().addChangeListener(cl); } if (pcl != null) { sb.addPropertyChangeListener(pcl); } } } public class PropertyChangeHandler implements PropertyChangeListener { // NOTE: This class exists only for backward compatability. All // its functionality has been moved into Handler. If you need to add // new functionality add it to the Handler, but make sure this // class calls into the Handler. public void propertyChange(PropertyChangeEvent e) { getHandler().propertyChange(e); } } /** {@collect.stats} * Creates an instance of PropertyChangeListener that's added to * the JScrollPane by installUI(). Subclasses can override this method * to return a custom PropertyChangeListener, e.g. * <pre> * class MyScrollPaneUI extends BasicScrollPaneUI { * protected PropertyChangeListener <b>createPropertyChangeListener</b>() { * return new MyPropertyChangeListener(); * } * public class MyPropertyChangeListener extends PropertyChangeListener { * public void propertyChange(PropertyChangeEvent e) { * if (e.getPropertyName().equals("viewport")) { * // do some extra work when the viewport changes * } * super.propertyChange(e); * } * } * } * </pre> * * @see java.beans.PropertyChangeListener * @see #installUI */ protected PropertyChangeListener createPropertyChangeListener() { return getHandler(); } private static class Actions extends UIAction { private static final String SCROLL_UP = "scrollUp"; private static final String SCROLL_DOWN = "scrollDown"; private static final String SCROLL_HOME = "scrollHome"; private static final String SCROLL_END = "scrollEnd"; private static final String UNIT_SCROLL_UP = "unitScrollUp"; private static final String UNIT_SCROLL_DOWN = "unitScrollDown"; private static final String SCROLL_LEFT = "scrollLeft"; private static final String SCROLL_RIGHT = "scrollRight"; private static final String UNIT_SCROLL_LEFT = "unitScrollLeft"; private static final String UNIT_SCROLL_RIGHT = "unitScrollRight"; Actions(String key) { super(key); } public void actionPerformed(ActionEvent e) { JScrollPane scrollPane = (JScrollPane)e.getSource(); boolean ltr = scrollPane.getComponentOrientation().isLeftToRight(); String key = getName(); if (key == SCROLL_UP) { scroll(scrollPane, SwingConstants.VERTICAL, -1, true); } else if (key == SCROLL_DOWN) { scroll(scrollPane, SwingConstants.VERTICAL, 1, true); } else if (key == SCROLL_HOME) { scrollHome(scrollPane); } else if (key == SCROLL_END) { scrollEnd(scrollPane); } else if (key == UNIT_SCROLL_UP) { scroll(scrollPane, SwingConstants.VERTICAL, -1, false); } else if (key == UNIT_SCROLL_DOWN) { scroll(scrollPane, SwingConstants.VERTICAL, 1, false); } else if (key == SCROLL_LEFT) { scroll(scrollPane, SwingConstants.HORIZONTAL, ltr ? -1 : 1, true); } else if (key == SCROLL_RIGHT) { scroll(scrollPane, SwingConstants.HORIZONTAL, ltr ? 1 : -1, true); } else if (key == UNIT_SCROLL_LEFT) { scroll(scrollPane, SwingConstants.HORIZONTAL, ltr ? -1 : 1, false); } else if (key == UNIT_SCROLL_RIGHT) { scroll(scrollPane, SwingConstants.HORIZONTAL, ltr ? 1 : -1, false); } } private void scrollEnd(JScrollPane scrollpane) { JViewport vp = scrollpane.getViewport(); Component view; if (vp != null && (view = vp.getView()) != null) { Rectangle visRect = vp.getViewRect(); Rectangle bounds = view.getBounds(); if (scrollpane.getComponentOrientation().isLeftToRight()) { vp.setViewPosition(new Point(bounds.width - visRect.width, bounds.height - visRect.height)); } else { vp.setViewPosition(new Point(0, bounds.height - visRect.height)); } } } private void scrollHome(JScrollPane scrollpane) { JViewport vp = scrollpane.getViewport(); Component view; if (vp != null && (view = vp.getView()) != null) { if (scrollpane.getComponentOrientation().isLeftToRight()) { vp.setViewPosition(new Point(0, 0)); } else { Rectangle visRect = vp.getViewRect(); Rectangle bounds = view.getBounds(); vp.setViewPosition(new Point(bounds.width - visRect.width, 0)); } } } private void scroll(JScrollPane scrollpane, int orientation, int direction, boolean block) { JViewport vp = scrollpane.getViewport(); Component view; if (vp != null && (view = vp.getView()) != null) { Rectangle visRect = vp.getViewRect(); Dimension vSize = view.getSize(); int amount; if (view instanceof Scrollable) { if (block) { amount = ((Scrollable)view).getScrollableBlockIncrement (visRect, orientation, direction); } else { amount = ((Scrollable)view).getScrollableUnitIncrement (visRect, orientation, direction); } } else { if (block) { if (orientation == SwingConstants.VERTICAL) { amount = visRect.height; } else { amount = visRect.width; } } else { amount = 10; } } if (orientation == SwingConstants.VERTICAL) { visRect.y += (amount * direction); if ((visRect.y + visRect.height) > vSize.height) { visRect.y = Math.max(0, vSize.height - visRect.height); } else if (visRect.y < 0) { visRect.y = 0; } } else { if (scrollpane.getComponentOrientation().isLeftToRight()) { visRect.x += (amount * direction); if ((visRect.x + visRect.width) > vSize.width) { visRect.x = Math.max(0, vSize.width - visRect.width); } else if (visRect.x < 0) { visRect.x = 0; } } else { visRect.x -= (amount * direction); if (visRect.width > vSize.width) { visRect.x = vSize.width - visRect.width; } else { visRect.x = Math.max(0, Math.min(vSize.width - visRect.width, visRect.x)); } } } vp.setViewPosition(visRect.getLocation()); } } } class Handler implements ChangeListener, PropertyChangeListener, MouseWheelListener { // // MouseWheelListener // public void mouseWheelMoved(MouseWheelEvent e) { if (scrollpane.isWheelScrollingEnabled() && e.getWheelRotation() != 0) { JScrollBar toScroll = scrollpane.getVerticalScrollBar(); int direction = e.getWheelRotation() < 0 ? -1 : 1; int orientation = SwingConstants.VERTICAL; // find which scrollbar to scroll, or return if none if (toScroll == null || !toScroll.isVisible()) { toScroll = scrollpane.getHorizontalScrollBar(); if (toScroll == null || !toScroll.isVisible()) { return; } orientation = SwingConstants.HORIZONTAL; } if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) { JViewport vp = scrollpane.getViewport(); if (vp == null) { return; } Component comp = vp.getView(); int units = Math.abs(e.getUnitsToScroll()); // When the scrolling speed is set to maximum, it's possible // for a single wheel click to scroll by more units than // will fit in the visible area. This makes it // hard/impossible to get to certain parts of the scrolling // Component with the wheel. To make for more accurate // low-speed scrolling, we limit scrolling to the block // increment if the wheel was only rotated one click. boolean limitScroll = Math.abs(e.getWheelRotation()) == 1; // Check if we should use the visibleRect trick Object fastWheelScroll = toScroll.getClientProperty( "JScrollBar.fastWheelScrolling"); if (Boolean.TRUE == fastWheelScroll && comp instanceof Scrollable) { // 5078454: Under maximum acceleration, we may scroll // by many 100s of units in ~1 second. // // BasicScrollBarUI.scrollByUnits() can bog down the EDT // with repaints in this situation. However, the // Scrollable interface allows us to pass in an // arbitrary visibleRect. This allows us to accurately // calculate the total scroll amount, and then update // the GUI once. This technique provides much faster // accelerated wheel scrolling. Scrollable scrollComp = (Scrollable) comp; Rectangle viewRect = vp.getViewRect(); int startingX = viewRect.x; boolean leftToRight = comp.getComponentOrientation().isLeftToRight(); int scrollMin = toScroll.getMinimum(); int scrollMax = toScroll.getMaximum() - toScroll.getModel().getExtent(); if (limitScroll) { int blockIncr = scrollComp.getScrollableBlockIncrement(viewRect, orientation, direction); if (direction < 0) { scrollMin = Math.max(scrollMin, toScroll.getValue() - blockIncr); } else { scrollMax = Math.min(scrollMax, toScroll.getValue() + blockIncr); } } for (int i = 0; i < units; i++) { int unitIncr = scrollComp.getScrollableUnitIncrement(viewRect, orientation, direction); // Modify the visible rect for the next unit, and // check to see if we're at the end already. if (orientation == SwingConstants.VERTICAL) { if (direction < 0) { viewRect.y -= unitIncr; if (viewRect.y <= scrollMin) { viewRect.y = scrollMin; break; } } else { // (direction > 0 viewRect.y += unitIncr; if (viewRect.y >= scrollMax) { viewRect.y = scrollMax; break; } } } else { // Scroll left if ((leftToRight && direction < 0) || (!leftToRight && direction > 0)) { viewRect.x -= unitIncr; if (leftToRight) { if (viewRect.x < scrollMin) { viewRect.x = scrollMin; break; } } } // Scroll right else if ((leftToRight && direction > 0) || (!leftToRight && direction < 0)) { viewRect.x += unitIncr; if (leftToRight) { if (viewRect.x > scrollMax) { viewRect.x = scrollMax; break; } } } else { assert false : "Non-sensical ComponentOrientation / scroll direction"; } } } // Set the final view position on the ScrollBar if (orientation == SwingConstants.VERTICAL) { toScroll.setValue(viewRect.y); } else { if (leftToRight) { toScroll.setValue(viewRect.x); } else { // rightToLeft scrollbars are oriented with // minValue on the right and maxValue on the // left. int newPos = toScroll.getValue() - (viewRect.x - startingX); if (newPos < scrollMin) { newPos = scrollMin; } else if (newPos > scrollMax) { newPos = scrollMax; } toScroll.setValue(newPos); } } } else { // Viewport's view is not a Scrollable, or fast wheel // scrolling is not enabled. BasicScrollBarUI.scrollByUnits(toScroll, direction, units, limitScroll); } } else if (e.getScrollType() == MouseWheelEvent.WHEEL_BLOCK_SCROLL) { BasicScrollBarUI.scrollByBlock(toScroll, direction); } } } // // ChangeListener: This is added to the vieport, and hsb/vsb models. // public void stateChanged(ChangeEvent e) { JViewport viewport = scrollpane.getViewport(); if (viewport != null) { if (e.getSource() == viewport) { viewportStateChanged(e); } else { JScrollBar hsb = scrollpane.getHorizontalScrollBar(); if (hsb != null && e.getSource() == hsb.getModel()) { hsbStateChanged(viewport, e); } else { JScrollBar vsb = scrollpane.getVerticalScrollBar(); if (vsb != null && e.getSource() == vsb.getModel()) { vsbStateChanged(viewport, e); } } } } } private void vsbStateChanged(JViewport viewport, ChangeEvent e) { BoundedRangeModel model = (BoundedRangeModel)(e.getSource()); Point p = viewport.getViewPosition(); p.y = model.getValue(); viewport.setViewPosition(p); } private void hsbStateChanged(JViewport viewport, ChangeEvent e) { BoundedRangeModel model = (BoundedRangeModel)(e.getSource()); Point p = viewport.getViewPosition(); int value = model.getValue(); if (scrollpane.getComponentOrientation().isLeftToRight()) { p.x = value; } else { int max = viewport.getViewSize().width; int extent = viewport.getExtentSize().width; int oldX = p.x; /* Set new X coordinate based on "value". */ p.x = max - extent - value; /* If setValue() was called before "extent" was fixed, * turn setValueCalled flag on. */ if ((extent == 0) && (value != 0) && (oldX == max)) { setValueCalled = true; } else { /* When a pane without a horizontal scroll bar was * reduced and the bar appeared, the viewport should * show the right side of the view. */ if ((extent != 0) && (oldX < 0) && (p.x == 0)) { p.x += value; } } } viewport.setViewPosition(p); } private void viewportStateChanged(ChangeEvent e) { syncScrollPaneWithViewport(); } // // PropertyChangeListener: This is installed on both the JScrollPane // and the horizontal/vertical scrollbars. // // Listens for changes in the model property and reinstalls the // horizontal/vertical PropertyChangeListeners. public void propertyChange(PropertyChangeEvent e) { if (e.getSource() == scrollpane) { scrollPanePropertyChange(e); } else { sbPropertyChange(e); } } private void scrollPanePropertyChange(PropertyChangeEvent e) { String propertyName = e.getPropertyName(); if (propertyName == "verticalScrollBarDisplayPolicy") { updateScrollBarDisplayPolicy(e); } else if (propertyName == "horizontalScrollBarDisplayPolicy") { updateScrollBarDisplayPolicy(e); } else if (propertyName == "viewport") { updateViewport(e); } else if (propertyName == "rowHeader") { updateRowHeader(e); } else if (propertyName == "columnHeader") { updateColumnHeader(e); } else if (propertyName == "verticalScrollBar") { updateVerticalScrollBar(e); } else if (propertyName == "horizontalScrollBar") { updateHorizontalScrollBar(e); } else if (propertyName == "componentOrientation") { scrollpane.revalidate(); scrollpane.repaint(); } } // PropertyChangeListener for the horizontal and vertical scrollbars. private void sbPropertyChange(PropertyChangeEvent e) { String propertyName = e.getPropertyName(); Object source = e.getSource(); if ("model" == propertyName) { JScrollBar sb = scrollpane.getVerticalScrollBar(); BoundedRangeModel oldModel = (BoundedRangeModel)e. getOldValue(); ChangeListener cl = null; if (source == sb) { cl = vsbChangeListener; } else if (source == scrollpane.getHorizontalScrollBar()) { sb = scrollpane.getHorizontalScrollBar(); cl = hsbChangeListener; } if (cl != null) { if (oldModel != null) { oldModel.removeChangeListener(cl); } if (sb.getModel() != null) { sb.getModel().addChangeListener(cl); } } } else if ("componentOrientation" == propertyName) { if (source == scrollpane.getHorizontalScrollBar()) { JScrollBar hsb = scrollpane.getHorizontalScrollBar(); JViewport viewport = scrollpane.getViewport(); Point p = viewport.getViewPosition(); if (scrollpane.getComponentOrientation().isLeftToRight()) { p.x = hsb.getValue(); } else { p.x = viewport.getViewSize().width - viewport.getExtentSize().width - hsb.getValue(); } viewport.setViewPosition(p); } } } } }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; import java.awt.Font; import javax.swing.plaf.UIResource; /** {@collect.stats} * A subclass of java.awt.Font that implements UIResource. * UI classes which set default font properties should use * this class. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @see javax.swing.plaf.UIResource * @author Hans Muller * */ public class FontUIResource extends Font implements UIResource { public FontUIResource(String name, int style, int size) { super(name, style, size); } public FontUIResource(Font font) { super(font); } }
Java
/* * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; /** {@collect.stats} * Pluggable look and feel interface for JDesktopPane. * * @author David Kloba */ public abstract class DesktopPaneUI extends ComponentUI { }
Java
/* * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; /** {@collect.stats} * Pluggable look and feel interface for JToolTip. * * @author Dave Moore */ public abstract class ToolTipUI extends ComponentUI { }
Java
/* * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; /** {@collect.stats} * Pluggable look and feel interface for JInternalFrame. * * @author David Kloba */ public abstract class InternalFrameUI extends ComponentUI { }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; import javax.swing.JList; import java.awt.Point; import java.awt.Rectangle; /** {@collect.stats} * The {@code JList} pluggable look and feel delegate. * * @author Hans Muller */ public abstract class ListUI extends ComponentUI { /** {@collect.stats} * Returns the cell index in the specified {@code JList} closest to the * given location in the list's coordinate system. To determine if the * cell actually contains the specified location, compare the point against * the cell's bounds, as provided by {@code getCellBounds}. * This method returns {@code -1} if the list's model is empty. * * @param list the list * @param location the coordinates of the point * @return the cell index closest to the given location, or {@code -1} * @throws NullPointerException if {@code location} is null */ public abstract int locationToIndex(JList list, Point location); /** {@collect.stats} * Returns the origin in the given {@code JList}, of the specified item, * in the list's coordinate system. * Returns {@code null} if the index isn't valid. * * @param list the list * @param index the cell index * @return the origin of the cell, or {@code null} */ public abstract Point indexToLocation(JList list, int index); /** {@collect.stats} * Returns the bounding rectangle, in the given list's coordinate system, * for the range of cells specified by the two indices. * The indices can be supplied in any order. * <p> * If the smaller index is outside the list's range of cells, this method * returns {@code null}. If the smaller index is valid, but the larger * index is outside the list's range, the bounds of just the first index * is returned. Otherwise, the bounds of the valid range is returned. * * @param list the list * @param index1 the first index in the range * @param index2 the second index in the range * @return the bounding rectangle for the range of cells, or {@code null} */ public abstract Rectangle getCellBounds(JList list, int index1, int index2); }
Java
/* * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; import java.awt.Component; import java.awt.Insets; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.io.Serializable; import javax.swing.border.*; import javax.swing.Icon; import javax.swing.plaf.UIResource; /* * A Border wrapper class which implements UIResource. UI * classes which set border properties should use this class * to wrap any borders specified as defaults. * * This class delegates all method invocations to the * Border "delegate" object specified at construction. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @see javax.swing.plaf.UIResource * @author Amy Fowler * */ public class BorderUIResource implements Border, UIResource, Serializable { static Border etched; static Border loweredBevel; static Border raisedBevel; static Border blackLine; public static Border getEtchedBorderUIResource() { if (etched == null) { etched = new EtchedBorderUIResource(); } return etched; } public static Border getLoweredBevelBorderUIResource() { if (loweredBevel == null) { loweredBevel = new BevelBorderUIResource(BevelBorder.LOWERED); } return loweredBevel; } public static Border getRaisedBevelBorderUIResource() { if (raisedBevel == null) { raisedBevel = new BevelBorderUIResource(BevelBorder.RAISED); } return raisedBevel; } public static Border getBlackLineBorderUIResource() { if (blackLine == null) { blackLine = new LineBorderUIResource(Color.black); } return blackLine; } private Border delegate; /** {@collect.stats} * Creates a UIResource border object which wraps * an existing Border instance. * @param delegate the border being wrapped */ public BorderUIResource(Border delegate) { if (delegate == null) { throw new IllegalArgumentException("null border delegate argument"); } this.delegate = delegate; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { delegate.paintBorder(c, g, x, y, width, height); } public Insets getBorderInsets(Component c) { return delegate.getBorderInsets(c); } public boolean isBorderOpaque() { return delegate.isBorderOpaque(); } public static class CompoundBorderUIResource extends CompoundBorder implements UIResource { public CompoundBorderUIResource(Border outsideBorder, Border insideBorder) { super(outsideBorder, insideBorder); } } public static class EmptyBorderUIResource extends EmptyBorder implements UIResource { public EmptyBorderUIResource(int top, int left, int bottom, int right) { super(top, left, bottom, right); } public EmptyBorderUIResource(Insets insets) { super(insets); } } public static class LineBorderUIResource extends LineBorder implements UIResource { public LineBorderUIResource(Color color) { super(color); } public LineBorderUIResource(Color color, int thickness) { super(color, thickness); } } public static class BevelBorderUIResource extends BevelBorder implements UIResource { public BevelBorderUIResource(int bevelType) { super(bevelType); } public BevelBorderUIResource(int bevelType, Color highlight, Color shadow) { super(bevelType, highlight, shadow); } public BevelBorderUIResource(int bevelType, Color highlightOuter, Color highlightInner, Color shadowOuter, Color shadowInner) { super(bevelType, highlightOuter, highlightInner, shadowOuter, shadowInner); } } public static class EtchedBorderUIResource extends EtchedBorder implements UIResource { public EtchedBorderUIResource() { super(); } public EtchedBorderUIResource(int etchType) { super(etchType); } public EtchedBorderUIResource(Color highlight, Color shadow) { super(highlight, shadow); } public EtchedBorderUIResource(int etchType, Color highlight, Color shadow) { super(etchType, highlight, shadow); } } public static class MatteBorderUIResource extends MatteBorder implements UIResource { public MatteBorderUIResource(int top, int left, int bottom, int right, Color color) { super(top, left, bottom, right, color); } public MatteBorderUIResource(int top, int left, int bottom, int right, Icon tileIcon) { super(top, left, bottom, right, tileIcon); } public MatteBorderUIResource(Icon tileIcon) { super(tileIcon); } } public static class TitledBorderUIResource extends TitledBorder implements UIResource { public TitledBorderUIResource(String title) { super(title); } public TitledBorderUIResource(Border border) { super(border); } public TitledBorderUIResource(Border border, String title) { super(border, title); } public TitledBorderUIResource(Border border, String title, int titleJustification, int titlePosition) { super(border, title, titleJustification, titlePosition); } public TitledBorderUIResource(Border border, String title, int titleJustification, int titlePosition, Font titleFont) { super(border, title, titleJustification, titlePosition, titleFont); } public TitledBorderUIResource(Border border, String title, int titleJustification, int titlePosition, Font titleFont, Color titleColor) { super(border, title, titleJustification, titlePosition, titleFont, titleColor); } } }
Java
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; import java.awt.Dimension; import javax.swing.plaf.UIResource; /* * A subclass of <code>Dimension</code> that implements * <code>UIResource</code>. UI classes that use * <code>Dimension</code> values for default properties * should use this class. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @see javax.swing.plaf.UIResource * @author Amy Fowler * */ public class DimensionUIResource extends Dimension implements UIResource { public DimensionUIResource(int width, int height) { super(width, height); } }
Java
/* * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; /** {@collect.stats} * Pluggable look and feel interface for JScrollBar. * * @author David Kloba */ public abstract class ScrollBarUI extends ComponentUI { }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; import java.awt.Component; import java.awt.Graphics; import java.io.Serializable; import javax.swing.Icon; import javax.swing.plaf.UIResource; /** {@collect.stats} * An Icon wrapper class which implements UIResource. UI * classes which set icon properties should use this class * to wrap any icons specified as defaults. * * This class delegates all method invocations to the * Icon "delegate" object specified at construction. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @see javax.swing.plaf.UIResource * @author Amy Fowler * */ public class IconUIResource implements Icon, UIResource, Serializable { private Icon delegate; /** {@collect.stats} * Creates a UIResource icon object which wraps * an existing Icon instance. * @param delegate the icon being wrapped */ public IconUIResource(Icon delegate) { if (delegate == null) { throw new IllegalArgumentException("null delegate icon argument"); } this.delegate = delegate; } public void paintIcon(Component c, Graphics g, int x, int y) { delegate.paintIcon(c, g, x, y); } public int getIconWidth() { return delegate.getIconWidth(); } public int getIconHeight() { return delegate.getIconHeight(); } }
Java
/* * Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; /** {@collect.stats} * Pluggable look and feel interface for JSpinner * * @author Hans Muller * @since 1.4 */ public abstract class SpinnerUI extends javax.swing.plaf.ComponentUI { }
Java
/* * Copyright (c) 1997, 2000, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf; import java.awt.event.MouseEvent; import javax.swing.Popup; import javax.swing.PopupFactory; import javax.swing.JPopupMenu; /** {@collect.stats} * Pluggable look and feel interface for JPopupMenu. * * @author Georges Saab * @author David Karlton */ public abstract class PopupMenuUI extends ComponentUI { /** {@collect.stats} * @since 1.3 */ public boolean isPopupTrigger(MouseEvent e) { return e.isPopupTrigger(); } /** {@collect.stats} * Returns the <code>Popup</code> that will be responsible for * displaying the <code>JPopupMenu</code>. * * @param popup JPopupMenu requesting Popup * @param x Screen x location Popup is to be shown at * @param y Screen y location Popup is to be shown at. * @return Popup that will show the JPopupMenu * @since 1.4 */ public Popup getPopup(JPopupMenu popup, int x, int y) { PopupFactory popupFactory = PopupFactory.getSharedInstance(); return popupFactory.getPopup(popup.getInvoker(), popup, x, y); } }
Java
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.multi; import java.util.Vector; import javax.swing.plaf.SliderUI; import javax.swing.plaf.ComponentUI; import javax.swing.JComponent; import java.awt.Graphics; import java.awt.Dimension; import javax.accessibility.Accessible; /** {@collect.stats} * A multiplexing UI used to combine <code>SliderUI</code>s. * * <p>This file was automatically generated by AutoMulti. * * @author Otto Multey */ public class MultiSliderUI extends SliderUI { /** {@collect.stats} * The vector containing the real UIs. This is populated * in the call to <code>createUI</code>, and can be obtained by calling * the <code>getUIs</code> method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector(); //////////////////// // Common UI methods //////////////////// /** {@collect.stats} * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // SliderUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** {@collect.stats} * Invokes the <code>contains</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = ((ComponentUI) (uis.elementAt(0))).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).contains(a,b,c); } return returnValue; } /** {@collect.stats} * Invokes the <code>update</code> method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).update(a,b); } } /** {@collect.stats} * Returns a multiplexing UI instance if any of the auxiliary * <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the * UI object obtained from the default <code>LookAndFeel</code>. */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiSliderUI(); return MultiLookAndFeel.createUIs(mui, ((MultiSliderUI) mui).uis, a); } /** {@collect.stats} * Invokes the <code>installUI</code> method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).installUI(a); } } /** {@collect.stats} * Invokes the <code>uninstallUI</code> method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).uninstallUI(a); } } /** {@collect.stats} * Invokes the <code>paint</code> method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).paint(a,b); } } /** {@collect.stats} * Invokes the <code>getPreferredSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMinimumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMaximumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChild</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b); } return returnValue; } }
Java
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.multi; import java.util.Vector; import javax.swing.plaf.DesktopPaneUI; import javax.swing.plaf.ComponentUI; import javax.swing.JComponent; import java.awt.Graphics; import java.awt.Dimension; import javax.accessibility.Accessible; /** {@collect.stats} * A multiplexing UI used to combine <code>DesktopPaneUI</code>s. * * <p>This file was automatically generated by AutoMulti. * * @author Otto Multey */ public class MultiDesktopPaneUI extends DesktopPaneUI { /** {@collect.stats} * The vector containing the real UIs. This is populated * in the call to <code>createUI</code>, and can be obtained by calling * the <code>getUIs</code> method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector(); //////////////////// // Common UI methods //////////////////// /** {@collect.stats} * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // DesktopPaneUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** {@collect.stats} * Invokes the <code>contains</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = ((ComponentUI) (uis.elementAt(0))).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).contains(a,b,c); } return returnValue; } /** {@collect.stats} * Invokes the <code>update</code> method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).update(a,b); } } /** {@collect.stats} * Returns a multiplexing UI instance if any of the auxiliary * <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the * UI object obtained from the default <code>LookAndFeel</code>. */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiDesktopPaneUI(); return MultiLookAndFeel.createUIs(mui, ((MultiDesktopPaneUI) mui).uis, a); } /** {@collect.stats} * Invokes the <code>installUI</code> method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).installUI(a); } } /** {@collect.stats} * Invokes the <code>uninstallUI</code> method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).uninstallUI(a); } } /** {@collect.stats} * Invokes the <code>paint</code> method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).paint(a,b); } } /** {@collect.stats} * Invokes the <code>getPreferredSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMinimumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMaximumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChild</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b); } return returnValue; } }
Java
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.multi; import java.util.Vector; import javax.swing.plaf.ProgressBarUI; import javax.swing.plaf.ComponentUI; import javax.swing.JComponent; import java.awt.Graphics; import java.awt.Dimension; import javax.accessibility.Accessible; /** {@collect.stats} * A multiplexing UI used to combine <code>ProgressBarUI</code>s. * * <p>This file was automatically generated by AutoMulti. * * @author Otto Multey */ public class MultiProgressBarUI extends ProgressBarUI { /** {@collect.stats} * The vector containing the real UIs. This is populated * in the call to <code>createUI</code>, and can be obtained by calling * the <code>getUIs</code> method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector(); //////////////////// // Common UI methods //////////////////// /** {@collect.stats} * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // ProgressBarUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** {@collect.stats} * Invokes the <code>contains</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = ((ComponentUI) (uis.elementAt(0))).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).contains(a,b,c); } return returnValue; } /** {@collect.stats} * Invokes the <code>update</code> method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).update(a,b); } } /** {@collect.stats} * Returns a multiplexing UI instance if any of the auxiliary * <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the * UI object obtained from the default <code>LookAndFeel</code>. */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiProgressBarUI(); return MultiLookAndFeel.createUIs(mui, ((MultiProgressBarUI) mui).uis, a); } /** {@collect.stats} * Invokes the <code>installUI</code> method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).installUI(a); } } /** {@collect.stats} * Invokes the <code>uninstallUI</code> method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).uninstallUI(a); } } /** {@collect.stats} * Invokes the <code>paint</code> method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).paint(a,b); } } /** {@collect.stats} * Invokes the <code>getPreferredSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMinimumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMaximumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChild</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b); } return returnValue; } }
Java
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.multi; import java.util.Vector; import javax.swing.plaf.TableUI; import javax.swing.plaf.ComponentUI; import javax.swing.JComponent; import java.awt.Graphics; import java.awt.Dimension; import javax.accessibility.Accessible; /** {@collect.stats} * A multiplexing UI used to combine <code>TableUI</code>s. * * <p>This file was automatically generated by AutoMulti. * * @author Otto Multey */ public class MultiTableUI extends TableUI { /** {@collect.stats} * The vector containing the real UIs. This is populated * in the call to <code>createUI</code>, and can be obtained by calling * the <code>getUIs</code> method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector(); //////////////////// // Common UI methods //////////////////// /** {@collect.stats} * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // TableUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** {@collect.stats} * Invokes the <code>contains</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = ((ComponentUI) (uis.elementAt(0))).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).contains(a,b,c); } return returnValue; } /** {@collect.stats} * Invokes the <code>update</code> method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).update(a,b); } } /** {@collect.stats} * Returns a multiplexing UI instance if any of the auxiliary * <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the * UI object obtained from the default <code>LookAndFeel</code>. */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiTableUI(); return MultiLookAndFeel.createUIs(mui, ((MultiTableUI) mui).uis, a); } /** {@collect.stats} * Invokes the <code>installUI</code> method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).installUI(a); } } /** {@collect.stats} * Invokes the <code>uninstallUI</code> method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).uninstallUI(a); } } /** {@collect.stats} * Invokes the <code>paint</code> method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).paint(a,b); } } /** {@collect.stats} * Invokes the <code>getPreferredSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMinimumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMaximumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChild</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b); } return returnValue; } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.multi; import java.util.Vector; import javax.swing.plaf.PopupMenuUI; import java.awt.event.MouseEvent; import javax.swing.Popup; import javax.swing.JPopupMenu; import javax.swing.plaf.ComponentUI; import javax.swing.JComponent; import java.awt.Graphics; import java.awt.Dimension; import javax.accessibility.Accessible; /** {@collect.stats} * A multiplexing UI used to combine <code>PopupMenuUI</code>s. * * <p>This file was automatically generated by AutoMulti. * * @author Otto Multey */ public class MultiPopupMenuUI extends PopupMenuUI { /** {@collect.stats} * The vector containing the real UIs. This is populated * in the call to <code>createUI</code>, and can be obtained by calling * the <code>getUIs</code> method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector(); //////////////////// // Common UI methods //////////////////// /** {@collect.stats} * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // PopupMenuUI methods //////////////////// /** {@collect.stats} * Invokes the <code>isPopupTrigger</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> * @since 1.3 */ public boolean isPopupTrigger(MouseEvent a) { boolean returnValue = ((PopupMenuUI) (uis.elementAt(0))).isPopupTrigger(a); for (int i = 1; i < uis.size(); i++) { ((PopupMenuUI) (uis.elementAt(i))).isPopupTrigger(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getPopup</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> * @since 1.4 */ public Popup getPopup(JPopupMenu a, int b, int c) { Popup returnValue = ((PopupMenuUI) (uis.elementAt(0))).getPopup(a,b,c); for (int i = 1; i < uis.size(); i++) { ((PopupMenuUI) (uis.elementAt(i))).getPopup(a,b,c); } return returnValue; } //////////////////// // ComponentUI methods //////////////////// /** {@collect.stats} * Invokes the <code>contains</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = ((ComponentUI) (uis.elementAt(0))).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).contains(a,b,c); } return returnValue; } /** {@collect.stats} * Invokes the <code>update</code> method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).update(a,b); } } /** {@collect.stats} * Returns a multiplexing UI instance if any of the auxiliary * <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the * UI object obtained from the default <code>LookAndFeel</code>. */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiPopupMenuUI(); return MultiLookAndFeel.createUIs(mui, ((MultiPopupMenuUI) mui).uis, a); } /** {@collect.stats} * Invokes the <code>installUI</code> method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).installUI(a); } } /** {@collect.stats} * Invokes the <code>uninstallUI</code> method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).uninstallUI(a); } } /** {@collect.stats} * Invokes the <code>paint</code> method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).paint(a,b); } } /** {@collect.stats} * Invokes the <code>getPreferredSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMinimumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMaximumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChild</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b); } return returnValue; } }
Java
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.multi; import java.util.Vector; import javax.swing.plaf.TreeUI; import java.awt.Rectangle; import javax.swing.JTree; import javax.swing.tree.TreePath; import javax.swing.plaf.ComponentUI; import javax.swing.JComponent; import java.awt.Graphics; import java.awt.Dimension; import javax.accessibility.Accessible; /** {@collect.stats} * A multiplexing UI used to combine <code>TreeUI</code>s. * * <p>This file was automatically generated by AutoMulti. * * @author Otto Multey */ public class MultiTreeUI extends TreeUI { /** {@collect.stats} * The vector containing the real UIs. This is populated * in the call to <code>createUI</code>, and can be obtained by calling * the <code>getUIs</code> method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector(); //////////////////// // Common UI methods //////////////////// /** {@collect.stats} * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // TreeUI methods //////////////////// /** {@collect.stats} * Invokes the <code>getPathBounds</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Rectangle getPathBounds(JTree a, TreePath b) { Rectangle returnValue = ((TreeUI) (uis.elementAt(0))).getPathBounds(a,b); for (int i = 1; i < uis.size(); i++) { ((TreeUI) (uis.elementAt(i))).getPathBounds(a,b); } return returnValue; } /** {@collect.stats} * Invokes the <code>getPathForRow</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public TreePath getPathForRow(JTree a, int b) { TreePath returnValue = ((TreeUI) (uis.elementAt(0))).getPathForRow(a,b); for (int i = 1; i < uis.size(); i++) { ((TreeUI) (uis.elementAt(i))).getPathForRow(a,b); } return returnValue; } /** {@collect.stats} * Invokes the <code>getRowForPath</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int getRowForPath(JTree a, TreePath b) { int returnValue = ((TreeUI) (uis.elementAt(0))).getRowForPath(a,b); for (int i = 1; i < uis.size(); i++) { ((TreeUI) (uis.elementAt(i))).getRowForPath(a,b); } return returnValue; } /** {@collect.stats} * Invokes the <code>getRowCount</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int getRowCount(JTree a) { int returnValue = ((TreeUI) (uis.elementAt(0))).getRowCount(a); for (int i = 1; i < uis.size(); i++) { ((TreeUI) (uis.elementAt(i))).getRowCount(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getClosestPathForLocation</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public TreePath getClosestPathForLocation(JTree a, int b, int c) { TreePath returnValue = ((TreeUI) (uis.elementAt(0))).getClosestPathForLocation(a,b,c); for (int i = 1; i < uis.size(); i++) { ((TreeUI) (uis.elementAt(i))).getClosestPathForLocation(a,b,c); } return returnValue; } /** {@collect.stats} * Invokes the <code>isEditing</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public boolean isEditing(JTree a) { boolean returnValue = ((TreeUI) (uis.elementAt(0))).isEditing(a); for (int i = 1; i < uis.size(); i++) { ((TreeUI) (uis.elementAt(i))).isEditing(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>stopEditing</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public boolean stopEditing(JTree a) { boolean returnValue = ((TreeUI) (uis.elementAt(0))).stopEditing(a); for (int i = 1; i < uis.size(); i++) { ((TreeUI) (uis.elementAt(i))).stopEditing(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>cancelEditing</code> method on each UI handled by this object. */ public void cancelEditing(JTree a) { for (int i = 0; i < uis.size(); i++) { ((TreeUI) (uis.elementAt(i))).cancelEditing(a); } } /** {@collect.stats} * Invokes the <code>startEditingAtPath</code> method on each UI handled by this object. */ public void startEditingAtPath(JTree a, TreePath b) { for (int i = 0; i < uis.size(); i++) { ((TreeUI) (uis.elementAt(i))).startEditingAtPath(a,b); } } /** {@collect.stats} * Invokes the <code>getEditingPath</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public TreePath getEditingPath(JTree a) { TreePath returnValue = ((TreeUI) (uis.elementAt(0))).getEditingPath(a); for (int i = 1; i < uis.size(); i++) { ((TreeUI) (uis.elementAt(i))).getEditingPath(a); } return returnValue; } //////////////////// // ComponentUI methods //////////////////// /** {@collect.stats} * Invokes the <code>contains</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = ((ComponentUI) (uis.elementAt(0))).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).contains(a,b,c); } return returnValue; } /** {@collect.stats} * Invokes the <code>update</code> method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).update(a,b); } } /** {@collect.stats} * Returns a multiplexing UI instance if any of the auxiliary * <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the * UI object obtained from the default <code>LookAndFeel</code>. */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiTreeUI(); return MultiLookAndFeel.createUIs(mui, ((MultiTreeUI) mui).uis, a); } /** {@collect.stats} * Invokes the <code>installUI</code> method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).installUI(a); } } /** {@collect.stats} * Invokes the <code>uninstallUI</code> method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).uninstallUI(a); } } /** {@collect.stats} * Invokes the <code>paint</code> method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).paint(a,b); } } /** {@collect.stats} * Invokes the <code>getPreferredSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMinimumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMaximumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChild</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b); } return returnValue; } }
Java
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.multi; import java.util.Vector; import javax.swing.plaf.ScrollPaneUI; import javax.swing.plaf.ComponentUI; import javax.swing.JComponent; import java.awt.Graphics; import java.awt.Dimension; import javax.accessibility.Accessible; /** {@collect.stats} * A multiplexing UI used to combine <code>ScrollPaneUI</code>s. * * <p>This file was automatically generated by AutoMulti. * * @author Otto Multey */ public class MultiScrollPaneUI extends ScrollPaneUI { /** {@collect.stats} * The vector containing the real UIs. This is populated * in the call to <code>createUI</code>, and can be obtained by calling * the <code>getUIs</code> method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector(); //////////////////// // Common UI methods //////////////////// /** {@collect.stats} * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // ScrollPaneUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** {@collect.stats} * Invokes the <code>contains</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = ((ComponentUI) (uis.elementAt(0))).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).contains(a,b,c); } return returnValue; } /** {@collect.stats} * Invokes the <code>update</code> method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).update(a,b); } } /** {@collect.stats} * Returns a multiplexing UI instance if any of the auxiliary * <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the * UI object obtained from the default <code>LookAndFeel</code>. */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiScrollPaneUI(); return MultiLookAndFeel.createUIs(mui, ((MultiScrollPaneUI) mui).uis, a); } /** {@collect.stats} * Invokes the <code>installUI</code> method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).installUI(a); } } /** {@collect.stats} * Invokes the <code>uninstallUI</code> method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).uninstallUI(a); } } /** {@collect.stats} * Invokes the <code>paint</code> method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).paint(a,b); } } /** {@collect.stats} * Invokes the <code>getPreferredSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMinimumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMaximumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChild</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b); } return returnValue; } }
Java
/* * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.multi; import java.util.Vector; import javax.swing.plaf.ViewportUI; import javax.swing.plaf.ComponentUI; import javax.swing.JComponent; import java.awt.Graphics; import java.awt.Dimension; import javax.accessibility.Accessible; /** {@collect.stats} * A multiplexing UI used to combine <code>ViewportUI</code>s. * * <p>This file was automatically generated by AutoMulti. * * @author Otto Multey */ public class MultiViewportUI extends ViewportUI { /** {@collect.stats} * The vector containing the real UIs. This is populated * in the call to <code>createUI</code>, and can be obtained by calling * the <code>getUIs</code> method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector(); //////////////////// // Common UI methods //////////////////// /** {@collect.stats} * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // ViewportUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** {@collect.stats} * Invokes the <code>contains</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = ((ComponentUI) (uis.elementAt(0))).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).contains(a,b,c); } return returnValue; } /** {@collect.stats} * Invokes the <code>update</code> method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).update(a,b); } } /** {@collect.stats} * Returns a multiplexing UI instance if any of the auxiliary * <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the * UI object obtained from the default <code>LookAndFeel</code>. */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiViewportUI(); return MultiLookAndFeel.createUIs(mui, ((MultiViewportUI) mui).uis, a); } /** {@collect.stats} * Invokes the <code>installUI</code> method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).installUI(a); } } /** {@collect.stats} * Invokes the <code>uninstallUI</code> method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).uninstallUI(a); } } /** {@collect.stats} * Invokes the <code>paint</code> method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).paint(a,b); } } /** {@collect.stats} * Invokes the <code>getPreferredSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMinimumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMaximumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChild</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b); } return returnValue; } }
Java
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.multi; import java.util.Vector; import javax.swing.plaf.SeparatorUI; import javax.swing.plaf.ComponentUI; import javax.swing.JComponent; import java.awt.Graphics; import java.awt.Dimension; import javax.accessibility.Accessible; /** {@collect.stats} * A multiplexing UI used to combine <code>SeparatorUI</code>s. * * <p>This file was automatically generated by AutoMulti. * * @author Otto Multey */ public class MultiSeparatorUI extends SeparatorUI { /** {@collect.stats} * The vector containing the real UIs. This is populated * in the call to <code>createUI</code>, and can be obtained by calling * the <code>getUIs</code> method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector(); //////////////////// // Common UI methods //////////////////// /** {@collect.stats} * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // SeparatorUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** {@collect.stats} * Invokes the <code>contains</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = ((ComponentUI) (uis.elementAt(0))).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).contains(a,b,c); } return returnValue; } /** {@collect.stats} * Invokes the <code>update</code> method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).update(a,b); } } /** {@collect.stats} * Returns a multiplexing UI instance if any of the auxiliary * <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the * UI object obtained from the default <code>LookAndFeel</code>. */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiSeparatorUI(); return MultiLookAndFeel.createUIs(mui, ((MultiSeparatorUI) mui).uis, a); } /** {@collect.stats} * Invokes the <code>installUI</code> method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).installUI(a); } } /** {@collect.stats} * Invokes the <code>uninstallUI</code> method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).uninstallUI(a); } } /** {@collect.stats} * Invokes the <code>paint</code> method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).paint(a,b); } } /** {@collect.stats} * Invokes the <code>getPreferredSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMinimumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMaximumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChild</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b); } return returnValue; } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.multi; import java.util.Vector; import javax.swing.plaf.TextUI; import java.lang.String; import javax.swing.text.JTextComponent; import java.awt.Point; import java.awt.Rectangle; import javax.swing.text.BadLocationException; import javax.swing.text.Position; import javax.swing.text.EditorKit; import javax.swing.text.View; import javax.swing.plaf.ComponentUI; import javax.swing.JComponent; import java.awt.Graphics; import java.awt.Dimension; import javax.accessibility.Accessible; /** {@collect.stats} * A multiplexing UI used to combine <code>TextUI</code>s. * * <p>This file was automatically generated by AutoMulti. * * @author Otto Multey */ public class MultiTextUI extends TextUI { /** {@collect.stats} * The vector containing the real UIs. This is populated * in the call to <code>createUI</code>, and can be obtained by calling * the <code>getUIs</code> method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector(); //////////////////// // Common UI methods //////////////////// /** {@collect.stats} * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // TextUI methods //////////////////// /** {@collect.stats} * Invokes the <code>getToolTipText</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> * @since 1.4 */ public String getToolTipText(JTextComponent a, Point b) { String returnValue = ((TextUI) (uis.elementAt(0))).getToolTipText(a,b); for (int i = 1; i < uis.size(); i++) { ((TextUI) (uis.elementAt(i))).getToolTipText(a,b); } return returnValue; } /** {@collect.stats} * Invokes the <code>modelToView</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Rectangle modelToView(JTextComponent a, int b) throws BadLocationException { Rectangle returnValue = ((TextUI) (uis.elementAt(0))).modelToView(a,b); for (int i = 1; i < uis.size(); i++) { ((TextUI) (uis.elementAt(i))).modelToView(a,b); } return returnValue; } /** {@collect.stats} * Invokes the <code>modelToView</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Rectangle modelToView(JTextComponent a, int b, Position.Bias c) throws BadLocationException { Rectangle returnValue = ((TextUI) (uis.elementAt(0))).modelToView(a,b,c); for (int i = 1; i < uis.size(); i++) { ((TextUI) (uis.elementAt(i))).modelToView(a,b,c); } return returnValue; } /** {@collect.stats} * Invokes the <code>viewToModel</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int viewToModel(JTextComponent a, Point b) { int returnValue = ((TextUI) (uis.elementAt(0))).viewToModel(a,b); for (int i = 1; i < uis.size(); i++) { ((TextUI) (uis.elementAt(i))).viewToModel(a,b); } return returnValue; } /** {@collect.stats} * Invokes the <code>viewToModel</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int viewToModel(JTextComponent a, Point b, Position.Bias[] c) { int returnValue = ((TextUI) (uis.elementAt(0))).viewToModel(a,b,c); for (int i = 1; i < uis.size(); i++) { ((TextUI) (uis.elementAt(i))).viewToModel(a,b,c); } return returnValue; } /** {@collect.stats} * Invokes the <code>getNextVisualPositionFrom</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int getNextVisualPositionFrom(JTextComponent a, int b, Position.Bias c, int d, Position.Bias[] e) throws BadLocationException { int returnValue = ((TextUI) (uis.elementAt(0))).getNextVisualPositionFrom(a,b,c,d,e); for (int i = 1; i < uis.size(); i++) { ((TextUI) (uis.elementAt(i))).getNextVisualPositionFrom(a,b,c,d,e); } return returnValue; } /** {@collect.stats} * Invokes the <code>damageRange</code> method on each UI handled by this object. */ public void damageRange(JTextComponent a, int b, int c) { for (int i = 0; i < uis.size(); i++) { ((TextUI) (uis.elementAt(i))).damageRange(a,b,c); } } /** {@collect.stats} * Invokes the <code>damageRange</code> method on each UI handled by this object. */ public void damageRange(JTextComponent a, int b, int c, Position.Bias d, Position.Bias e) { for (int i = 0; i < uis.size(); i++) { ((TextUI) (uis.elementAt(i))).damageRange(a,b,c,d,e); } } /** {@collect.stats} * Invokes the <code>getEditorKit</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public EditorKit getEditorKit(JTextComponent a) { EditorKit returnValue = ((TextUI) (uis.elementAt(0))).getEditorKit(a); for (int i = 1; i < uis.size(); i++) { ((TextUI) (uis.elementAt(i))).getEditorKit(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getRootView</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public View getRootView(JTextComponent a) { View returnValue = ((TextUI) (uis.elementAt(0))).getRootView(a); for (int i = 1; i < uis.size(); i++) { ((TextUI) (uis.elementAt(i))).getRootView(a); } return returnValue; } //////////////////// // ComponentUI methods //////////////////// /** {@collect.stats} * Invokes the <code>contains</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = ((ComponentUI) (uis.elementAt(0))).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).contains(a,b,c); } return returnValue; } /** {@collect.stats} * Invokes the <code>update</code> method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).update(a,b); } } /** {@collect.stats} * Returns a multiplexing UI instance if any of the auxiliary * <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the * UI object obtained from the default <code>LookAndFeel</code>. */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiTextUI(); return MultiLookAndFeel.createUIs(mui, ((MultiTextUI) mui).uis, a); } /** {@collect.stats} * Invokes the <code>installUI</code> method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).installUI(a); } } /** {@collect.stats} * Invokes the <code>uninstallUI</code> method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).uninstallUI(a); } } /** {@collect.stats} * Invokes the <code>paint</code> method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).paint(a,b); } } /** {@collect.stats} * Invokes the <code>getPreferredSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMinimumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMaximumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChild</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b); } return returnValue; } }
Java
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.multi; import java.util.Vector; import javax.swing.plaf.MenuItemUI; import javax.swing.plaf.ButtonUI; import javax.swing.plaf.ComponentUI; import javax.swing.JComponent; import java.awt.Graphics; import java.awt.Dimension; import javax.accessibility.Accessible; /** {@collect.stats} * A multiplexing UI used to combine <code>MenuItemUI</code>s. * * <p>This file was automatically generated by AutoMulti. * * @author Otto Multey */ public class MultiMenuItemUI extends MenuItemUI { /** {@collect.stats} * The vector containing the real UIs. This is populated * in the call to <code>createUI</code>, and can be obtained by calling * the <code>getUIs</code> method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector(); //////////////////// // Common UI methods //////////////////// /** {@collect.stats} * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // MenuItemUI methods //////////////////// //////////////////// // ButtonUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** {@collect.stats} * Invokes the <code>contains</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = ((ComponentUI) (uis.elementAt(0))).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).contains(a,b,c); } return returnValue; } /** {@collect.stats} * Invokes the <code>update</code> method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).update(a,b); } } /** {@collect.stats} * Returns a multiplexing UI instance if any of the auxiliary * <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the * UI object obtained from the default <code>LookAndFeel</code>. */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiMenuItemUI(); return MultiLookAndFeel.createUIs(mui, ((MultiMenuItemUI) mui).uis, a); } /** {@collect.stats} * Invokes the <code>installUI</code> method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).installUI(a); } } /** {@collect.stats} * Invokes the <code>uninstallUI</code> method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).uninstallUI(a); } } /** {@collect.stats} * Invokes the <code>paint</code> method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).paint(a,b); } } /** {@collect.stats} * Invokes the <code>getPreferredSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMinimumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMaximumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChild</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b); } return returnValue; } }
Java
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.multi; import java.util.Vector; import javax.swing.plaf.MenuBarUI; import javax.swing.plaf.ComponentUI; import javax.swing.JComponent; import java.awt.Graphics; import java.awt.Dimension; import javax.accessibility.Accessible; /** {@collect.stats} * A multiplexing UI used to combine <code>MenuBarUI</code>s. * * <p>This file was automatically generated by AutoMulti. * * @author Otto Multey */ public class MultiMenuBarUI extends MenuBarUI { /** {@collect.stats} * The vector containing the real UIs. This is populated * in the call to <code>createUI</code>, and can be obtained by calling * the <code>getUIs</code> method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector(); //////////////////// // Common UI methods //////////////////// /** {@collect.stats} * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // MenuBarUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** {@collect.stats} * Invokes the <code>contains</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = ((ComponentUI) (uis.elementAt(0))).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).contains(a,b,c); } return returnValue; } /** {@collect.stats} * Invokes the <code>update</code> method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).update(a,b); } } /** {@collect.stats} * Returns a multiplexing UI instance if any of the auxiliary * <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the * UI object obtained from the default <code>LookAndFeel</code>. */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiMenuBarUI(); return MultiLookAndFeel.createUIs(mui, ((MultiMenuBarUI) mui).uis, a); } /** {@collect.stats} * Invokes the <code>installUI</code> method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).installUI(a); } } /** {@collect.stats} * Invokes the <code>uninstallUI</code> method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).uninstallUI(a); } } /** {@collect.stats} * Invokes the <code>paint</code> method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).paint(a,b); } } /** {@collect.stats} * Invokes the <code>getPreferredSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMinimumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMaximumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChild</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b); } return returnValue; } }
Java
/* * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.plaf.multi; import java.util.Vector; import javax.swing.plaf.LabelUI; import javax.swing.plaf.ComponentUI; import javax.swing.JComponent; import java.awt.Graphics; import java.awt.Dimension; import javax.accessibility.Accessible; /** {@collect.stats} * A multiplexing UI used to combine <code>LabelUI</code>s. * * <p>This file was automatically generated by AutoMulti. * * @author Otto Multey */ public class MultiLabelUI extends LabelUI { /** {@collect.stats} * The vector containing the real UIs. This is populated * in the call to <code>createUI</code>, and can be obtained by calling * the <code>getUIs</code> method. The first element is guaranteed to be the real UI * obtained from the default look and feel. */ protected Vector uis = new Vector(); //////////////////// // Common UI methods //////////////////// /** {@collect.stats} * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); } //////////////////// // LabelUI methods //////////////////// //////////////////// // ComponentUI methods //////////////////// /** {@collect.stats} * Invokes the <code>contains</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public boolean contains(JComponent a, int b, int c) { boolean returnValue = ((ComponentUI) (uis.elementAt(0))).contains(a,b,c); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).contains(a,b,c); } return returnValue; } /** {@collect.stats} * Invokes the <code>update</code> method on each UI handled by this object. */ public void update(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).update(a,b); } } /** {@collect.stats} * Returns a multiplexing UI instance if any of the auxiliary * <code>LookAndFeel</code>s supports this UI. Otherwise, just returns the * UI object obtained from the default <code>LookAndFeel</code>. */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiLabelUI(); return MultiLookAndFeel.createUIs(mui, ((MultiLabelUI) mui).uis, a); } /** {@collect.stats} * Invokes the <code>installUI</code> method on each UI handled by this object. */ public void installUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).installUI(a); } } /** {@collect.stats} * Invokes the <code>uninstallUI</code> method on each UI handled by this object. */ public void uninstallUI(JComponent a) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).uninstallUI(a); } } /** {@collect.stats} * Invokes the <code>paint</code> method on each UI handled by this object. */ public void paint(Graphics a, JComponent b) { for (int i = 0; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).paint(a,b); } } /** {@collect.stats} * Invokes the <code>getPreferredSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getPreferredSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getPreferredSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getPreferredSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMinimumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMinimumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMinimumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMinimumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getMaximumSize</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Dimension getMaximumSize(JComponent a) { Dimension returnValue = ((ComponentUI) (uis.elementAt(0))).getMaximumSize(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getMaximumSize(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChildrenCount</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public int getAccessibleChildrenCount(JComponent a) { int returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChildrenCount(a); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChildrenCount(a); } return returnValue; } /** {@collect.stats} * Invokes the <code>getAccessibleChild</code> method on each UI handled by this object. * * @return the value obtained from the first UI, which is * the UI obtained from the default <code>LookAndFeel</code> */ public Accessible getAccessibleChild(JComponent a, int b) { Accessible returnValue = ((ComponentUI) (uis.elementAt(0))).getAccessibleChild(a,b); for (int i = 1; i < uis.size(); i++) { ((ComponentUI) (uis.elementAt(i))).getAccessibleChild(a,b); } return returnValue; } }
Java