Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Logic Error with keyListener.

$
0
0
I have a problem with a keyListener that's absolutely beyond me as to what the problem is. I'm trying to get basic one-character user input working provided that it doesn't use any special text boxes. As a test in my paint() method, I have a String drawn if the char is equal to 'c'.

All I know is that the String isn't printing, and the program will not terminate without the aid of Window's Task Manager.


Here's my code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="SaveChristmas" width=300 height=50>
</applet>
*/

public class SaveChristmas extends JApplet implements KeyListener
{
    boolean pause;
    char ch = 0;
    String s = "HW";
    
    public void init()
    {
        char ch;
        addKeyListener(this);
    }
    
    public void start()
    {
        pause = false;
        setFocusable(true);
    }
    
    public void run()
    {
        for( ; ; )
        {
            //try
            {
                repaint();
                if(pause)
                    break;
            }
            //catch(InterruptedException exc) {}
        }
    }
    
    public void stop()
    {
        pause = true;
        setFocusable(false);
    }
    
    public void keyTyped(KeyEvent e)
    {
        ch = e.getKeyChar();
        run();
    }
    
    @Override
    public void keyPressed(KeyEvent e)
    {
    }
    
    @Override
    public void keyReleased(KeyEvent e)
    {
    }
    
    public void paint(Graphics g)
    {
        if(ch == 'c')
            g.drawString(s, 50, 50);
    }
}


What I've tried:

  • setting focus on the JApplet
  • putting a call to run() in the key listener
  • getting rid of the call to run() in the key listener and moving the setting of the char to the run method

Viewing all articles
Browse latest Browse all 51036

Trending Articles