Link to home
Start Free TrialLog in
Avatar of damienm
damienmFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Keystroke evaluation

Hi All,

I have the below code but I would like to limit people to typing in the characters in range A-E, so I need some kind of a key listener that will display a message if any other character is typed and will remove this character.

So if I typed AF it would say something like invalid character and the textfield would only have A remaining.

Thanks for any help

Damien

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

public class Bullseye extends JFrame
{
      public char first;
      public char second;
      public char third;
      public int comScore=0;
      public int perScore=0;
      public int noOfTrys=0;

      JTextField textId = null;
      
      public static void main(String[] args)
         {
            JFrame frame = new Bullseye();
            frame.show();
         }
   
   public Bullseye()
   {
               //System.out.println("before chars");
               generateChars();
            //System.out.println("after chars");
               setSize(500, 100);
        setTitle("Bullseye");
               addWindowListener(new WindowAdapter()
        {  
                  public void windowClosing(WindowEvent e)
            {  
                        System.exit(0);
            }
        }
            );
   
         Container contentPane = getContentPane();
         JPanel canvas = new JPanel();
             canvas.setLayout( new GridLayout(1,1,0,0));
             canvas.add(new JLabel("Enter 3 characters: "));
             textId = new JTextField();
                         

             canvas.add(textId);
             contentPane.add(canvas, "Center");
         JPanel p = new JPanel();
         addButton(p, "Submit",
             new ActionListener()
              {  
                   public void actionPerformed(ActionEvent evt)
            {  
                        evaluate();            
            }
         }
             );
 
         addButton(p, "Close",
            new ActionListener()
            {  public void actionPerformed(ActionEvent evt)
               {  
                        System.exit(0);
               }
            });
         contentPane.add(p, "South");
      }
      
      public void addButton(Container c, String title,ActionListener a)
      {  
            JButton b = new JButton(title);
          c.add(b);
          b.addActionListener(a);
         }
      
      private void generateChars()
      {
            boolean bEqual;
            first = convertToChar(Math.random());
            second = convertToChar(Math.random());
            third = convertToChar(Math.random());
            bEqual = true;
            
            while (bEqual)
            {
                  if (first == second)
                        second = convertToChar(Math.random());
                  else
                        bEqual = false;      
                        
                  //System.out.println("boolean = "+bEqual);
            }
            
            bEqual = true;
            while (bEqual)
            {
                  if ((first == third) || (second == third))
                        third = convertToChar(Math.random());
                  else
                        bEqual = false;      
            }
            //This is only in for testing purposes
            System.out.println("New Combination :"+first+second+third);
            
      }
      
      private char convertToChar(double d)
      {
            //System.out.println("random number: "+d);
            int val = (new Double((d*5)+0.5)).intValue();
            //System.out.println("random int: "+val);
            switch(val)
            {
                  case 1:
                        return 'A';
                  case 2:
                        return 'B';
                  case 3:
                        return 'C';
                  case 4:
                        return 'D';
                  case 5:
                        return 'E';
                  default :
                        return 'A';
            }
      }
      
      private void evaluate()
      {
            try{
            noOfTrys++;
            String guess = textId.getText();
            guess = guess.toUpperCase();
            char a = guess.charAt(0);
            char b = guess.charAt(1);
            char c = guess.charAt(2);
            int[] intArray = compare(a,b,c);
            System.out.println("There is "+intArray[0]+" bullseye.");
            System.out.println("There is "+intArray[1]+" hits.");
            System.out.println("This is try "+noOfTrys);
            if (intArray[0]==3)
            {
                  perScore++;
                  noOfTrys=0;
                  System.out.println("You win!");
                  generateChars();

            }
            else
            {
                  if (noOfTrys==4)
                  {
                        comScore++;
                        noOfTrys=0;
                        System.out.println("You lose!");
                        generateChars();

                  }
            }
            System.out.println("Person : "+perScore);
            System.out.println("Computer : "+comScore);




            
            }
            catch(Exception e)
            {
                  System.out.println("Error in startSearch");
            }
      }
      
      private int[] compare(char a ,char b , char c)
      {
            int bullcount =0;
            int hitcount =0;
            if (a==first)
                  bullcount++;
            if (b==second)
                  bullcount++;
            if (c==third)
                  bullcount++;
            if ((a==second)||(a==third))
                  hitcount++;
            if ((b==first)||(b==third))
                  hitcount++;
            if ((c==second)||(c==first))
                  hitcount++;
            
            int[] result = new int[] {bullcount,hitcount};
            return result;
      }
}
ASKER CERTIFIED SOLUTION
Avatar of bobbit31
bobbit31
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mzimmer74
mzimmer74

Create a customTextField and overwrite the document model like this:

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

public class CustomTextField extends JTextField
{
     private Toolkit toolkit;

     public CustomTextField(String text, int cols)
     {
         super(cols);
         toolkit = Toolkit.getDefaultToolkit();
         this.setText(text);
     }
     protected Document createDefaultModel()
     {
         return new CustomTextDocument();
     }  

  protected class CustomTextDocument extends PlainDocument
  {
     public void insertString(int offs, String str, AttributeSet a)
                    throws BadLocationException
     {
         if(str != null && goodChar(str))
         {
            super.insertString(offs,str,a);
         }
         else
         {
           toolkit.beep();
         }
     }
  }
}



You'll want to write the method goodChar(String s) to check to see that the string only contains the characters you want.  Hope this helps.
When checking for suitable characters, use a BitSet to do the checking, as it will perform MUCH better than any switch, if, or String manipulations...

private static final BitSet ALLOWED_CHARS = new BitSet(5);

static {
     ALLOWED_CHARS .set('A');
     ALLOWED_CHARS .set('B');
     ALLOWED_CHARS .set('C');
     ALLOWED_CHARS .set('D');
     ALLOWED_CHARS .set('E');
}

public true isValidChar(char c){
     return ALLOWED_CHARS.get(c)
}
Adding a key listener to your text field is useless because the user can still copy-and-paste text (with other characters) onto your text field.

mzimmer74's solution is the way to go. By the way, in JDK1.4, there is a class called JFormattedField which I think will let you do what you want.
Avatar of damienm

ASKER

I am not that familiar with Java but this is close enough.

Thanks

Damien