Solved

Forcing uppercase in a textfield...

Posted on 1998-01-13
20
568 Views
Last Modified: 2008-02-01
I want to force uppercase when the user is typing in the textfield.  So every character they type will appear in upper case in the textfield.  How do I do this?
0
Comment
Question by:beano
  • 10
  • 4
  • 3
  • +2
20 Comments
 
LVL 32

Expert Comment

by:jhance
ID: 1232178
Add the Event.KEY_PRESS to the TextField component and direct it to the following function:

      protected void TextField1KeyPress( Event event )
      {
            //       Put event handler code here...
            char uc = (char)event.key;
            String x = new String().valueOf(uc).toUpperCase();
            String curstring = textField1.getText();
            textField1.setText(curstring + x);
      }
0
 

Author Comment

by:beano
ID: 1232179
How do I do this with the java 1.1 event model?  I currently have:

class UpperCaseKeyListener extends KeyAdapter {
      private NewProfileGroupDialog np;
      char c;

      UpperCaseKeyListener(NewProfileGroupDialog np) {
            this.np = np;
      }

      public void keyPressed(KeyEvent e) {
            c = e.getKeyChar();
            if (Character.isLetter(c)) {
                  c = Character.toUpperCase(c);
                  String curLine = np.input.getText();
                  np.input.setText(curLine + c);
            }
      }
}

This works but it types the lowercase as well as the Uppercase character in the textfield.  How do I not let it type the lowercase character, and only the uppercase one?
0
 
LVL 5

Expert Comment

by:msmolyak
ID: 1232180
How about replacing

String curLine = np.input.getText();
np.input.setText(curLine + c);

with

String curLine = np.input.getText();
String withoutLastChar = curLine.substring(0, curLine.length() - 2)
np.input.setText(withoutLastChar + c);

You may play with substring function argument to get it right.

0
 

Author Comment

by:beano
ID: 1232181
It doesn't seem to be working to good.  I played around with the substring and it still doesn't work.  Is this the best way to do this?  If not, what is the best way to force uppercase?
0
 
LVL 5

Expert Comment

by:msmolyak
ID: 1232182
I am not sure whether it is the best way but at least it should work. What exactly happens? Did you make sure that the substring() function chops off the last character?
0
 

Author Comment

by:beano
ID: 1232183
When you type the key, and trap the event, and then in the public void keyPressed(KeyEvent e) method, you print the textfield.getText(), it prints the text that was there before you pressed the last key, so cutting off the last character doesn't work in this case.
0
 
LVL 5

Expert Comment

by:msmolyak
ID: 1232184
Replace keyPressed()with keyTyped() and try the same trick. From what you are saying I conclude that the upper case character was showing up before the lower case one, right?
0
 

Author Comment

by:beano
ID: 1232185
I tried that, and it is the same case.
0
 
LVL 2

Expert Comment

by:webster030697
ID: 1232186
To get the TextField to display uppercase, all you need to do is use the setEchoChar() method:

public void setEchoChar(char c)

    Sets the echo character for this text field.

You would implement this something like:

setEchoChar(Character.toUpperCase(c))
0
 

Author Comment

by:beano
ID: 1232187
This is the code that I have, and it didn't work all that well, it forced uppercase, but it the text did not appear as I typed it:

class UpperCaseKeyListener extends KeyAdapter {
      private NewProfileGroupDialog np;
      char c;

      UpperCaseKeyListener(NewProfileGroupDialog np) {
            this.np = np;
      }

      public void keyPressed(KeyEvent e) {
            c = e.getKeyChar();
            if (Character.isLetter(c)) {
                  np.input.setEchoChar(Character.toUpperCase(c));
            }
      }
}

When I typed the word test, it appeared in the TextField as "TTTT".  How do I correct this?
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 6

Expert Comment

by:jpk041897
ID: 1232188
If the event model isn't handling the code correctly, you might want to consider overriding the TextField so that you control both its paint mechanism and the characters that are being inputed into the associated string.
0
 

Author Comment

by:beano
ID: 1232189
How do I do that?  I have not done anything like overriding a TextField.
0
 
LVL 32

Accepted Solution

by:
jhance earned 50 total points
ID: 1232190
You know, I posted this earlier and it still works, even under JDK 1.1:

Add the Event.KEY_PRESS to the TextField component and direct it to the following function:

protected void TextField1KeyPress( Event event )
{
// Put event handler code here...
char uc = (char)event.key;
String x = new String().valueOf(uc).toUpperCase();
String curstring = textField1.getText();
textField1.setText(curstring + x);
}
0
 

Author Comment

by:beano
ID: 1232191
I just tried your code, and when I type the word test I get the following output in my textfield:  tsetTEST

This is my code:

