Reputation: 23
I am creating a game that allows one player to move around a board with user input by the arrow keys on the keyboard. The objective is to collect the gems on the board and avoid the monsters that move around randomly. I am having issues just getting my board to be drawn in the GUI. Each "tile", "item", and "character" are drawn with simple, generic draw methods like drawRect and drawOval. However, I don't know how to get these to be drawn in an array of panels.
Is my issue in the constructor or the paint method? Help!
public class LevelPanel extends JPanel {
private static Player player;
private Level level;
private JLabel gemLabel, scoreLabel, healthLabel;
private JPanel[][] squares;
private JPanel boardPanel;
private JOptionPane optionPane = new JOptionPane();
public LevelPanel() {
this.player = player;
setPreferredSize(new Dimension(300,300));
setBackground(Color.white);
setLayout(new GridLayout(10,10));
gemLabel = new JLabel("Gems Left: 0");
scoreLabel = new JLabel("Score: 0");
healthLabel = new JLabel("Health: 100");
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
squares[i][j] = new JPanel();
squares[i][j].setBackground(Color.white);
boardPanel.add(squares[i][j]);
}
}
add(gemLabel);
add(scoreLabel);
add(healthLabel);
add(boardPanel);
}
public void paint(Graphics g) {
super.paint(g);
level.draw(g);
}
private class KeyHandler extends KeyAdapter {
public void keyPressed (KeyEvent e) {
int keyCode = e.getKeyCode();
switch(keyCode) {
case KeyEvent.VK_UP:
player.move(-1,0);
break;
case KeyEvent.VK_DOWN:
player.move(1,0);
break;
case KeyEvent.VK_LEFT:
player.move(0,-1);
break;
case KeyEvent.VK_RIGHT:
player.move(0,1);
break;
}
gemLabel.setText("Gems Left: " + level.getNumGems());
scoreLabel.setText("Score: " + player.getScore());
healthLabel.setText("Health: " + player.getHealth());
repaint();
}
}
Upvotes: 2
Views: 1009
Reputation: 159844
You never instantiate squares
or boardPanel
:
private JPanel[][] squares = new JPanel[10][10];
private JPanel boardPanel = new JPanel();
Also level
in class LevelPanel
does not appear to be instantiated. In this class also, you are assigning an undefined reference to player
public LevelPanel() {
this.player = player;
You could pass in a Player
reference:
public LevelPanel(Player player) {
this.player = player;
Upvotes: 1
Reputation: 11298
Instead of having JPanel[]
you can use JButton[]
without any name with background color.
Here is an game example which is similar to your 2D Array need Shuffling JButton in CardLayout
Upvotes: 0