JTextField AND JTextArea
In Java Swing (javax.swing), JTextField and JTextArea are commonly used for user text input. Below are their important properties, how to set/get values, and an example.
✅ 1. JTextField (Single-line Input)
Important Properties:
| Property | Method | Description |
|---|---|---|
| Set text | setText(String text) |
Set text in the field |
| Get text | getText() |
Get current text |
| Set columns | setColumns(int cols) |
Width of the text field (in columns) |
| Set editable | setEditable(boolean) |
Allow user editing or not |
| Set font | setFont(Font font) |
Set font style and size |
| Set foreground color | setForeground(Color c) |
Set text color |
| Set background color | setBackground(Color c) |
Set background color |
✅ 2. JTextArea (Multi-line Input)
Important Properties:
| Property | Method | Description |
|---|---|---|
| Set text | setText(String text) |
Set text in the area |
| Get text | getText() |
Get text |
| Set rows/columns | setRows(int), setColumns(int) |
Set size of the text area |
| Line wrap | setLineWrap(true) |
Automatically wrap lines |
| Wrap style | setWrapStyleWord(true) |
Wrap at word boundaries |
| Editable | setEditable(boolean) |
Allow editing |
✅ Full Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TextInputExample {
public static void main(String[] args) {
JFrame frame = new JFrame("TextField & TextArea Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
// JTextField
JTextField textField = new JTextField(20);
textField.setText("Enter your name");
textField.setFont(new Font("Arial", Font.PLAIN, 14));
// JTextArea
JTextArea textArea = new JTextArea(5, 20);
textArea.setText("Enter your message here...");
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setFont(new Font("Arial", Font.PLAIN, 14));
// Button to read input
JButton btn = new JButton("Submit");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = textField.getText();
String message = textArea.getText();
JOptionPane.showMessageDialog(frame, "Name: " + name + "\nMessage: " + message);
}
});
// Add components to frame
frame.add(new JLabel("Name:"));
frame.add(textField);
frame.add(new JLabel("Message:"));
frame.add(new JScrollPane(textArea)); // Use scroll pane for textarea
frame.add(btn);
frame.setVisible(true);
}
}
π Summary:
-
Use
setText()to set, andgetText()to retrieve values. -
Always use
JScrollPanewithJTextAreafor better UX. -
JTextFieldis for single-line input;JTextAreais for multi-line.
Would you like an example that stores the input into a file or database next?
Comments
Post a Comment