• Post Reply Bookmark Topic Watch Topic
  • New Topic

Inputting one letter into a JTextField

 
Michelle Ruth
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm writing a java program in eclipse of a tic-tac-toe game. I have to create it using JTextField's only I'm having trouble where the JTextField will only accept one letter and will only accept X and O is there any particular way to do this I started off with this piece of code



But it doesn't work so is there something I'm missing
 
Campbell Ritchie
Marshal
Posts: 52519
119
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

In real life, without that restriction, you would do that with a formatted text field, but you have been told to use an ordinary text field. There are document listeners, but I don't know how they work.
How are you calling that block of code? Have you got a Listener attached to the text field?
Don't use System.out from a GUI; use a dialogue window. If you export the whole thing as a .jar file and open it you use javaw instead of java, so System.out might not appear.
 
Rob Camick
Ranch Hand
Posts: 2699
10
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are document listeners, but I don't know how they work.


You don't want a DocumentListener. The listener fires its event AFTER the Document has been updated which is too late to reject letters.

Instead you want a DocumentFilter whichs allows you to edit the letter BEFORE it is added to the Document. Read the section from the Swing tutorial on Implementing a Document Filter for more information.
 
Campbell Ritchie
Marshal
Posts: 52519
119
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you RC; your replies are always helpful. 1 cow for persistent helpfulness.
 
Michelle Ruth
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you gonna try and implement that into my code and see if it works
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!