为什么我在尝试调用paintComponent时遇到错误?

问题描述:

我的班级命名为UI扩展RoundButton这是如下:为什么我在尝试调用paintComponent时遇到错误?

public class RoundButton extends JButton { 

    public RoundButton(String label) { 
     super(label); 
     this.setContentAreaFilled(false); 
     Dimension size = this.getPreferredSize(); 
     size.height = size.width = Math.max(size.height, size.width); 
     this.setPreferredSize(size); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     if(!GameState.getIfComplete()) { // If the game is not complete or has just started 
      this.setBorder(null); 
      g.setColor(Color.BLACK); 
      g.fillRect(0, 0, this.getSize().width, this.getSize().height); 
      if(this.getModel().isArmed()) { 
       g.setColor(Color.RED); 
      }else { 
       g.setColor(Color.GREEN); 
      } 
      g.fillOval(0,0,this.getSize().width-1,this.getSize().height-1); 
      super.paintComponent(g); 
     }else { 
      this.setBorder(null); 
      g.setColor(Color.BLACK); 
      g.fillRect(0, 0, this.getSize().width, this.getSize().height); 
      if(this.getModel().isArmed()) { 
       g.setColor(Color.BLUE); 
      }else { 
       g.setColor(Color.BLUE); 
      } 
      g.fillOval(0,0,this.getSize().width-1,this.getSize().height-1); 
      super.paintComponent(g); 
     } 
    } 
} 

里面UI有一个名为disableAllButtons方法,该方法如下:

public void disableAllButtons() { 
    int count =0 ; 
    while(count <= buttons.length-1) { 
     buttons[count].setEnabled(false); 
     buttons[count].paintComponent(Graphics g); // GENERATES AN ERROR 
     // where buttons[count] = new RoundButton() 
     count++; 
    } 
} 

从这个方法我打电话,paintComponent我在RoundButton课上覆盖。但我得到一个错误:

')' expected 
';' expected 
not a statement 
cannot find symbol 
symbol: variable Graphics 
location: class UI 

当我导入java.awt.Graphics类。

这是为什么?

查看来电buttons[count].paintComponent(Graphics g) ...

首先,你应该永远不会调用paintComponent自己,你应该让RepaintManager处理。改为使用repaint

其次,Graphics g不是一个有效的参数,它是一个减速。

退房

有关Swing和绘画细节。

另外...在你内部调用this.setBorder(null);绘制方法是一个非常非常糟糕的主意。这会触发一个新的重新绘制请求,一次又一次地重复发送到事件调度线程上......你明白了。它会消耗你CPU