2013-05-15 61 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