JTextField - potatoscript/JavaSwing GitHub Wiki
📝 JTextField in Java Swing
JTextField
1️⃣ Introduction to A JTextField is a GUI component in Java Swing used to accept single-line text input from the user.
JTextField
?
Why Use ✔️ Allows user input
✔️ Supports text editing, selection, and copying
✔️ Can be customized with font, size, color, and events
JTextField
2️⃣ Creating a Basic Example: Adding a Text Field to a JFrame
import javax.swing.*;
public class JTextFieldExample {
public static void main(String[] args) {
// Create JFrame
JFrame frame = new JFrame("JTextField Example");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create JTextField
JTextField textField = new JTextField("Enter text here...", 20);
// Add text field to frame
frame.add(textField);
// Make frame visible
frame.setVisible(true);
}
}
Explanation
✔️ new JTextField("Enter text here...", 20);
→ Creates a text field with placeholder text and a 20-character width.
✔️ frame.add(textField);
→ Adds the text field to the frame.
✔️ By default, text is left-aligned inside the field.
3️⃣ Getting and Setting Text
JTextField
Example: Read & Change Text in String inputText = textField.getText(); // Get user input
textField.setText("New text"); // Set new text
✔️ getText()
→ Returns the current text in the field.
✔️ setText("New text")
→ Updates the field content.
JTextField
Events with ActionListener
4️⃣ Handling When the Enter key is pressed inside a JTextField
, an ActionEvent
occurs.
Example: Detecting User Input
import javax.swing.*;
import java.awt.event.*;
public class JTextFieldEventExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTextField Event");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField(20);
JLabel label = new JLabel("Enter your name:");
// Add ActionListener
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input = textField.getText();
JOptionPane.showMessageDialog(frame, "Hello, " + input + "!");
}
});
// Add components to frame
JPanel panel = new JPanel();
panel.add(label);
panel.add(textField);
frame.add(panel);
frame.setVisible(true);
}
}
Explanation
✔️ textField.addActionListener()
→ Detects Enter key press.
✔️ JOptionPane.showMessageDialog()
→ Shows a pop-up with input.
JTextField
(Size, Color, Font)
5️⃣ Customizing JTextField
Example: Styling a textField.setFont(new Font("Arial", Font.BOLD, 14)); // Change font
textField.setForeground(Color.BLUE); // Text color
textField.setBackground(Color.LIGHT_GRAY); // Background color
textField.setHorizontalAlignment(JTextField.CENTER); // Center text
✔️ setFont(new Font("Arial", Font.BOLD, 14));
→ Changes font & size.
✔️ setForeground(Color.BLUE);
→ Changes text color.
✔️ setBackground(Color.LIGHT_GRAY);
→ Changes background color.
✔️ setHorizontalAlignment(JTextField.CENTER);
→ Aligns text inside the field.
JTextField
Read-Only
6️⃣ Disabling or Making Example: Disabling a Text Field
textField.setEditable(false); // User cannot type
textField.setEnabled(false); // Field is grayed out
✔️ setEditable(false);
→ Locks the field (user cannot edit).
✔️ setEnabled(false);
→ Disables the field (gray and non-editable).
7️⃣ Limiting Input Length
By default, JTextField
does not restrict input length. You need to manually limit it.
Example: Restricting Input to 10 Characters
import javax.swing.*;
import javax.swing.text.*;
public class JTextFieldLimitExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTextField Limit");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField(20);
// Limit input length to 10 characters
((AbstractDocument) textField.getDocument()).setDocumentFilter(new DocumentFilter() {
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
if ((fb.getDocument().getLength() + string.length()) <= 10) {
super.insertString(fb, offset, string, attr);
}
}
public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attr) throws BadLocationException {
if ((fb.getDocument().getLength() + string.length() - length) <= 10) {
super.replace(fb, offset, length, string, attr);
}
}
});
frame.add(textField);
frame.setVisible(true);
}
}
✔️ Uses DocumentFilter
to restrict input length.
JTextField
with JButton
8️⃣ Using Example: Get Text When Clicking a Button
import javax.swing.*;
import java.awt.event.*;
public class JTextFieldButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTextField & JButton");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField(15);
JButton button = new JButton("Submit");
JLabel label = new JLabel("Enter something:");
// Add ActionListener to button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input = textField.getText();
JOptionPane.showMessageDialog(frame, "You entered: " + input);
}
});
// Add components to frame
JPanel panel = new JPanel();
panel.add(label);
panel.add(textField);
panel.add(button);
frame.add(panel);
frame.setVisible(true);
}
}
✔️ button.addActionListener()
→ Reads JTextField
input when clicked.
✔️ Displays user input in a dialog box.
🔥 Summary
✅ JTextField
allows single-line text input.
✅ Use getText()
& setText()
to read and change text.
✅ Handle Enter key events with ActionListener
.
✅ Customize with fonts, colors, alignment, and size.
✅ Combine with JButton
for interactive input handling.
✅ Limit input length using DocumentFilter
.