Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a small panel where i am making a ball to move by just varying it's x co-ordinate. I want the ball move back when it encounters the end of frame.The width of my frame is 300 (by fr.setSize(300,300)). Now I programmed the animation like :

// when x == 300
// stop the timer

But x=300 seems to be greater than it's width which is 300 ! How is this possible. **The ball moves out of the 300 x 300 frame and becomes invisible. Why is this happening ?

These are the screen shots of what happens eventually.

Ball is moving...

Ball is no where..!!

Upon Enlarging,ball is there

First snapshot is that of the moving ball,second shows that ball has disappeared,third shows on enlarging that ball is there.

Why this happens.? How can i set the frame's end point as the ball's end point?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
220 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to consider the viewable size of your component. It won't necessarily be the same as the size you requested.

You can use the getSize method to determine the actual size of your component, but you also need to call getInsets to find out if any space has been reserved for use by borders. This will give you the real, drawable area:

public void paint(Graphics g) {
    Dimension size = getSize();
    Insets insets = getInsets();
    int available = size.width - insets.left - insets.right;
    // Draw stuff. Remember to offset by insets.left and insets.top!
    ...
}

Also remember that Graphics routines like fillOval draw down and to the right of the coodinate you specify, so you need to think about what the ball coordinate means. Is it the center of the ball, or the left or right side? You may need to subtract the width of the ball when calculating whether it has reached the side of the drawable area or not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...