Reputation: 13
I am a beginner in java and appologies for any wrong terminology.
I am trying to create a simple 2D game just to learn more about how java works.
For now what I would want to know is how I would go about using a 2D array and drawing it. And maybe add a simple icon(player) you can move around with the arrowkeys.
Currently I have the following classes Keybarricade:
public class Keybarricade{
public static void main(String[] args)
{
JFrame obj = new JFrame();
Playingfield playingfield = new Playingfield();
obj.setBounds(0, 0, 900, 900);
obj.setBackground(Color.GRAY);
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.add(playingfield);
}
and playingfield:
public class Playingfield extends JPanel{
private ImageIcon playerIcon;
private int [][] playinggrid = new int[10][10];
private int [] playerX = new int[10];
private int [] playerY = new int[10];
public Playingfield()
{
}
public void paint (Graphics g)
{
//draw border for playingfield
g.setColor(Color.white);
g.drawRect(10, 10, 876, 646);
//draw background for the playingfield
g.setColor(Color.LIGHT_GRAY);
g.fillRect(11, 11, 875, 645);
//draw player imageicon
playerIcon = new ImageIcon("src/images/playerIcon.png");
playerIcon.paintIcon(this, g, playerX[1], playerY[1] );
}
this gives the following window:window I have right now
What I would want is to use the 2D array to draw/paint a 10x10 grid, something like this: window I would like
But sadly I couldnt find a way to do this or I did but didnt understand it. If someone could point me in the right dirrection that would be awsome!
thanks in advance.
Upvotes: 1
Views: 3368
Reputation: 1750
You could use something like this in your paint function:
int boxWidth = 30;
int boxHeight = 30;
for (int currentX = 0;
currentX < playinggrid.length * boxWidth;
currentX += boxWidth) {
for (int currentY = 0;
currentY < playinggrid[0].length * boxHeight;
currentY += boxHeight) {
g.drawRect(currentX, currentY, boxWidth, boxHeight);
}
}
If you want to draw the icon in the middle of a cell you can do the following inside the two for loops:
g.drawImage(playerIcon.getImage(),
currentX + boxWidth/2 - playerIcon.getIconWidth()/2,
currentY + boxHeight/2 - playerIcon.getIconHeight()/2,
null);
BTW: I think it's better to override paintComponent instead of paint, see this post
Upvotes: 1