• Post Reply Bookmark Topic Watch Topic
  • New Topic

Type conversion question.  RSS feed

 
David Garratt
Ranch Hand
Posts: 216
Eclipse IDE Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Background

In a database I have 2 columns, one a string and one an integer. When my program runs it displays the text field held in the database as menu options and uses the integer column in order to use the setmnemonic function to highlight the required letter.

I order to maintain this table I have written a small form which allows the user to enter the text and integer values.

Problem.

I would like to modify my maintenance screen so that use user can enter the letter required for highligting (underling) as a character rather than an integer. If I do this I will need to convert the character entered into the ASCII value equivalent (A = 65 etc).

I think this can be done as :-

byte[] b = jTextFieldMnemonic.getText().getBytes();
int cb = b[0];
// cb is the ascii value of the character entered.

What has me a litte stumped is the way to do the opposite.

i.e. Take a integer, convert it to a string 1 character long

65 to "A" so that I can put it in the JTextfield on the screen.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi David,

The getBytes() method you've shown would work (in an ASCII-based locale, anyway) but is very inefficient; creating a byte[] object just so you can read the one entry is unnecessary overhead. String has a method charAt(int) which returns the character at a given position.

int cb = jTextFieldMnemonic.getText().charAt(0);

(By the way, either this version or yours will throw a RuntimeException if the user hasn't actually typed anything; better to fetch the String, check it for length, and don't do anything if it's 0 characters long.)

OK, now, for your real question: the String class has a whole bunch of overloaded static "valueOf(type)" methods which make a String out of various types. These are often the most straightforward way to make a String out of something else.

String myString = String.valueOf((char) theInteger);

That cast to "char" is important, or you'll get the String "65" instead of the String "A".
 
David Garratt
Ranch Hand
Posts: 216
Eclipse IDE Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Many thanks, that did the trick. Now I've come across what appears to be a know bug with mnemonics. Even though I specify a mnemonic of 65 which is a capital letter "A", if the text contains a lower case "a" somewhere before a capital "A" appears then it's the lowercase letter that gets underlined.

I'm using Java 1.5

Thanks for the quick response

Dave
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!