Advertisement
CSenshi

Evil Circle

Nov 25th, 2020
819
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.45 KB | None | 0 0
  1. package samples;
  2.  
  3. /*
  4.  * File: GraphicsHierarchy.java
  5.  * ----------------------------
  6.  * This program is a stub for the GraphicsHierarchy problem, which
  7.  * draws a partial diagram of the acm.graphics hierarchy.
  8.  */
  9. import acm.graphics.GOval;
  10. import acm.program.*;
  11. import acm.util.RandomGenerator;
  12.  
  13. import java.awt.*;
  14. import java.awt.event.MouseEvent;
  15.  
  16. public class GraphicsProgramSample extends GraphicsProgram {
  17.  
  18.     private final static int CIRCLE_D = 40;
  19.     private GOval myBall = null;
  20.     private RandomGenerator rgen = RandomGenerator.getInstance();
  21.  
  22.     public void init() {
  23.         addMouseListeners();
  24.         drawBall();
  25.     }
  26.  
  27.     // draws the main ball
  28.     private void drawBall() {
  29.         int ballX = getWidth() / 2 - CIRCLE_D / 2;
  30.         int ballY = getHeight() / 2 - CIRCLE_D / 2;
  31.         myBall = new GOval(ballX, ballY, CIRCLE_D, CIRCLE_D);
  32.         myBall.setFilled(true);
  33.         myBall.setColor(Color.BLACK);
  34.         add(myBall);
  35.     }
  36.  
  37.     // 1. Color on click
  38.     public void mouseClicked(MouseEvent e) {
  39.         Color ballsNewColor = rgen.nextColor();
  40.         myBall.setColor(ballsNewColor);
  41.     }
  42.  
  43.     // 2. change size on move
  44.     public void mouseDragged(MouseEvent e) {
  45.         // 2.1 change size
  46.         int dx = (int) (e.getX() - (getWidth() / 2));
  47.         int dy = (int) (e.getY() - (getHeight() / 2));
  48.         int r = (int) Math.sqrt(dx * dx + dy * dy);
  49.         myBall.setSize(2 * r, 2 * r);
  50.  
  51.         // 2.2 change location
  52.         int ballX = getWidth() / 2 - r;
  53.         int ballY = getHeight() / 2 - r;
  54.         myBall.setLocation(ballX, ballY);
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement