Search code examples
javaswingjtextfield

Get Text From a disabled JTextField


I have been using the function getText() to read user Input in MyJTextField Until I have noticed that this does Not Look Possible with Disabled JTextField.

JTextField jtx = new JTextField();
jtx.setText("TEST");
jtx.setEnabled(false);
String str = jtx.getText();
System.out.println(str);

This does not return Anything and I am begining to think that it is because of the Disabled JTextField. Is there a Way to get Text From a Disabled JTextField or Should I just:

jtx.setEditable(false);

I do not want to do this. I want the field to be disabled.


Solution

  • The code below works as expected (prints TEST whether the text field is enabled or disabled) - are you running your code in the EDT?

    public static void main(String[] args) throws InterruptedException {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JTextField jtx = new JTextField();
                jtx.setText("TEST");
                System.out.println("Before: " + jtx.getText());
                jtx.setEnabled(false);
                System.out.println("After: " + jtx.getText());
            }
        };
        SwingUtilities.invokeLater(r);
    }