有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

这是一个JButton,当单击它时需要有动作监听器,它将调用drawPiece方法。当前错误是connect find symbol变量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) 个答案

  1. # 1 楼答案

    column3.drawPiece(g);
    

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

    column3.repaint();
    

    调用RepaintManager来计划重新绘制。最终paintComponent()方法将被相应的Graphics对象调用