2013-05-15 111 views
0

我遇到了类组件问题。问题是我的椭圆不改变他们的颜色。函数if在类Counter中观察OVF标志。当OVF =真椭圆应该是红色的,并且当OVF =假椭圆应该是白色的。在我的GUI中,我只能看到红色的椭圆(即使OVF = false)。我尝试添加重绘()命令,但红色椭圆只开始闪烁。这里是我的代码:Java JComponent不刷新

import java.awt.*; 
import javax.swing.*; 
import java.util.Observable; 


public class Komponent extends JComponent 
{ 
Counter counter3; 
public Komponent() 
{ 
    counter3=new Counter(); 
} 
public void paint(Graphics g) 
{ 
Graphics2D dioda = (Graphics2D)g; 
int x1 = 85; 
int x2 = 135; 
int y = 3; 
int width = (getSize().width/9)-6; 
int height = (getSize().height-1)-6; 

if (counter3.OVF = true) 
{ 
dioda.setColor(Color.RED); 
dioda.fillOval(x1, y, width, height); 
dioda.fillOval(x2, y, width, height); 
} 
if (counter3.OVF = false) 
{ 
dioda.setColor(Color.WHITE); 
dioda.fillOval(x1, y, width, height); 
dioda.fillOval(x2, y, width, height); 
} 
} 
public static void main(String[] arg) 
{ 
new Komponent(); 
} 
} 

该代码有什么问题?

+0

不覆盖涂料,其建议您使用的paintComponent代替。你也应该调用super.paintComponent(或者在你的情况下是super.paint)。查看[自定义绘画](http://docs.oracle.com/javase/tutorial/uiswing/painting/)以获取更多详细信息 – MadProgrammer

+0

为了更快获得更好的帮助,请发布[SSCCE](http://sscce.org/) 。 –

回答

0

如果应该是:

if (counter3.OVF == true) { // watch out for = and == 
    // red 
} 
if (counter3.OVF == false) { 
    // white 
} 

或者简单:

if (counter3.OVF) { 
    // red 
} else { 
    // white 
} 

或者简单:

dioda.setColor(counter3.OVF ? Color.RED : Color.WHITE); 
dioda.fillOval(x1, y, width, height); 
dioda.fillOval(x2, y, width, height); 
+0

谢谢,你说得对。但是现在椭圆仍然是白色的,也许我应该添加重绘()函数。 – Martyn

+0

所有的答案都很好,谢谢:)但是我仍然只能看到白色椭圆:( – Martyn

+0

@ user2283763尝试'System.out.println(counter3.OVF);'在'paint'中检查' counter3.OVF'。 – johnchen902