Search code examples
javaswingnullpointerexceptionjtextfield

JTextField.getInputContext() returns null value


In my Swing application, I use JTextField component to get Farsi text values.

I want to set locale for this component by using the following code:

txt_fname.getInputContext().selectInputMethod(new Locale("fa", "IR"));

But txt_fname.getInputContext() returns null and the code throws a NullPointerException.

How can I solve this problem?

Edited

the code is called in InternalJFrame constructor:

public DriversList() {
    initComponents();
    txt_fname.getInputContext().selectInputMethod(new Locale("fa", "IR"));        
}

Solution

  • This MCVE suggests the code you have not shown, is attempting to get the input context before the text field is first displayed.

    Code

    import java.awt.*;
    import javax.swing.*;
    
    class InputContextTest {
    
        public static void main(String[] args) {
            Runnable r = new Runnable() {
    
                @Override
                public void run() {
                    JTextField tf = new JTextField(10);
                    System.out.println(tf.getInputContext());
                    JOptionPane.showMessageDialog(null, tf);
                    System.out.println(tf.getInputContext());
                }
            };
            // Swing GUIs should be created and updated on the EDT
            // http://docs.oracle.com/javase/tutorial/uiswing/concurrency
            SwingUtilities.invokeLater(r);
        }
    }
    

    Output

    null
    sun.awt.im.InputMethodContext@1fa5e5e
    Press any key to continue . . .