Home > Java > javaTutorial > How to Keep Animated Ornaments Within a Java Christmas Tree\'s Boundaries?

How to Keep Animated Ornaments Within a Java Christmas Tree\'s Boundaries?

Patricia Arquette
Release: 2024-12-18 01:24:10
Original
795 people have browsed it

How to Keep Animated Ornaments Within a Java Christmas Tree's Boundaries?

Passing current Date

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template