BasicRadioButtonUI.java 21.1 KB
Newer Older
D
duke 已提交
1
/*
V
van 已提交
2
 * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * 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
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * 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.
 *
21 22 23
 * 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.
D
duke 已提交
24 25 26 27 28 29 30 31 32 33 34
 */

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;
35
import sun.awt.AppContext;
V
van 已提交
36 37
import java.util.Enumeration;
import java.util.HashSet;
D
duke 已提交
38 39 40 41 42 43 44 45

/**
 * RadioButtonUI implementation for BasicRadioButtonUI
 *
 * @author Jeff Dinkins
 */
public class BasicRadioButtonUI extends BasicToggleButtonUI
{
46
    private static final Object BASIC_RADIO_BUTTON_UI_KEY = new Object();
D
duke 已提交
47

V
van 已提交
48 49 50
    /**
     * The icon.
     */
D
duke 已提交
51 52 53 54 55 56
    protected Icon icon;

    private boolean defaults_initialized = false;

    private final static String propertyPrefix = "RadioButton" + ".";

V
van 已提交
57 58
    private KeyListener keyListener = null;

D
duke 已提交
59 60 61
    // ********************************
    //        Create PLAF
    // ********************************
V
van 已提交
62 63 64 65 66 67 68

    /**
     * Returns an instance of {@code BasicRadioButtonUI}.
     *
     * @param b a component
     * @return an instance of {@code BasicRadioButtonUI}
     */
D
duke 已提交
69
    public static ComponentUI createUI(JComponent b) {
70 71 72 73 74 75 76
        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);
        }
D
duke 已提交
77 78 79
        return radioButtonUI;
    }

V
van 已提交
80
    @Override
D
duke 已提交
81 82 83 84 85 86 87
    protected String getPropertyPrefix() {
        return propertyPrefix;
    }

    // ********************************
    //        Install PLAF
    // ********************************
V
van 已提交
88 89
    @Override
    protected void installDefaults(AbstractButton b) {
D
duke 已提交
90 91 92 93 94 95 96 97 98 99
        super.installDefaults(b);
        if(!defaults_initialized) {
            icon = UIManager.getIcon(getPropertyPrefix() + "icon");
            defaults_initialized = true;
        }
    }

    // ********************************
    //        Uninstall PLAF
    // ********************************
V
van 已提交
100 101
    @Override
    protected void uninstallDefaults(AbstractButton b) {
D
duke 已提交
102 103 104 105
        super.uninstallDefaults(b);
        defaults_initialized = false;
    }

V
van 已提交
106 107 108 109 110
    /**
     * Returns the default icon.
     *
     * @return the default icon
     */
D
duke 已提交
111 112 113 114
    public Icon getDefaultIcon() {
        return icon;
    }

V
van 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    // ********************************
    //        Install Listeners
    // ********************************
    @Override
    protected void installListeners(AbstractButton button) {
        super.installListeners(button);

        // Only for JRadioButton
        if (!(button instanceof JRadioButton))
            return;

        keyListener = createKeyListener();
        button.addKeyListener(keyListener);

        // Need to get traversal key event
        button.setFocusTraversalKeysEnabled(false);

        // Map actions to the arrow keys
        button.getActionMap().put("Previous", new SelectPreviousBtn());
        button.getActionMap().put("Next", new SelectNextBtn());

        button.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
            put(KeyStroke.getKeyStroke("UP"), "Previous");
        button.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
            put(KeyStroke.getKeyStroke("DOWN"), "Next");
        button.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
            put(KeyStroke.getKeyStroke("LEFT"), "Previous");
        button.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
            put(KeyStroke.getKeyStroke("RIGHT"), "Next");
    }

    // ********************************
    //        UnInstall Listeners
    // ********************************
    @Override
    protected void uninstallListeners(AbstractButton button) {
        super.uninstallListeners(button);

        // Only for JRadioButton
        if (!(button instanceof JRadioButton))
            return;

        // Unmap actions from the arrow keys
        button.getActionMap().remove("Previous");
        button.getActionMap().remove("Next");
        button.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
                    .remove(KeyStroke.getKeyStroke("UP"));
        button.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
                    .remove(KeyStroke.getKeyStroke("DOWN"));
        button.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
                    .remove(KeyStroke.getKeyStroke("LEFT"));
        button.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
                    .remove(KeyStroke.getKeyStroke("RIGHT"));

        if (keyListener != null) {
            button.removeKeyListener(keyListener);
            keyListener = null;
        }
    }
D
duke 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188

    /* 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();

    /**
     * paint the radio button
     */
