正在运行但未显示的swing Java组件
因此,我只想在屏幕的随机部分绘制一个正方形作为custonJComponent
:
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
不断变化,但我知道这是可行的。当我运行代码时,它会在应该打印的地方打印^{
额外代码:
下面是我为让它出现而写的:
\\in JComponent constructore
setOpaque(true);
setVisible(true);
setSize(this.w,this.h);
# 1 楼答案
我的猜测是:您有一个while(true)循环来连接Swing事件线程,因此当您更改状态时,GUI无法重新绘制自身以显示它正在发生。或者您的JComponent的大小非常小,太小,无法显示图像
对于一个不只是猜测的答案,你需要问一个更完整的问题,并附上相关的代码
请注意
paintComponent(...)
方法重写缺少对super方法的调用注意:您可以通过在paintComponent中添加getSize()方法来测试JComponent的大小:
注意:您应该而不是调用组件上的
setSize(...)
。这通常是误导性的,因为布局管理者经常忽略它# 2 楼答案
根据您提供的示例代码,问题在于您实际上正在绘制组件可视空间边界的外侧
绘制时,
Graphics
上下文的左上角是0x0
,Swing已经根据组件的位置转换了Graphics
上下文,因此实际上(可能)在零部件的可视区域之外进行绘制。例如,如果
x
位置为10
且y
位置为10
,但高度和宽度仅为10
,10
,则在位置10x10
处进行绘制,这将超出组件的可视空间,相反,您应该尝试以下操作或者,根据您的示例代码
相反