我想做一个下棋的程序,在paint方法中画了游戏的棋盘,然后给窗口加了鼠标监听,根据鼠标点的位置画棋子,为什么我每画一个棋子之后,棋盘都会重新画一遍盖住了我的棋子,求大侠帮助!…
我想做一个下棋的程序,在paint方法中画了游戏的棋盘,然后给窗口加了鼠标监听,根据鼠标点的位置画棋子,为什么我每画一个棋子之后,棋盘都会重新画一遍盖住了我的棋子,求大侠帮助!代码如下:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.UIManager;
public class MainFrame extends JFrame {
int width = 40;
int height = width;
int baseWidth = 45;
int baseHeight = 80;
int i = 0;
int j = 0;
int radius = width / 2 – 3;
public MainFrame() {
setTitle(“欢迎使用五子棋”);
setSize(700, 700);
setResizable(false);
setVisible(true);
setLocation(
(Toolkit.getDefaultToolkit().getScreenSize().width – this
.getSize().width) / 2,
(Toolkit.getDefaultToolkit().getScreenSize().height – this
.getSize().height) / 2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
int tempX = 0;
int modX = 0;
int modY = 0;
int tempY = 0;
int finaX = 0;
int finaY = 0;
tempX = (x – baseWidth) / width;
modX = (x – baseWidth) % width;
if (modX > width / 2) {
finaX = tempX + 2;
} else {
finaX = tempX + 1;
}
tempY = (y – baseHeight) / height;
modY = (y – baseHeight) % height;
if (modY > height / 2) {
finaY = tempY + 3;
} else {
finaY = tempY + 2;
}
Graphics g = getGraphics();
g.setColor(Color.BLACK);
g.fillOval(finaX * width – radius, finaY * height – radius,
radius * 2, radius * 2);
paint(g);
System.out.println(finaX);
System.out.println(finaY);
}
});
}
public void paint(Graphics g) {
g.setColor(Color.DARK_GRAY.brighter());
g.fill3DRect(baseWidth – 4, baseHeight – 4, width * 15 + 8,
height * 15 + 8, true);
g.setColor(Color.DARK_GRAY.brighter().brighter());
for (i = 0; i < 15; i++) {
for (j = 0; j < 15; j++) {
g.fill3DRect(baseWidth + width * i, baseHeight + width * j, 40,
height, true);
}
}
}
public static void main(String[] args) {
new MainFrame();
}
static {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
}
}
展开