V
van 已提交
189
    @Override
D
duke 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    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()) {
242
                        altIcon = b.getRolloverSelectedIcon();
D
duke 已提交
243
                        if (altIcon == null) {
244
                                altIcon = b.getSelectedIcon();
D
duke 已提交
245 246
                        }
                } else {
247
                        altIcon = b.getSelectedIcon();
D
duke 已提交
248 249
                }
            } else if(b.isRolloverEnabled() && model.isRollover()) {
250
                altIcon = b.getRolloverIcon();
D
duke 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
            }

            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);
            }
        }
    }

V
van 已提交
279 280 281 282 283 284 285 286
    /**
     * Paints focused radio button.
     *
     * @param g an instance of {@code Graphics}
     * @param textRect bounds
     * @param size the size of radio button
     */
    protected void paintFocus(Graphics g, Rectangle textRect, Dimension size) {
D
duke 已提交
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    }


    /* 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);

    /**
     * The preferred size of the radio button
     */
V
van 已提交
304
    @Override
D
duke 已提交
305 306 307 308 309 310 311 312 313
    public Dimension getPreferredSize(JComponent c) {
        if(c.getComponentCount() > 0) {
            return null;
        }

        AbstractButton b = (AbstractButton) c;

        String text = b.getText();

314
        Icon buttonIcon = b.getIcon();
D
duke 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
        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);
    }
