I've been trying to create a ball in Eclipse. I tried to find out what to do in this post and I can't seem to figure out what to put in my Ball class. Any suggestions?
Asked
Active
Viewed 2,817 times
3 Answers
1
Here is a simple java class from which you can create a ball object:
public class Ball {
private int x, y, r;
private Color c = Color.YELLOW;
public Ball (int x, int y, int r)
{
this.x = x;
this.y = y;
this.r = r;
}
// draws the ball
public void draw (Graphics g)
{
g.setColor(c);
g.fillOval(x-r, y-r, 2*r, 2*r);
}
}

Marcin S.
- 11,161
- 6
- 50
- 63
-
Thanks! I've got a few problems, though: Color.YELLOW; gets an error, saying "Type mismatch: cannot convert from int to Color" and g.setColor gets an error, saying "The method setColor(Color) in the type Graphics is not applicable for the arguments (Color)" the Color.YELLOW wants me to change c to an int, and the setColor relies on the variable c. Should I change c to an int? – Jordan Oct 18 '12 at 01:42
1
try this in case you decide to change your mind.
public class MainActivity extends Activity {
private int c = Color.YELLOW;
private Canvas g;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
draw();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// draws the ball
public void draw ()
{
Display display = getWindowManager().getDefaultDisplay();
int width = display.getHeight();
int height = display.getWidth();
Bitmap bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
g = new Canvas(bitmap);
g.drawColor(c);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
g.drawCircle(50, 10, 25, paint); //Put your values
// In order to display this image, we need to create a new ImageView that we can display.
ImageView imageView = new ImageView(this);
// Set this ImageView's bitmap to ours
imageView.setImageBitmap(bitmap);
// Create a simple layout and add imageview to it.
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
layout.addView(imageView, params);
layout.setBackgroundColor(Color.BLACK);
// Show layout in activity.
setContentView(layout);
}
}

Viktor Tango
- 453
- 9
- 19
0
The only way i know of rendering a sphere is in openGl .. check it out here
For 2D rendering, you may perhaps see this tut .. its quiet simple .. Link

Community
- 1
- 1

Viktor Tango
- 453
- 9
- 19
-
Thanks, but I'm using the code that Marcin gave me. I have some errors, though. Do you know what I should do? – Jordan Oct 18 '12 at 03:36
-
-