I'm starting to teach myself Java, and it's possible my reach doth exceed my grasp. Still, that's the best way to learn, right?
I'm trying to play around with simple graphics. I've found various resources on how to draw shapes into a JFrame, and made them work, but as far as I can tell the code always needs to go inside the paint method, which gets called automatically, which means I can't figure out how to go about passing it arguments.
What I'm trying to do is write some code that can take co-ordinates as arguments, and then place a simple shape (let's go with a 10x10 pixel square) at those co-ordinates. I feel sure that must be something that's possible, but I cannot for the life of me work out how.
Code so far, incorporating help from both @resueman and @Mikle:
public class Robots {
public static void main(String[] args) {
Window window = new Window();
window.Window();
new PlayArea();
Point p = new Point(50,50);
Entity player1 = new Entity();
player1.Entity(p);
}
}
public class Window extends JFrame{
int x;
int y;
public void Window(){
Window window = new Window();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setTitle("Robots");
window.setSize(800,600);
window.getContentPane().add(new PlayArea());
window.setLocationRelativeTo(null);
window.setBackground(Color.white);
window.setVisible(true);
}
}
public class PlayArea extends JComponent{
// I keep all added and displayed entities here for easier access
public final List<Entity> entities = new ArrayList<Entity> ();
public PlayArea(){
super();
}
public void addEntity(final Entity entity){
//add new entity and repaint area
entities.add(entity);
}
@Override
protected void paintComponent (final Graphics g)
{
super.paintComponent (g);
// Painting entities
final Graphics2D g2d = (Graphics2D) g;
for (final Entity entity : entities)
{
g2d.setPaint ( Color.BLACK );
g2d.fill (getEntityShape (entity));
}
}
protected Shape getEntityShape ( final Entity entity )
{
// Simple entity shape, you can replace it with any other shape
return new Rectangle ( entity.entPos.x - 5, entity.entPos.y - 5, 10, 10 );
}
}
public class Entity extends JComponent{
protected Point entPos = null;
public void Entity(Point p){
entPos = p;
repaint();
}
@Override
public void paintComponent (Graphics g){
super.paintComponent(g);
if (entPos != null){
g.fillRect(entPos.x, entPos.y, 10,10);
}
}
}
I want to be able to create an object in the Entity class, and put it in the window at the x,y co-ordinates.
I will eventually want to be able to move Entities around, but I'll work that one out once I've figured out how to draw them in the first place!
Still not drawing anything in the window. I'm probably missing something really obvious though.