2

我正在创建一个游戏,允许一个玩家通过键盘上的箭头键在用户输入的情况下在棋盘上移动。目标是收集板上的宝石并避免随机移动的怪物。我在让我的板子在 GUI 中绘制时遇到了问题。每个“tile”、“item”和“character”都是使用简单的通用绘制方法绘制的,例如 drawRect 和 drawOval。但是,我不知道如何将这些绘制在一组面板中。

我的问题是在构造函数中还是在绘制方法中?帮助!

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();
    }
}
4

2 回答 2

1

你永远不会实例化squaresor boardPanel

private JPanel[][] squares = new JPanel[10][10];
private JPanel boardPanel = new JPanel();

同样level在课堂LevelPanel上似乎没有被实例化。同样在这个类中,您正在分配一个未定义的引用player

public LevelPanel() {
    this.player = player;

你可以传入一个Player参考:

public LevelPanel(Player player) {
    this.player = player;
于 2012-11-24T19:33:11.663 回答
0

而不是让JPanel[]你可以使用JButton[]没有任何名称的背景颜色。

这是一个游戏示例,类似于您的 2D 数组需要 在 CardLayout 中洗牌 JButton

于 2012-11-24T19:24:17.383 回答