Home > Java > javaTutorial > How to Confine Star Movement Within a JFrame Using the move() Method?

How to Confine Star Movement Within a JFrame Using the move() Method?

Barbara Streisand
Release: 2024-11-30 21:24:14
Original
350 people have browsed it

How to Confine Star Movement Within a JFrame Using the move() Method?

The move() method in the Star class is responsible for moving the star. However, it only checks the WIDTH and HEIGHT constants, which are defined for the size of the JPanel that the Star is drawn on. This means that if the Star moves outside of the JPanel, it will continue to move in the same direction and will not be relocated within the JPanel.

To fix this, the move() method needs to be updated to check the width and height of the JFrame that the JPanel is inside of. This way, the Star will be relocated within the JFrame if it moves outside of the JPanel. Here is the updated code for the 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

The above is the detailed content of How to Confine Star Movement Within a JFrame Using the move() Method?. 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