V
van 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440

    /////////////////////////// Private functions ////////////////////////
    /**
     * Creates the key listener to handle tab navigation in JRadioButton Group.
     */
    private KeyListener createKeyListener() {
         if (keyListener == null) {
            keyListener = new KeyHandler();
        }
        return keyListener;
    }


    private boolean isValidRadioButtonObj(Object obj) {
        return ((obj instanceof JRadioButton) &&
                    ((JRadioButton) obj).isVisible() &&
                    ((JRadioButton) obj).isEnabled());
    }

    /**
     * Select radio button based on "Previous" or "Next" operation
     *
     * @param event, the event object.
     * @param next, indicate if it's next one
     */
    private void selectRadioButton(ActionEvent event, boolean next) {
        // Get the source of the event.
        Object eventSrc = event.getSource();

        // Check whether the source is JRadioButton, it so, whether it is visible
        if (!isValidRadioButtonObj(eventSrc))
            return;

        ButtonGroupInfo btnGroupInfo = new ButtonGroupInfo((JRadioButton)eventSrc);
        btnGroupInfo.selectNewButton(next);
    }

    /////////////////////////// Inner Classes ////////////////////////
    @SuppressWarnings("serial")
    private class SelectPreviousBtn extends AbstractAction {
        public SelectPreviousBtn() {
            super("Previous");
        }

        public void actionPerformed(ActionEvent e) {
           BasicRadioButtonUI.this.selectRadioButton(e, false);
        }
    }

    @SuppressWarnings("serial")
    private class SelectNextBtn extends AbstractAction{
        public SelectNextBtn() {
            super("Next");
        }

        public void actionPerformed(ActionEvent e) {
            BasicRadioButtonUI.this.selectRadioButton(e, true);
        }
    }

    /**
     * ButtonGroupInfo, used to get related info in button group
     * for given radio button
     */
    private class ButtonGroupInfo {

        JRadioButton activeBtn = null;

        JRadioButton firstBtn = null;
        JRadioButton lastBtn = null;

        JRadioButton previousBtn = null;
        JRadioButton nextBtn = null;

        HashSet<JRadioButton> btnsInGroup = null;

        boolean srcFound = false;
        public ButtonGroupInfo(JRadioButton btn) {
            activeBtn = btn;
            btnsInGroup = new HashSet<JRadioButton>();
        }

        // Check if given object is in the button group
        boolean containsInGroup(Object obj){
           return btnsInGroup.contains(obj);
        }

        // Check if the next object to gain focus belongs
        // to the button group or not
        Component getFocusTransferBaseComponent(boolean next){
            Component focusBaseComp = activeBtn;
441
            Container container = focusBaseComp.getFocusCycleRootAncestor();
V
van 已提交
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
            if (container != null) {
                FocusTraversalPolicy policy = container.getFocusTraversalPolicy();
                Component comp = next ? policy.getComponentAfter(container, activeBtn)
                                      : policy.getComponentBefore(container, activeBtn);

                // If next component in the button group, use last/first button as base focus
                // otherwise, use the activeBtn as the base focus
                if (containsInGroup(comp)) {
                    focusBaseComp = next ? lastBtn : firstBtn;
                }
            }

            return focusBaseComp;
        }

        boolean getButtonGroupInfo() {
            if (activeBtn == null)
                return false;

            btnsInGroup.clear();

            // Get the button model from the source.
            ButtonModel model = activeBtn.getModel();
            if (!(model instanceof DefaultButtonModel))
                return false;

            // If the button model is DefaultButtonModel, and use it, otherwise return.
            DefaultButtonModel bm = (DefaultButtonModel) model;

            // get the ButtonGroup of the button from the button model
            ButtonGroup group = bm.getGroup();
            if (group == null)
                return false;

            // Get all the buttons in the group
            Enumeration<AbstractButton> e = group.getElements();
            if (e == null)
                return false;

            while (e.hasMoreElements()) {
                AbstractButton curElement = e.nextElement();
                if (!isValidRadioButtonObj(curElement))
                    continue;

                btnsInGroup.add((JRadioButton) curElement);

                // If firstBtn is not set yet, curElement is that first button
                if (null == firstBtn)
                    firstBtn = (JRadioButton) curElement;

                if (activeBtn == curElement)
                    srcFound = true;
                else if (!srcFound) {
                    // The source has not been yet found and the current element
                    // is the last previousBtn
                    previousBtn = (JRadioButton) curElement;
                } else if (nextBtn == null) {
                    // The source has been found and the current element
                    // is the next valid button of the list
                    nextBtn = (JRadioButton) curElement;
                }

                // Set new last "valid" JRadioButton of the list
                lastBtn = (JRadioButton) curElement;
            }

            return true;
        }

        /**
          * Find the new radio button that focus needs to be
          * moved to in the group, select the button
          *
          * @param next, indicate if it's arrow up/left or down/right
          */
        void selectNewButton(boolean next) {
            if (!getButtonGroupInfo())
                return;

            if (srcFound) {
                JRadioButton newSelectedBtn = null;
                if (next) {
                    // Select Next button. Cycle to the first button if the source
                    // button is the last of the group.
                    newSelectedBtn = (null == nextBtn) ? firstBtn : nextBtn;
                } else {
                    // Select previous button. Cycle to the last button if the source
                    // button is the first button of the group.
                    newSelectedBtn = (null == previousBtn) ? lastBtn : previousBtn;
                }
                if (newSelectedBtn != null &&
                    (newSelectedBtn != activeBtn)) {
                    newSelectedBtn.requestFocusInWindow();
                    newSelectedBtn.setSelected(true);
                }
            }
        }

        /**
          * Find the button group the passed in JRadioButton belongs to, and
          * move focus to next component of the last button in the group
          * or previous component of first button
          *
          * @param next, indicate if jump to next component or previous
          */
        void jumpToNextComponent(boolean next) {
            if (!getButtonGroupInfo()){
                // In case the button does not belong to any group, it needs
                // to be treated as a component
                if (activeBtn != null){
                    lastBtn = activeBtn;
                    firstBtn = activeBtn;
                }
                else
                    return;
            }

            // Update the component we will use as base to transfer
            // focus from
            JComponent compTransferFocusFrom = activeBtn;

            // If next component in the parent window is not in
            // the button group, current active button will be
            // base, otherwise, the base will be first or last
            // button in the button group
            Component focusBase = getFocusTransferBaseComponent(next);
            if (focusBase != null){
                if (next) {
                    KeyboardFocusManager.
                        getCurrentKeyboardFocusManager().focusNextComponent(focusBase);
                } else {
                    KeyboardFocusManager.
                        getCurrentKeyboardFocusManager().focusPreviousComponent(focusBase);
                }
            }
        }
    }

    /**
     * Radiobutton KeyListener
     */
    private class KeyHandler implements KeyListener {

        // This listener checks if the key event is a KeyEvent.VK_TAB
        // or shift + KeyEvent.VK_TAB event on a radio button, consume the event
        // if so and move the focus to next/previous component
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_TAB) {
                 // Get the source of the event.
                Object eventSrc = e.getSource();

                // Check whether the source is a visible and enabled JRadioButton
                if (isValidRadioButtonObj(eventSrc)) {
                    e.consume();
                    ButtonGroupInfo btnGroupInfo = new ButtonGroupInfo((JRadioButton)eventSrc);
                    btnGroupInfo.jumpToNextComponent(!e.isShiftDown());
                }
            }
        }

        public void keyReleased(KeyEvent e) {
        }

        public void keyTyped(KeyEvent e) {
        }
    }
D
duke 已提交
608
}