调用方法时找不到图形变量?

时间:2015-12-17 21:39:16

标签: java graphics actionlistener

这是一个JButton,点击时需要有动作监听器才会调用drawPiece方法。目前错误是连接查找符号变量g。

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


      }
    });

这是drawPiece方法,初始化图形。

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;
  }

任何建议都表示赞赏。

1 个答案:

答案 0 :(得分:0)

column3.drawPiece(g);

您永远不应该直接从侦听器调用绘制方法。如果要重新绘制组件,则告诉组件重新绘制自己:

column3.repaint();

调用RepaintManager来安排重新绘制。最终,将使用相应的paintComponent()对象调用Graphics方法。

相关问题