Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

java - ending the ball's path

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...