简体   繁体   中英

Cannot find graphics variable when method is called?

This is a JButton that needs to have action listener when clicked will call drawPiece method. Currently error is connect find symbol variable g.

JButton column3 = new JButton();
    column3.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        x = 2;
        //.drawPiece(g);
        column3.drawPiece(g);


      }
    });

This is the drawPiece method and where the graphics are initialized.

public void paintComponent(Graphics pen) {
    super.paintComponent(pen);
    drawBoard(pen);
    drawPiece(pen);
    boardarray();
  }

  public void drawPiece(Graphics g) {
    x = x;
    y=0;// fixed at 0
    int turn=0; 
    boolean p1Win = false;
    boolean p2Win = false;
    //while(p1Win==false && p2Win==false) {
      checkPiece();
      g.setColor(Color.RED);
      g.fillOval(10+x*110,10+y*110,100,100);
      //checkWin();     
      p1Win = true;
  }

Any suggestions are appreciated.

column3.drawPiece(g);

You should never invoke a painting method from a listener directly. If you want to repaint the component then you tell the component to repaint itself:

column3.repaint();

The makes a call to the RepaintManager to schedule the repainting. Ultimately the paintComponent() method will be invoked with the appropriate Graphics object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM