从PaintComponent

时间:2015-10-12 11:52:53

标签: java graphics

我有一些编程经验,但我不熟悉面向对象编程和Java。我在从不同的类调用类方法时遇到问题。更具体地说,我试图在myDrawPanel(board.drawBoard)中调用Paintcomponent中的方法。编译器告诉我符号' board'编译类mypanel时无法识别。任何建议/信息非常感谢:代码如下:

import javax.swing.* ;
import java.awt.* ;
import java.awt.event.* ;
import java.awt.Graphics;

public class Connect {

  public static PBoard board = new PBoard() ;

  public void main(String[] args) {

      Connect gui = new Connect() ;
      gui.go() ;
  }

  public void go() {

      JFrame frame = new JFrame() ;
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ; 

      MyDrawPanel drawPanel = new MyDrawPanel() ;

      frame.getContentPane().add(BorderLayout.CENTER, drawPanel) ;

      frame.setSize(800,800) ;
      frame.setVisible(true) ;  

      }  
    }

import java.awt.* ;
import javax.swing.* ;

public class MyDrawPanel extends JPanel {

  public  void paintComponent(Graphics g) {

  board.drawBoard(g) ;

}

import javax.swing.* ;
import java.awt.* ;
import java.awt.event.* ;   

public class PBoard {

    int startx, starty, width, height ;
    int i, j ;
    final int X_BOARD_POS = 200 ;
    final int Y_BOARD_POS = 200 ;
    final int SQUARE_SIZE = 50 ;

  public PBoard() {

  }

  public  void drawBoard(Graphics g) {

    startx = X_BOARD_POS ;
    starty = Y_BOARD_POS ; 
    width = SQUARE_SIZE ;
    height = SQUARE_SIZE ;

    for (i = 0; i<=7 ; i++){  
      starty = Y_BOARD_POS ;
      for (j = 0 ; j<= 7 ; j++){
        g.setColor(Color.gray) ;
        g.fillRect(startx,starty,width,height) ;
        g.setColor(Color.black) ;
        g.drawRect(startx,starty,width,height) ;
        starty = starty + SQUARE_SIZE ;
      }
      starty = X_BOARD_POS ;
      startx = startx + SQUARE_SIZE ;
    }
  }
}

1 个答案:

答案 0 :(得分:0)

boardConnect的静态成员。由于MyDrawPanel不是Connect的子类,因此您无法直接访问它。使用Connect.board.drawBoard(g)代替board.drawBoard(g)