-1

I have a problem with my Component in Java. When i set OVF flag to true, Rect should be in Color red (255,0,0), and if i set OVF flag to false, Rect should be in color blue (0,0,255). The problem is that I can see in my GUI only blue rectangle (even if OVF flag is set to true). What should I change in this code?

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 ();
}
}

Thanks for helping me.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Martyn
  • 21
  • 3
  • 3
    Your code needs an emergency indentation. – Maroun May 15 '13 at 21:15
  • 2
    Probably has something to do with how you are instantiating a new counter3 in every call to `paintComponent`. Where are you setting OVF? – martinez314 May 15 '13 at 21:16
  • OVF is setting in Counter class. OVF is set to true when MainReg is set to 0 (it works, because if OVF==true i can see in my GUI class label "INTERRUPT" – Martyn May 15 '13 at 21:18
  • Swing Timer repeats. Y default, so calling start in paintComponent probably isn't a good idea – MadProgrammer May 15 '13 at 21:27
  • You might want to check [this](http://stackoverflow.com/questions/13779392/blinking-in-jframe-java/13781606#13781606) out for some more ideas – MadProgrammer May 15 '13 at 21:29
  • So where should I put start of timer? – Martyn May 15 '13 at 21:40
  • 1) Use a consistent and logical indent for code blocks. The indentation of the code is intended to help people understand the program flow. 2) Please learn common [Java naming conventions](http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#73307) (specifically the case used for the names) for class, method & attribute names & use them consistently. – Andrew Thompson May 16 '13 at 06:29

1 Answers1

1

Create a constructor in the Komponent2 class containing the counter initialization and start the Timer. This will prevent multiple instances of Counter being created. Also move the Timer from the paintComponent method so that it is not restarting for every repaint.

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

public void init() {
   tm.start();
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276