Search code examples
javaswingencodingjtextfield

Java - Russian strings and JTextField, changing the String to "????..."


I'm writing a small application that should receive some English and Russian text from the user, then do some processing on it. I would prefer to keep both as on String, if possible.

The way I was trying to do it right now involved having a GUI I wrote using the swing lib, specifically the JTextField.

For the English strings, that works fine and all. However, the russian Strings keep coming out as "???????". I feel like I'm doing something wrong with the encodings, but I could not find for the life of me any resources about what I should do differently.

Here is the code:

JLabel name_ru;
JTextField name_russian;

public Gui()
{
    name_ru = new JLabel("Name in Russian:");
    name_russian = new JTextField();
}

public void run()
{
ru_name = name_russian.getText();
System.out.println(ru_name);
}

Upon actually adding my JTextField to my JFrame based GUI, I am able to prompt the printing of the JTextField.getText() String to consol and save it to a txt file using a BufferedWriter. If the text in the JTextField is in English, I have no porblem doing this. However , as soon as I try it with Russian text (Or any non-english text) my output comes out as "??????????". The way the text gets into that JTextField is simpley the user typing it in once the GUI is running.

I've looked around, however none of the solutions posted on here (or anywhere else where I could find) seemed to be dealing with the JTextField class - it seems that the .getText() returns a badly encoded string... Is there a way to change it? Help!

Thank you, Eric.


Solution

  • System.out.println(ru_name);
    

    will not be able to print the UTF-8(russian) characters with default console settings. And hence it is printing ??? for the characters. Make sure the console you use to display the output is encoded in UTF-8. If you are using eclipse then go to

    Run Configuration > Common -> Encoding and select UTF-8 form the drop-down.

    enter image description here