Stepan Stepan - 8 months ago 24
Java Question

Java add a non-editable tJTextField in one line

We can add an editable JTextField to a panel in one line like this

panel.add(new JTextField(text));
in Java. Is there a standard way to set it non-editable using something like
panel.add(new JTextField(text).setEditable(false));
without writing our own method?


It's possible to do it that way, but you still shouldn't.

panel.add(new JTextField(text){{setEditable(false);}});

This creates an anonymous class, which sets it as not editable in the initialization block.

Doing it that way is considered bad practice though. You should just split it into multiple lines, or write a method to do it. The code will be more maintainable and easier to read that way.