0
我有一些編程經驗,但是面向對象編程和Java是新手。我在調用不同類的類方法時遇到問題。更具體地說,我想從myDrawPanel(board.drawBoard)中的Paintcomponent調用該方法。編譯器告訴我,編譯類mypanel時,符號'board'不被識別。任何建議/信息大加讚賞:代碼如下:從PaintComponent中訪問對象方法
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 ;
}
}
}