为什么我在尝试调用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