class UpperCaseKeyListener extends KeyAdapter {
      private NewProfileGroupDialog np;
      char c;

      UpperCaseKeyListener(NewProfileGroupDialog np) {
            this.np = np;
      }

      public void keyPressed(KeyEvent e) {
            c = e.getKeyChar();
            if (Character.isLetter(c)) {
                  String x = new String().valueOf(c).toUpperCase();
                  String curstring = np.input.getText();
                  np.input.setText(curstring + x);
            }
      }
}

And I register this listener with the textfield which is called input.
0
 
LVL 6

Expert Comment

by:jpk041897
ID: 1232192
I posted the following code for a 1.02 question regarding limiting the ammount of characters accepted by a textfield. Although the event model for this code has changed, the problem is close enough in nature to your application and the technique used should give you insight as to how to acomplish overriding the text field.

import java.awt.*;

                 //Define a custom TextField class that can respond to events.
                 // Note that this class extends TextField.
                 class TF extends TextField{

                   int maxCount = 5;
                   int count = 0;
                   TF(String inString, int MaxCount){
                     setText(inString);
                     maxCount = MaxCount;
                   }//end constructor

                   //The following event handler method handles events at the
                   // component level as opposed to the container level.
                   public boolean handleEvent(Event evObj){
                   
                     switch(evObj.id){
                     case Event.KEY_PRESS :
                 if (count < maxCount){
                     char[] c = new char[1];
                     c[0]= (char) evObj.key;
                     String s = new String(c);
                     setText(getText() + s);
                     count++;
                     }
                     break;
                     default : //catch and display all other event types here
                     break;
                     }//end switch
                     return super.handleEvent(evObj);
                   }//end handleEvent() in class TF
                   
                 }//end class TF
                 //===================================================================

                 And folloing is a sample app that uses it:

                 import java.awt.*;


                 public class Event05 extends Frame{

                   public Event05(){
                     TF myTextField = new TF("", 5);//instantiate custom TextField object
                     add ("Center",myTextField);
                     myTextField.setEditable(false);//make it non-editable

                     resize(300,50);//set frame size
                    }//end constructor

                   //Create and show the frame object
                   public static void main(String[] args){
                     Event05 displayWindow = new Event05(); //instantiate obj of this type
                     displayWindow.show();//display the frame
                   }//end main
                   
                   
                   public boolean handleEvent(Event evObj){
                     //Terminate program if user closes the window
                     if(evObj.id == Event.WINDOW_DESTROY) System.exit(0);
                     return super.handleEvent(evObj);
                   }//end handleEvent()
                   
                 }//end class Event05

Hope it helps.
0
 

Author Comment

by:beano
ID: 1232193
This is the class that I created:

import java.awt.*;
import java.awt.event.*;

//Define a custom TextField class that can respond to events.
// Note that this class extends TextField.
public class UpperTF extends TextField implements KeyListener{

      UpperTF() {
            addKeyListener(this);
      }

      public void keyPressed(KeyEvent e) {
            char c = e.getKeyChar();
            if (Character.isLetter(c)) {
                  String c_upper = new String().valueOf(c).toUpperCase();
                  setText(getText() + c_upper);
            }
      }
      public void keyReleased(KeyEvent e) {}
      public void keyTyped(KeyEvent e) {}
}
 
But when I type the word "test", this is what appears in the textfield:  "tsetTEST".  It seems to type both what I type and what I convert to UpperCase.  How do I only let it display what I change to uppercase?
0
 
LVL 6

Expert Comment

by:jpk041897
ID: 1232194
setText(getText() + c_upper); Is appending the data to the end of the string. Set a running counter of inputed characters so that you can end up with something like:

String newText = getText.substring(1, i++) + c_upper;
setText(newText);

Of course, you will need to initialize i bebore you start procecing the text field.

This way you insure overwritng the appropiate sections of the text field rather than appending to it.
0
 

Author Comment

by:beano
ID: 1232195
I am not sure if I understand what you are trying to do here.
0
 
LVL 6

Expert Comment

by:jpk041897
ID: 1232196
Your code is bringing in the entire contents of the textbox (both what the native methods are building) plus what you are coding. (I'm actualy supprised you arent getting tTeExXtT with your code :-) )

My suggestion is that if Java is producing the following:

tT
teTE
texTEX
textTEXT

Then the hack would be to have your code overrwrite the character that Java is placing with its uppercase equivalent, rather then appending.

Another alternative would be along the lines of:

String UpperText;
...
 String c_upper = new String().valueOf(c).toUpperCase();
 UpperText+=c_upper;
 setText(UpperText);

And just overwrite the text on the edit box with each character entered.
0
 

Author Comment

by:beano
ID: 1232197
that doesn't work either, I just tried that.
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now