我正在研究Java中的跳棋游戏,并且似乎无法在棋盘上绘制棋子

时间:2016-04-13 16:54:20

标签: java jframe

BoardView.java

package checkers.views;
import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class BoardView extends JPanel{
    public void paint(Graphics g){
        g.setColor(Color.DARK_GRAY);
        g.fillRect(100, 100, 400, 400); 
        for(int i = 100; i <= 400; i+=100){ 
            for(int j = 100; j <= 400; j+=100){ 
                g.setColor(Color.LIGHT_GRAY);
                g.fillRect(i, j, 50, 50); 
                } 
            }
        for(int i = 150; i <= 450; i+=100){ 
            for(int j = 150; j <= 450; j+=100){ 
                g.setColor(Color.LIGHT_GRAY);
                g.fillRect(i, j, 50, 50); 
                } 
            }

        } 
}

PiecesView.java

import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import checkers.models.*;
import checkers.utilities.*;
import checkers.business_logic.*;


public class PieceView extends JPanel{
    public void paint(Graphics g, Board checkersBoard ){
        for (int row = 0; row < 8; row++) {
            for (int col = 0; col < 8; col++) {
               int color = checkersBoard.piecesGrid[row][col].getColor();
               if(color == ConstantsHolder.RED){
                  g.setColor(Color.RED);
                  g.fillOval(col, row, 60, 60);
               }
               else if(color == ConstantsHolder.BLACK){
                   g.setColor(Color.BLACK);
                   g.fillOval(col, row, 60, 60);
               }

            }

        }
    }
}

BoardViewDrawer.java

import checkers.utilities.*;
import checkers.models.*;
import checkers.views.*;
import checkers.business_logic.*;

public class BoardViewDrawer {

  public static void drawBoard(){

  JFrame Board = new JFrame(); 
    Board.setSize(600,600); 
    Board.getContentPane().add(new BoardView()); 
    Board.setLocationRelativeTo(null); 
    Board.setBackground(Color.BLACK); 
    Board.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    Board.setVisible(true);
    Board.setTitle("Checkers Palooza");
    Board.setLayout(new GridLayout(8,8));
    Board.getContentPane().add(new PieceView()); 

}

我认为这一切都有道理,但我不确定我在这里做错了什么。我正在使用我的电路板的逻辑来尝试根据它设置各个部分。如果有人有任何见解或只是看到我在做什么,那将是非常感谢愚蠢的帮助。

1 个答案:

答案 0 :(得分:1)

paint中的PieceView方法永远不会被调用,因为它没有正确覆盖paint方法。这需要签名:

public void paint(Graphics g);

BoardView类一样。

如果你想在paint方法中使用checkersBoard,你可以将它传递给构造函数并在绘画时保存它:

public class PieceView extends JPanel{

    private Board checkersBoard;

    public PieceView(Board checkersBoard) {
        this.checkersBoard = checkersBoard;
    }

    @Override // makes sure you're overriding
    public void paint(Graphics g){
        // paint code here
    }

    ...
}

您可以checkersBoard方法使用paint