【问题标题】:Why am I getting an error as I try to call paintComponent?为什么我在尝试调用paintComponent 时会收到错误消息?
【发布时间】:2013-04-05 04:36:44
【问题描述】:

我的班级名为 UI 扩展 RoundButton 如下:

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 类时。

为什么会这样?

【问题讨论】:

    标签: java swing jbutton custom-component paintcomponent


    【解决方案1】:

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

    首先,你不应该自己打电话给paintComponent,你应该让RepaintManager来处理它。请改用repaint

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

    退房

    有关 Swing 和绘画的详细信息。

    另外...在您的绘画方法中调用this.setBorder(null); 是一个非常非常糟糕的主意。这将触发一个新的重绘请求,一遍又一遍地发布在事件调度线程上……你明白了。它会消耗你的 CPU

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      • 2015-01-25
      • 1970-01-01
      • 2016-07-12
      • 1970-01-01
      • 1970-01-01
      • 2019-10-16
      相关资源
      最近更新 更多