我定义了一个继承自panel的类,重写了它的paint()方法画了一个棋盘,并载入一幅水墨画作为棋盘的背景图;又定义了两个继承自Canvas的类用来表示黑子和白子。但是在下棋过程中出现了一个现象就是我的两个表示棋子的类是继承自Canvas的,显示棋子的时候其后的矩形边界也被显示出来了,而且矩形边界和棋子圆之间的空隙的颜色是当前面板的颜色,显示在水墨画上很难看。求解释!!!!
- import java.awt.*;
- import javax.swing.JFrame;
- class testChess
- extends JFrame {
- chessPad chesspad = new chessPad();
- public testChess() {
- setSize(450, 450);
- setLayout(new BorderLayout());
- add(chesspad, BorderLayout.CENTER);
- chessPoint_black chesspoint_black = new chessPoint_black(this.chesspad);
- chessPoint_white chesspoint_white = new chessPoint_white(this.chesspad);
- chesspad.add(chesspoint_white);
- chesspad.add(chesspoint_black);
- chesspoint_white.setBounds(163, 163, 16, 16);
- chesspoint_black.setBounds(103, 103, 16, 16);
- setDefaultCloseOperation(this.EXIT_ON_CLOSE );
- setVisible(true);
- }
- public static void main(String[] args) {
- testChess testchess = new testChess();
- }
- }
- class chessPad
- extends Panel {
- Image im = this.getToolkit().getImage("3.jpg");
- public chessPad() {
- setSize(420, 420);
- setLayout(null);
- setBackground(new Color(204, 204, 204));
- }
- public void paint(Graphics g) {
- g.drawImage(im, 0, 0, this); //将图片设置为棋盘背景
- for (int i = 40; i <= 400; i = i + 20) {
- g.drawLine(40, i, 400, i);
- }
- for (int j = 40; j <= 400; j = j + 20) {
- g.drawLine(j, 40, j, 400);
- }
- g.fillOval(97, 97, 6, 6);
- g.fillOval(337, 97, 6, 6);
- g.fillOval(97, 337, 6, 6);
- g.fillOval(337, 337, 6, 6);
- g.fillOval(217, 217, 6, 6);
- }
- public void update(Graphics g) {
- paint(g);
- }
- }
- /**
- * 表示黑子的类
- */
- class chessPoint_black
- extends Canvas {
- chessPad chesspad = null;
- chessPoint_black(chessPad p) {
- setSize(20, 20);
- chesspad = p;
- }
- public void paint(Graphics g) {
- g.setColor(Color.black);
- g.fillOval(0, 0, 14, 14);
- }
- }
- /*
- * 表示白子的类
- */
- class chessPoint_white
- extends Canvas {
- chessPad chesspad = null;
- chessPoint_white(chessPad p) {
- setSize(20, 20);
- chesspad = p;
- }
- public void paint(Graphics g) {
- g.setColor(Color.white);
- g.fillOval(0, 0, 14, 14);
- }
- }
复制代码 |