0

Im trying to make a hangman game. Im stuck on trying to listen for the keystroke. I want the user to be able to press a key and it will test to see if it is correct or not. I dont want to have to have it inputted into a text box, regardless of focus I want that key to be tested against the word. Ive tried adding a keylistener to the panel and it doesnt work. The whole thing consists of this panel, a leftpanel, a main panel and then a main frame.

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

public class RightPanel extends JPanel
{
JLabel jlbMissed, jlbWord, jlbScore, jlbTimer;
JComboBox jcbDifficulty;
JButton jbtStart, jbtQuit;
String[] difficulties = {"Easy", "Medium", "Hard"};
String[] words = {"First", "Next", "Hello", "World"};
char incorrectChar, correctChar;
String word;
int currentScore;
boolean clockIsRunning = false;
boolean gameInPlay = false;
int sec = 0;
int min = 0;




public RightPanel()
{

    this.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    ActionHandler actionHandler = new ActionHandler();
    jlbMissed   = new JLabel("Missed: " + incorrectChar);
    jlbWord     = new JLabel("Word: " + correctChar);
    jlbScore    = new JLabel("Score: " + currentScore);
    jlbTimer    = new JLabel("Time: " + "0:00");
    jbtStart    = new JButton("Start");
    jbtQuit     = new JButton("Quit");
    jcbDifficulty = new JComboBox();
    for (int i = 0; i < 3; i++)
    {
        jcbDifficulty.addItem(difficulties[i]); // Creates Difficutly ComboBox
    }
    this.add(jcbDifficulty, getConstraints(0,0,1,1, GridBagConstraints.NORTH));
    this.add(jlbMissed, getConstraints(0,1,1,1, GridBagConstraints.CENTER));
    this.add(jlbWord, getConstraints(0,2,1,1, GridBagConstraints.CENTER));
    this.add(jlbScore, getConstraints(0,3,1,1, GridBagConstraints.CENTER));
    this.add(jlbTimer, getConstraints(0,4,1,1, GridBagConstraints.CENTER));
    this.add(jbtStart, getConstraints(0,6,1,1, GridBagConstraints.CENTER));
    this.add(jbtQuit, getConstraints(1,6,1,1, GridBagConstraints.CENTER));
    jbtStart.addActionListener(actionHandler);
    jbtQuit.addActionListener(actionHandler);
    Random ran = new Random();  //
    int rand = ran.nextInt(4);  // Generates random number then selects word from words array
    word = words[rand];         //
    KeyListener k = new KeyAdapter()
    {
         public void keyPressed(KeyEvent e) {System.out.println("key was pressed");}
    };
    this.addKeyListener(k);




}




private GridBagConstraints getConstraints(int gridx, int gridy, int gridwidth, int gridheight, int anchor)
{
    GridBagConstraints c = new GridBagConstraints();
    c.insets = new Insets(5,5,5,5);
    c.ipadx = 0;
    c.ipady = 0;
    c.gridx = gridx;
    c.gridy = gridy;
    c.gridwidth = gridwidth;
    c.gridheight = gridheight;
    c.anchor = anchor;
    return c;
}

class ActionHandler implements ActionListener
  {
public void actionPerformed(ActionEvent e)
{
    Object source = e.getSource();
    if (source == jbtStart)
    {
        clockIsRunning = true;
        MyTimer timer = new MyTimer();
        timer.start();
        gameInPlay = true;
    }
    else if (source == jbtQuit)
    {
        System.exit(0);
        }

}
  }
  class MyTimer extends Thread
  {
public void run()
{
    while(true)
    {
        if(!clockIsRunning)
            break;
        try
        {
            Thread.sleep(1000);
        }
        catch (InterruptedException ecp)
        {
        }

        if (sec == 59)
        {
            min++;
            sec = 0;
        }
        else
            sec++;
        if(sec < 10)
            jlbTimer.setText("Time:" + min+":0"+sec);
        else
            jlbTimer.setText("Time:" + min+":"+sec);
    }
}
  }
Marcus
  • 49
  • 1
  • 7
  • Please look at this link: [how-can-i-listen-for-key-presses-within-java-swing-accross-all-components](http://stackoverflow.com/questions/5344823/how-can-i-listen-for-key-presses-within-java-swing-accross-all-components) and also [java-keylistener-for-jframe-is-being-unresponsive](http://stackoverflow.com/questions/286727/java-keylistener-for-jframe-is-being-unresponsive) – Hovercraft Full Of Eels Apr 05 '11 at 00:43

1 Answers1

0

If I understand you correctly, you want this key listener to work everywhere, all the time. If that's the case, you can just make your frame its own KeyListener, as described in this demo from the Swing tutorial.

I know it looks like it requires a text box, but try adding this as line 118:

displayArea.addKeyListener(this);
Pops
  • 30,199
  • 37
  • 136
  • 151
  • I created the display area 'JTextArea displayArea;' Now for me line 118 is showing up as right in the middle of the timer method. I put it just at the bottom of RightPanel() and it comes up with the message addKeyListener(java.awt.event.KeyListener) in java.awt.Component cannot be applied to (RightPanel) – Marcus Apr 04 '11 at 23:16
  • @Marcus, no, not _your_ line 118. I have no idea what the line numbers in your program are; you didn't even post it all. If you add that as line 118 in the demo I linked, it works even when the output area has focus. – Pops Apr 04 '11 at 23:24
  • It only works because the displayArea.addKeyListener listens for that. If focus is on the button then it doesnt work. For now Im simply adding KeyListeners to both the combo box and the button as they are pretty much the only things that could be in focus. – Marcus Apr 05 '11 at 01:00