【发布时间】:2013-12-02 14:48:59
【问题描述】:
所以我只想在屏幕的随机部分绘制一个正方形作为自定义JComponent:
public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D) g;
if( this.good ){
g2d.setColor(Color.green);
}
else{
g2d.setColor(Color.red);
}
g2d.fillRect(this.x, this.y, this.w, this.h);
System.out.println("painting");
}
这里是通过repaint()调用绘画的方法
private void stateChange(){
double rand = Math.random();
if (rand < 0.5){
this.good = !this.good;
}
setLocation(this.x,this.y);
repaint();
}
this.x 和 this.y 不断变化,但我知道这是可行的。当我运行我的代码时,它会在应有的位置打印"painting",但没有显示任何内容。我做错了吗?
额外代码:
这是我试图让它显示出来的内容:
\\in JComponent constructore
setOpaque(true);
setVisible(true);
setSize(this.w,this.h);
【问题讨论】:
-
确保您拨打的是
super.paintComponent;)
标签: java swing paintcomponent jcomponent