Home >Java >javaTutorial >How to Keep Animated Ornaments Within a Java Christmas Tree\'s Boundaries?
The given code snippet is an implementation of a Java program that creates a Christmas tree with randomly generated ornaments. However, the program has an issue where ornaments that move outside the bounds of the tree are not properly relocated within the bounds. To fix this issue, the move() method in the Star class needs to be modified to check for reaching the bounds of the container and reverse direction accordingly.
Here's the corrected move() method:
public void move() { if (location.x < 0 || location.x > frame.getContentPane().getWidth() - 20) { xIncr = -xIncr; } if (location.y < 0 || location.y > frame.getContentPane().getHeight() - 20) { yIncr = -yIncr; } translate(xIncr, yIncr); location.setLocation(location.x + xIncr, location.y + yIncr); }
In this corrected version, the move() method checks for reaching the left, right, top, and bottom bounds of the container (frame.getContentPane()) within the if conditions. If any of these bounds are reached, the corresponding xIncr or yIncr is reversed, causing the ornament to change direction and move back within the bounds.
The above is the detailed content of How to Keep Animated Ornaments Within a Java Christmas Tree\'s Boundaries?. For more information, please follow other related articles on the PHP Chinese website!