Need help painting to a Canvas
Im having a problem painting something that i feel should work. Since i've never really done something like this before I'm not sure whats going wrong. Here's my code, i have 2 classes, 1 named Board, the other named Boulder:
Code:
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import javax.swing.*;
public class Board extends Canvas implements Runnable
{
static JFrame f;
int ballNum = 0;
Graphics2D g;
Boulder b = new Boulder();
int flag = 1;
public static void main(String[] args)
{
f = new JFrame("DODGE!!");
f.setSize(800,600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
Board canvas = new Board();
f.add(canvas);
f.setVisible(true);
}
public void run()
{
if(flag == 1)
{
setCoordinates();
Draw(g);
flag = 2;
}
}
public void Draw(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.fill(b.balls.get(ballNum));
}
public void setCoordinates()
{
b.setX(1+(int)(Math.random()*800));
b.setY(400);
b.setHeight(10+(int)(Math.random()*35));
b.setWidth(b.getHeight());
b.makeBoulder();
}
}
import java.awt.*;
import java.awt.geom.Ellipse2D;
import javax.swing.*;
import java.util.ArrayList;
public class Boulder
{
int x;
int y;
int w;
int h;
ArrayList<Ellipse2D.Double> balls = new ArrayList<Ellipse2D.Double>();
public void makeBoulder()
{
Ellipse2D.Double ball = new Ellipse2D.Double();
ball.x = getX();
ball.y = getY();
ball.height = getHeight();
ball.width = getWidth();
balls.add(ball);
}
//sets x position of boulder
public void setX(int Xpos)
{
x = Xpos;
}
//sets y pos
public void setY(int Ypos)
{
y = Ypos;
}
//sets height of boulder
public void setHeight(int height)
{
h = height;
}
//sets width
public void setWidth(int width)
{
w = width;
}
//gets x position
public int getX()
{
return x;
}
//gets y position
public int getY()
{
return y;
}
//gets height
public int getHeight()
{
return h;
}
//gets width
public int getWidth()
{
return w;
}
}
I dont get any compile errors. The only thing is that it doesnt paint the object. Any ideas how to fix this? (Sorry for the somewhat long code).
Re: Need help painting to a Canvas
Why are you mixing Swing with AWT components? Why even use AWT components at all when they've been out of date for over 10 years? You also appear to be trying to do Java graphics without having read a tutorial or API (Draw? You can't make up methods and expect them to magically work).
My suggestions:
- Use only Swing components including JFrames, JPanels, etc.
- Read some tutorials on drawing with Swing. Start here: Lesson: Performing Custom Painting
- Then try to do what you're attempting here.