How do I use KEYLISTENER while a THREAD occurs in the execution? With the code below only the thread acts

Asked

Viewed 19 times

1

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

public class Letras extends Frame implements Runnable,KeyListener{

    private final Label pontuacao;
    private final Label mostraPontos;
    private final Button start;
    private final Label letraCair;

    char l[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R',
            'S','U','V','W','Y','X','Z'};


    public static void main(String[] args) {
        Letras letra = new Letras();
        letra.setVisible(true);
        letra.setSize(1100,400);
    }


    public void run() {

        int x = letraCair.getX();
        int y = letraCair.getY();

        try {

            while(y <250) {
                for (int i = 0; i < l.length; i++) {
                    int retornaChar = (int)(Math.random()*25);
                    letraCair.setText(l[retornaChar]+"");
                    letraCair.setLocation(x, y+10);
                    y+=10;
                    Thread.sleep(1000);

                }

            }

        } catch (InterruptedException e) {

            e.printStackTrace();
        }

    }


    public void keyPressed(KeyEvent e) {

//testando keylistener sem sucesso
        mostraPontos.setText(e.getKeyChar()+"");

    }

    public void keyReleased(KeyEvent arg0) {

    }

    public void keyTyped(KeyEvent e) {

    }

    public void paint(Graphics g) {
        g.drawRect(50, 50, 1000, 300);
        g.drawLine(800, 50, 800, 350);

    }

    //Construtor
    public Letras() {
        super("jogo de Letras");
        setLayout(null);
        setVisible(true);

        start = new Button("Start");
        pontuacao = new Label("PONTOS");
        mostraPontos = new Label("0");
        letraCair = new Label();


        add(mostraPontos).setBounds(900, 110, 130, 30);
        add(pontuacao).setBounds(880, 90, 60, 30);
        add(start).setBounds(900, 300, 60, 30);
        add(letraCair).setBounds(400, 60, 40, 10);

        addKeyListener(this);

        start.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                run();
            }
        }); 

        this.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent arg0) {

                System.exit(0);
            }

        });

    }

}
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.