📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Make JTextField Read-Only or Not Editable in Java
Here's a simple example demonstrating how to create a read-only JTextField:import javax.swing.*;
import java.awt.FlowLayout;
public class ReadOnlyTextFieldDemo {
public static void main(String[] args) {
// Create a new JFrame
JFrame frame = new JFrame("Read Only JTextField Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLayout(new FlowLayout());
// Create a JTextField
JTextField textField = new JTextField(20);
// Set some text
textField.setText("This is read-only text.");
// Make the JTextField read-only
textField.setEditable(false);
// Add the JTextField to the JFrame
frame.add(textField);
// Display the JFrame
frame.setVisible(true);
}
}
Output:
Explanation Step-By-Step:
import javax.swing.*;
import java.awt.FlowLayout;
// Create a new JFrame
JFrame frame = new JFrame("Read Only JTextField Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLayout(new FlowLayout());
- A new JFrame is created, which is essentially a window with a title "Read Only JTextField Demo".
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ensures that when you close the JFrame (by clicking the close button), the entire application will shut down.
- frame.setSize(300, 200) sets the size of the frame to be 300 pixels wide and 200 pixels tall.
- frame.setLayout(new FlowLayout()) sets the layout manager of the frame to be FlowLayout. This means any components added to this frame will be arranged from left to right.
JTextField textField = new JTextField(20);
textField.setText("This is read-only text.");
textField.setEditable(false);
- A new JTextField is created with a width that approximately fits 20 columns of characters.
- setText method sets an initial text into the text field: "This is read-only text.". textField.setEditable(false) makes the JTextField read-only, so users cannot modify the content.
// Add the JTextField to the JFrame
frame.add(textField);
Comments
Post a Comment
Leave Comment