Title: More Demos
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

More Demos

Moving Scaling Demo

For this demo you can place your mouse on either the square or the circle and drag it to some other location.

Also note that if your mouse is on one of the objects(square or circle), you can move the wheel on your mouse to increase or decrease the size of the object.

The dragging uses concepts we have covered in cps261 before. See if you can figure it out.

The resizing uses some new concepts:

MouseWheelListener interface which requires the method mouseWheelMoved.

The passed in MouseWheelEvent contains methods that allow you to determine the amount of wheel movement. See the ScaleHandler class where we have logic dealing with this interface.

MovingScalingDemo.java


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;


class MovingScalingDemoJPanel extends JPanel {

    private AdjustableRectangle adjustableRectangle;
    private AdjustableEllipse adjustableEllipse;

    public MovingScalingDemoJPanel() {

    	 MovingAdapter ma = new MovingAdapter();

        addMouseMotionListener(ma);
        addMouseListener(ma);
        addMouseWheelListener(new ScaleHandler());

        adjustableRectangle = new AdjustableRectangle(50, 50, 50, 50);
        adjustableEllipse = new AdjustableEllipse(150, 70, 80, 80);
    }


    private void doDrawing(Graphics g) {

        Graphics2D g2d = (Graphics2D) g;

        Font font = new Font("Serif", Font.BOLD, 40);
        g2d.setFont(font);

        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                        RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        g2d.setPaint(new Color(0, 0, 200));
        g2d.fill(adjustableRectangle);
        g2d.setPaint(new Color(0, 200, 0));
        g2d.fill(adjustableEllipse);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        doDrawing(g);
    }

    class AdjustableEllipse extends Ellipse2D.Float {

        public AdjustableEllipse(float x, float y, float width, float height) {

            setFrame(x, y, width, height);
        }

        public boolean isHit(float x, float y) {

            return getBounds2D().contains(x, y);
        }

        public void addX(float x) {

            this.x += x;
        }

        public void addY(float y) {

            this.y += y;
        }

        public void addWidth(float w) {

            this.width += w;
        }

        public void addHeight(float h) {

            this.height += h;
        }
    }

    class AdjustableRectangle extends Rectangle2D.Float {

        public AdjustableRectangle(float x, float y, float width, float height) {

            setRect(x, y, width, height);
        }

        public boolean isHit(float x, float y) {

            return getBounds2D().contains(x, y);
        }

        public void addX(float x) {

            this.x += x;
        }

        public void addY(float y) {

            this.y += y;
        }

        public void addWidth(float w) {

            this.width += w;
        }

        public void addHeight(float h) {

            this.height += h;
        }
    }

    class MovingAdapter extends MouseAdapter {

        private int x_current;
        private int y_current;

        @Override
        public void mousePressed(MouseEvent e) {

            x_current = e.getX();
            y_current = e.getY();
        }

        @Override
        public void mouseDragged(MouseEvent e) {

            doMove(e);
        }

        private void doMove(MouseEvent e) {

            int dx = e.getX() - x_current;
            int dy = e.getY() - y_current;

            if (adjustableRectangle.isHit(x_current, y_current)) {

                adjustableRectangle.addX(dx);
                adjustableRectangle.addY(dy);
                repaint();
            }

            if (adjustableEllipse.isHit(x_current, y_current)) {

                adjustableEllipse.addX(dx);
                adjustableEllipse.addY(dy);
                repaint();
            }

            x_current += dx;
            y_current += dy;
        }
    }

    class ScaleHandler implements MouseWheelListener {

        @Override
        public void mouseWheelMoved(MouseWheelEvent e) {

            doScale(e);
        }

        private void doScale(MouseWheelEvent e) {

            int x = e.getX();
            int y = e.getY();

            if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) {

                if (adjustableRectangle.isHit(x, y)) {

                    float amount =  e.getWheelRotation() * 5f;
                    adjustableRectangle.addWidth(amount);
                    adjustableRectangle.addHeight(amount);
                    repaint();
                }

                if (adjustableEllipse.isHit(x, y)) {

                    float amount =  e.getWheelRotation() * 5f;
                    adjustableEllipse.addWidth(amount);
                    adjustableEllipse.addHeight(amount);
                    repaint();
                }
            }
        }
    }
}

