2013-05-15 96 views
-1

我在Java中使用組件時遇到問題。當我將OVF標誌設置爲true時,Rect應該是顏色紅(255,0,0),如果我將OVF標誌設置爲false,則Rect應該是藍色(0,0,255)。問題是,我可以在我的GUI中看到只有藍色矩形(即使OVF標誌設置爲true)。這段代碼應該改變什麼?JComponent更改欄顏色

import java.awt.event.ActionListener; 
import java.awt.event.ActionEvent; 
import java.awt.*; 
import javax.swing.*; 

public class Komponent2 extends JComponent implements ActionListener 
{ 
Timer tm = new Timer(10, this); 
int x =30; 
int y =0, y2 = 8; 
Counter counter3; 
Color Kolor = new Color(255,255,255); 

public void paintComponent(Graphics g) 
{ 
    counter3=new Counter(); 
    super.paintComponent(g); 
    g.setColor(Kolor); 
    g.fillRect(y,30,x,30); 
    tm.start(); 
} 

public void actionPerformed(ActionEvent e) 
{ 
if(y<0 || y>300) 
y2=-y2; 
y=y + y2; 
if (counter3.OVF==true) 
Kolor = new Color (255,0,0); 
if (counter3.OVF==false) 
Kolor = new Color (0,0,255); 
repaint(); 
} 
} 

感謝您的幫助。

+3

您的代碼需要緊急縮進。 – Maroun

+2

可能與您在每次調用'paintComponent'時如何實例化新的counter3有關。你在哪裏設置OVF? – whiskeyspider

+0

OVF在Counter類中設置。當MainReg被設置爲0時,OVF被設置爲true(因爲如果OVF == true,我可以在我的GUI類標籤中看到「INTERRUPT」 – Martyn

回答

1

在包含計數器初始化的Komponent2類中創建一個構造函數,並啓動Timer。這將防止創建多個Counter實例。還要從paintComponent方法中移動Timer,以便每次重繪都不重新啓動。

public Komponent2() { 
    counter3 = new Counter(); 
} 

public void init() { 
    tm.start(); 
} 
+0

現在我的矩形仍然是白色的。它看起來像計時器不啓動。 – Martyn

+0

您是否調用了新的'init'方法來啓動它? – Reimeus

+0

我只是添加行「public void init(){tm.start();}」。我刪除了tm.start(); from paintComponent – Martyn