setEditable().
In Core Java, the correct method to set a TextComponent
(such as a TextField
or TextArea
) to the read-only state is setEditable(boolean)
.
The setEditable(boolean)
method allows you to control whether the text component is editable or not. If you pass false
as an argument, it makes the text component read-only, preventing the user from editing its content.
Here’s an example of how you might use it:
import javax.swing.*;
public class ReadOnlyTextFieldExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Read-Only TextField Example");
JTextField textField = new JTextField("This is a read-only text field");
// Set the text field to read-only
textField.setEditable(false);
frame.getContentPane().add(textField);
frame.setSize(300, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
In this example, the setEditable(false)
method is used to make the textField
read-only.