Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package samples;
- /*
- * File: GraphicsHierarchy.java
- * ----------------------------
- * This program is a stub for the GraphicsHierarchy problem, which
- * draws a partial diagram of the acm.graphics hierarchy.
- */
- import acm.graphics.GOval;
- import acm.program.*;
- import acm.util.RandomGenerator;
- import java.awt.*;
- import java.awt.event.MouseEvent;
- public class GraphicsProgramSample extends GraphicsProgram {
- private final static int CIRCLE_D = 40;
- private GOval myBall = null;
- private RandomGenerator rgen = RandomGenerator.getInstance();
- public void init() {
- addMouseListeners();
- drawBall();
- }
- // draws the main ball
- private void drawBall() {
- int ballX = getWidth() / 2 - CIRCLE_D / 2;
- int ballY = getHeight() / 2 - CIRCLE_D / 2;
- myBall = new GOval(ballX, ballY, CIRCLE_D, CIRCLE_D);
- myBall.setFilled(true);
- myBall.setColor(Color.BLACK);
- add(myBall);
- }
- // 1. Color on click
- public void mouseClicked(MouseEvent e) {
- Color ballsNewColor = rgen.nextColor();
- myBall.setColor(ballsNewColor);
- }
- // 2. change size on move
- public void mouseDragged(MouseEvent e) {
- // 2.1 change size
- int dx = (int) (e.getX() - (getWidth() / 2));
- int dy = (int) (e.getY() - (getHeight() / 2));
- int r = (int) Math.sqrt(dx * dx + dy * dy);
- myBall.setSize(2 * r, 2 * r);
- // 2.2 change location
- int ballX = getWidth() / 2 - r;
- int ballY = getHeight() / 2 - r;
- myBall.setLocation(ballX, ballY);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement