import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ChessRunner implements MouseListener
{
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 600;
private static int colFrom;
private static int rowFrom;
private static int colTo;
private static int rowTo;
public static void main(String[] args)
{
JFrame frame = new JFrame();
ChessViewer theImgTester = new ChessViewer();
frame.add(theImgTester);
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent event){
}
/**
* Gets initial mouse click position, translates it to row and column
*/
public void mousePressed(MouseEvent event){
colFrom = (int)((event.getX()/45));
rowFrom = (int)(9-(event.getY()/45));
}
/**
* Set the new row and column after mouse is released.
*/
public void mouseReleased(MouseEvent event){
colTo = (int)(event.getX()/45);
rowTo = (int)(9-event.getY()/45);
theImgTester.getBoard().move(rowFrom,colFrom,rowTo,colTo);
theImgTester.getBoard().print();
theImgTester.repaint();
frame.repaint();
}
});
}
}
这是一款有棋子的棋盘游戏。
在这里,我希望在完成拖动后重新绘制图形。 我在控制台中有一个非图形版本(基于文本),显示移动的部分。 我已经将repaint()方法添加到JFrame和Component(theImgTester)。
ChessViewer theImgTester是一个包含棋子和棋盘的组件。 我试图让repaint()方法工作。 我需要更改ChessViewer中的任何内容吗?我很确定问题在于这个文件。 请给我一些提示!
编辑:ChessViewer.java
import java.awt.Graphics2D;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JLabel;
public class ChessViewer extends JComponent{
private JLabel turn = new JLabel();
private ChessBoard board;
/**
* Constructor for the chess viewer.
* Constructs a new chessboard.
*/
public ChessViewer() {
board= new ChessBoard();
board.start();
}
/**
* Returns the chessboard
* @return
*/
public ChessBoard getBoard(){
return board;
}
/**
* Method to print the chessboard and pieces on the chessboard.
*/
public void paint(Graphics h) {
Graphics2D g = (Graphics2D)h;
board.paint(g);
for(int i = 0; i < board.getSizeB(); i++){
for(int j = 0; j<board.getSizeB(); j++){
board.getBoard()[j][i].paint(h);
}
}
}
}