Ruler.java 9.3 KB
Newer Older
1
/*
2
 * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
31 32 33 34 35 36 37 38 39

/*
 * This source code is provided to illustrate the usage of a given feature
 * or technique and has been deliberately simplified. Additional steps
 * required for a production-quality application, such as security checks,
 * input validation and proper error handling, might not be present in
 * this sample code.
 */

40 41 42
package transparentruler;


43
import java.awt.*;
44
import java.awt.GraphicsDevice.WindowTranslucency;
45
import static java.awt.GraphicsDevice.WindowTranslucency.*;
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Path2D.Float;
import java.lang.reflect.InvocationTargetException;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;


/**
 * This sample demonstrates shaped and translucent window feature.
 * @author Alexander Kouznetsov
 */
@SuppressWarnings("serial")
public class Ruler extends JFrame {

    private static final Color BACKGROUND = Color.RED;
    private static final Color FOREGROUND = Color.WHITE;
    private static final int OPACITY = 180;
    private static final int W = 70;
    private static final int F_HEIGHT = 400;
    private static final int F_WIDTH = (int) (F_HEIGHT * 1.618 + 0.5);

79 80 81 82
    private static boolean translucencySupported;
    private static boolean transparencySupported;

    private static boolean checkTranslucencyMode(WindowTranslucency arg) {
83 84 85
        GraphicsEnvironment ge =
                GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice gd = ge.getDefaultScreenDevice();
86
        return gd.isWindowTranslucencySupported(arg);
87
    }
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

    public Shape buildShape() {
        int h = getHeight();
        int w = getWidth();
        float a = (float) Math.hypot(h, w);
        Float path = new java.awt.geom.Path2D.Float();
        path.moveTo(0, 0);
        path.lineTo(w, 0);
        path.lineTo(0, h);
        path.closePath();
        path.moveTo(W, W);
        path.lineTo(W, h - W * (a + h) / w);
        path.lineTo(w - W * (a + w) / h, W);
        path.closePath();
        return path;
    }

105 106 107 108 109 110 111 112
    private final ComponentAdapter componentListener = new ComponentAdapter() {

        /**
         * Applies the shape to window. It is recommended to apply shape in
         * componentResized() method
         */
        @Override
        public void componentResized(ComponentEvent e) {
113 114 115 116 117

            // We do apply shape only if PERPIXEL_TRANSPARENT is supported
            if (transparencySupported) {
                setShape(buildShape());
            }
118 119
        }
    };
120

121 122 123 124 125 126
    private final Action exitAction = new AbstractAction("Exit") {

        {
            putValue(Action.MNEMONIC_KEY, KeyEvent.VK_X);
        }

127
        @Override
128 129 130 131
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    };
132

133 134 135 136 137
    private final JPopupMenu jPopupMenu = new JPopupMenu();

    {
        jPopupMenu.add(new JMenuItem(exitAction));
    }
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
    /**
     * Implements mouse-related behavior: window dragging and popup menu
     * invocation
     */
    private final MouseAdapter mouseListener = new MouseAdapter() {

        int x, y;

        @Override
        public void mousePressed(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON1) {
                x = e.getX();
                y = e.getY();
            }
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            if ((e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) {
                setLocation(e.getXOnScreen() - x, e.getYOnScreen() - y);
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                jPopupMenu.show(getContentPane(), e.getX(), e.getY());
            }
        }
    };
169

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
    /**
     * Implements keyboard navigation. Arrows move by 5 pixels, Ctrl + arrows
     * move by 50 pixels, Alt + arrows move by 1 pixel.
     * Esc exits the application.
     */
    private final KeyAdapter keyboardListener = new KeyAdapter() {

        @Override
        public void keyPressed(KeyEvent e) {
            int step = e.isControlDown() ? 50 : e.isAltDown() ? 1 : 5;
            switch (e.getKeyCode()) {
                case KeyEvent.VK_LEFT:
                    setLocation(getX() - step, getY());
                    break;
                case KeyEvent.VK_RIGHT:
                    setLocation(getX() + step, getY());
                    break;
                case KeyEvent.VK_UP:
                    setLocation(getX(), getY() - step);
                    break;
                case KeyEvent.VK_DOWN:
                    setLocation(getX(), getY() + step);
                    break;
                case KeyEvent.VK_ESCAPE:
                    exitAction.actionPerformed(null);
            }
        }
    };

    public Ruler() {
        setUndecorated(true);

        // Enables perpixel translucency
        setBackground(new Color(BACKGROUND.getRed(), BACKGROUND.getGreen(),
                BACKGROUND.getBlue(), OPACITY));

        addMouseListener(mouseListener);
        addMouseMotionListener(mouseListener);
        addComponentListener(componentListener);
        addKeyListener(keyboardListener);
        setContentPane(new JPanel() {

            @Override
            protected void paintComponent(Graphics g) {
214
                Graphics2D gg = (Graphics2D) g.create();
215 216 217
                int w = getWidth();
                int h = getHeight();
                int hh = gg.getFontMetrics().getAscent();
218 219 220 221 222 223 224 225 226 227 228 229

                // This is an approach to apply shape when PERPIXEL_TRANSPARENT
                // isn't supported
                if (!transparencySupported) {
                    gg.setBackground(new Color(0, 0, 0, 0));
                    gg.clearRect(0, 0, w, h);
                    gg.clip(buildShape());

                    gg.setBackground(Ruler.this.getBackground());
                    gg.clearRect(0, 0, w, h);
                }

230 231 232 233 234 235 236 237 238 239 240
                gg.setColor(FOREGROUND);
                for (int x = 0; x < w * (h - 8) / h - 5; x += 5) {
                    boolean hi = x % 50 == 0;
                    gg.drawLine(x + 5, 0, x + 5,
                            hi ? 20 : (x % 25 == 0 ? 13 : 8));
                    if (hi) {
                        String number = Integer.toString(x);
                        int ww = gg.getFontMetrics().stringWidth(number);
                        gg.drawString(number, x + 5 - ww / 2, 20 + hh);
                    }
                }
241

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
                gg.dispose();
            }
        });
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(F_WIDTH, F_HEIGHT);
        setLocationByPlatform(true);
    }

    /**
     * @param args the command line arguments are ignored
     */
    public static void main(String[] args) throws InterruptedException, InvocationTargetException {

        SwingUtilities.invokeAndWait(new Runnable() {

257
            @Override
258
            public void run() {
259 260 261 262 263 264 265 266 267
                translucencySupported = checkTranslucencyMode(PERPIXEL_TRANSLUCENT);
                transparencySupported = checkTranslucencyMode(PERPIXEL_TRANSPARENT);

                if (!translucencySupported) {
                    System.err.println("This application requires "
                            + "'PERPIXEL_TRANSLUCENT' translucency mode to "
                            + "be supported.");
                    System.exit(-1);
                }
268 269 270 271 272 273 274

                Ruler ruler = new Ruler();
                ruler.setVisible(true);
            }
        });
    }
}