public class MovingScalingDemo extends JFrame {

    public MovingScalingDemo() {

    	add(new MovingScalingDemoJPanel());

        setTitle("MovingScalingDemo");
        setSize(300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {

    	MovingScalingDemo msd = new MovingScalingDemo();
    }
}



Nothing particularly new here that hasn't been covered. See if you can figure it out.

BubblesDemo.java


import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

class BubblesDemoJPanel extends JPanel
implements ActionListener {

    private final Color colors[] = {
            Color.blue, Color.cyan, Color.green,
            Color.magenta, Color.orange, Color.pink,
            Color.red, Color.yellow, Color.lightGray, Color.white
    };

    private Ellipse2D.Float[] ellipses;
    private double esize[];
    private float estroke[];
    private double maxSize = 0;
    private final int NUMBER_OF_ELLIPSES = 25;
    private final int DELAY = 30;
    private final int INITIAL_DELAY = 150;
    private Timer timer;

    public BubblesDemoJPanel() {

        // Initialize the Surface
        setBackground(Color.black);
        ellipses = new Ellipse2D.Float[NUMBER_OF_ELLIPSES];
        esize = new double[ellipses.length];
        estroke = new float[ellipses.length];

        // initialize the ellipses
        int w = 350;
        int h = 250;

        maxSize = w / 10;

        for (int i = 0; i < ellipses.length; i++) {

            ellipses[i] = new Ellipse2D.Float();
            createRandomEllipse(i, maxSize * Math.random(), w, h);
        }

        // start timer
        timer = new Timer(DELAY, this);
        timer.setInitialDelay(INITIAL_DELAY);
        timer.start();
    }
    private void createRandomEllipse(int i, double size, int w, int h) {

        esize[i] = size;
        estroke[i] = 1.0f;
        double x = Math.random() * (w - (maxSize / 2));
        double y = Math.random() * (h - (maxSize / 2));
        ellipses[i].setFrame(x, y, size, size);
    }

    private void updateEllipses(int w, int h) {

        for (int i = 0; i < ellipses.length; i++) {

            estroke[i] += 0.025f;
            esize[i]++;

            if (esize[i] > maxSize) {

                createRandomEllipse(i, 1, w, h);
            } else {

                ellipses[i].setFrame(ellipses[i].getX(), ellipses[i].getY(),
                        esize[i], esize[i]);
            }
        }
    }

    private void drawEllipses(Graphics2D g2d) {

        for (int i = 0; i < ellipses.length; i++) {

            g2d.setColor(colors[i % colors.length]);
            g2d.setStroke(new BasicStroke(estroke[i]));
            g2d.draw(ellipses[i]);
        }
    }

    private void doDrawing(Graphics g) {

        Graphics2D g2d = (Graphics2D) g.create();

        RenderingHints rh
        = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        rh.put(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);

        g2d.setRenderingHints(rh);

        Dimension size = getSize();
        updateEllipses(size.width, size.height);
        drawEllipses(g2d);

        g2d.dispose();
    }

    @Override
    public void paintComponent(Graphics g) {

        super.paintComponent(g);
        doDrawing(g);
    }


    @Override
    public void actionPerformed(ActionEvent e) {

        repaint();
    }
}

public class BubblesDemo extends JFrame {

    public BubblesDemo() {
        add(new BubblesDemoJPanel());

        setTitle("BubblesDemo");
        setSize(350, 250);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }


    public static void main(String[] args) {

        BubblesDemo bd = new BubblesDemo();
    }
}




Puffer Demo

Again nothing new. See if you can figure it out

PuffDemo.java



import java.awt.AlphaComposite;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;


class PuffDemoJPanel extends JPanel
       implements ActionListener {

   private Timer timer;
   private int fontSize = 1;
   private float alpha = 1;
   private final int DELAY = 15;
   private final int INITIAL_DELAY = 200;

   public PuffDemoJPanel() {

       timer = new Timer(DELAY, this);
       timer.setInitialDelay(INITIAL_DELAY);
       timer.start();
   }


   private void doDrawing(Graphics g) {

       Graphics2D g2d = (Graphics2D) g.create();

       RenderingHints rh =
           new RenderingHints(RenderingHints.KEY_ANTIALIASING,
           RenderingHints.VALUE_ANTIALIAS_ON);

       rh.put(RenderingHints.KEY_RENDERING,
              RenderingHints.VALUE_RENDER_QUALITY);

       g2d.setRenderingHints(rh);

       Font font = new Font("Dialog", Font.PLAIN, fontSize);
       g2d.setFont(font);

       FontMetrics fm = g2d.getFontMetrics();
       String s = "Puffer";
       Dimension size = getSize();

       int w = (int) size.getWidth();
       int h = (int) size.getHeight();

       int stringWidth = fm.stringWidth(s);
       AlphaComposite ac = AlphaComposite.getInstance(
               AlphaComposite.SRC_OVER, alpha);
       g2d.setComposite(ac);

       g2d.drawString(s, (w - stringWidth) / 2, h / 2);

       g2d.dispose();
   }

   @Override
   public void paintComponent(Graphics g) {

       super.paintComponent(g);
       doDrawing(g);
   }

   private void puffUpdateStep() {

       fontSize += 1;

       if (fontSize > 40)
           alpha -= 0.01;

       if (alpha <= 0.01)
       {
           //timer.stop();  // If we want to stop after one Puff
           fontSize =1;
           alpha =1;
       }
   }

   @Override
   public void actionPerformed(ActionEvent e) {

       puffUpdateStep();
       repaint();
   }
}

public class PuffDemo extends JFrame {

   public PuffDemo() {
       setTitle("PuffDemo");

       add(new PuffDemoJPanel());

       setSize(400, 300);
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       setLocationRelativeTo(null);   // Centers window location
       setVisible(true);
   }


   public static void main(String[] args) {

       PuffDemo pd = new PuffDemo();
   }
}






ResizingDemo

Again nothing particularly new. See if you can figure this out.

package demos_more;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

class ResizingDemoJPanel extends JPanel {

    private Point2D[] points;
    private final int SIZE = 8;
    private int pos;

    public ResizingDemoJPanel() {

          addMouseListener(new ShapeTestAdapter());
          addMouseMotionListener(new ShapeTestAdapter());
          pos = -1;

          points = new Point2D[2];
          points[0] = new Point2D.Double(50, 50);
          points[1] = new Point2D.Double(150, 100);
    }


    private void doDrawing(Graphics g) {

        Graphics2D g2 = (Graphics2D) g;

        for (Point2D point : points) {
            double x = point.getX() - SIZE / 2;
            double y = point.getY() - SIZE / 2;
            g2.fill(new Rectangle2D.Double(x, y, SIZE, SIZE));
        }

        Rectangle2D r = new Rectangle2D.Double();
        r.setFrameFromDiagonal(points[0], points[1]);

        g2.draw(r);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        doDrawing(g);
    }

    private class ShapeTestAdapter extends MouseAdapter {

        @Override
        public void mousePressed(MouseEvent event) {

            Point p = event.getPoint();

            for (int i = 0; i < points.length; i++) {

                double x = points[i].getX() - SIZE / 2;
                double y = points[i].getY() - SIZE / 2;

                Rectangle2D r = new Rectangle2D.Double(x, y, SIZE, SIZE);

                if (r.contains(p)) {

                    pos = i;
                    return;
                }
            }
        }

        @Override
        public void mouseReleased(MouseEvent event) {

            pos = -1;
        }

        @Override
        public void mouseDragged(MouseEvent event) {

            if (pos == -1) {
                return;
            }

            points[pos] = event.getPoint();
            repaint();
        }
    }
}

public class ResizingDemo extends JFrame {

    public ResizingDemo()  {

          add(new ResizingDemoJPanel());

          setTitle("ResizingDemo");
          setSize(300, 300);
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setLocationRelativeTo(null);
          setVisible(true);
    }


    public static void main(String[] args) {

        ResizingDemo rd = new ResizingDemo();
    }
}



Last Updated: June 18, 2015 10:01 PM