Artur Alvaro
Artur Alvaro

Reputation: 115

Infinite loop inside paint() method in an Applet does not let me interact with the buttons displayed

What I am trying to do is an Appled which throws 2 threads, each running a counter which increases itself via an infinite loop I then use a while(true) in the Applet's paint() method, which continuously paints the counters, the problem is that I have also 2 buttons, each intended to stop each thread, but the infinite loop in the paint() method doesn't let me neither click none of them nor close the Applet's window nor anything

Here a screenshot followed by the code

btw I'm certain the problem is the paint() loop as if I disable the loop I can interact with the buttons, but the counters are obviously not updated, and weird thing is that I put the mouse cursor over the buttons to show it took the form like when you want to resize a windows but the imprpant didn't capture it :/

https://i.sstatic.net/Gz8cf.png

public class MainApplet extends Applet implements ActionListener {

private static final long serialVersionUID = -2500043816999861110L;
private Font fuente;
private Button bUno, bDos;
private HiloContador hUno, hDos;

public void init() {
    setBackground(Color.LIGHT_GRAY);
    fuente = new Font("Verdana",Font.BOLD,26);
    bUno = new Button("Parar");
    bUno.addActionListener(this);
    bDos = new Button("Parar");
    bDos.addActionListener(this);   
    bUno.setSize(40,20);
    add(bUno);
    bDos.setSize(40,20);
    add(bDos);
    hUno = new HiloContador(20);
    hUno.start();
    hDos = new HiloContador(40);    
    hDos.start();

}

@SuppressWarnings({ "deprecation", "static-access" })
public void actionPerformed(ActionEvent e) {
    if(e.getSource().equals(bUno)){
        hUno.parar();
        bUno.setLabel("1 parado");
    }else if (e.getSource().equals(bDos)){
        hDos.parar();
        bDos.setLabel("2 parado");
    }               
}

public void paint(Graphics g) {
    while (true){
        g.clearRect(1,1,getSize().width,getSize().height); //dibuja la ventana
        g.setFont(fuente);
        g.drawString(hUno.getContador()+"",40,60); 
        g.drawString(hDos.getContador()+"",100,60); 
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

}

Upvotes: 0

Views: 220

Answers (1)

Artur Alvaro
Artur Alvaro

Reputation: 115

in case it helps anyone, solved deleting the infinite loop and adding this method

Timer timer = new Timer();
timer.schedule( new TimerTask() {
public void run() {
repaint();}
}, 0, 1000);

Upvotes: 1

Related Questions