我正在用java编写一个国际象棋程序,它必须在小程序中显示。我目前在填充棋子数组时遇到问题。目前这是在我的 JApplet 的 Paint() 方法中完成的,我知道这是错误的,因为 Paint 可以被多次调用。我尝试创建数组并将其填充到我的初始化方法中,但这根本不起作用。任何帮助将不胜感激。
public class DrawChessBoard extends JApplet
implements MouseListener, MouseMotionListener {
ChessPiece myPiece;
ImageIcon square;
ImageObserver observer;
ChessBoard gameBoard;
boolean isMouseDragging = false;
int size; //square dimensions
public void initialize() {
setBackground(Color.white);
Image bSquare = square.getImage();
size = bSquare.getWidth(observer);
addMouseListener(this);
addMouseMotionListener(this);
}
public void paint(Graphics h) {
Graphics2D g = (Graphics2D) h;
//System.out.println("Am I being called more than once?");
gameBoard = new ChessBoard(8);
gameBoard.start();
gameBoard.paintBoard(g);
gameBoard.paintComponent(g);
}
}
最佳答案
不要在paint方法中执行程序逻辑——句号。这在很多方面都是错误的。该代码不仅会被多次调用并且超出您的控制,而且还会使程序图形速度减慢。绘画应该在 JPanel 或其他 JComponent 的 PaintComponent 方法中完成,并且该方法应该只关注绘画。
顺便问一下,你的 init 方法在哪里?这就是大部分代码应该放在的位置。
以下是在 JPanel 上完成的国际象棋应用程序的示例:does-adding-a-jlabel-to-a-jpanel-hide-the-jpanel 。由于它位于 JPanel 上,因此可以轻松地将其放置在 JApplet 的 contentPane 中并显示在 applet 中。
关于Java 国际象棋小程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8017801/