The Convert’s Guide to Java Swing: JTextField

This is several of the common code snippets for the Swing JTextField component in Java.

Text

jTextField1.setText("cat");
String text = jTextField1.getText();

Font

jTextField1.setFont(new Font("courier new",Font.ITALIC|Font.BOLD,24));

Background Color

jTextField1.setBackground(Color.red);

Select text (index range)

jTextField1.select(3,6); //highlight text at index 3, 4 and 5
jTextField1.requestFocus(); // if needed

Select text (everything)

jTextField1.selectAll();
jTextField1.requestFocus(); // if needed

Replace Text Selection (or insert at cursor)

jTextField1.replaceSelection("find"); //just inserts 'find' at cursor if nothing selected

Selected text color

jTextField1.setSelectedTextColor(Color.CYAN);

Cursor Location (text index)

jTextField1.setCaretPosition(5); //between text index 4 and 5

jTextField1.setCaretPosition(jTextField1.getText().length()); //set it to the end of the text

int cPos = jTextField1.getCaretPosition(); //between text index (cPos-1) and (cPos)

Cursor Location (pixel index)

Custom Paint a region of Text (by pixel index)

Custom Paint a region of Text (by text index)

Custom Paint the cursor/caret

Translate Text Index to Rendered Pixel Index

Change Cursor/Caret width

jTextField1.firePropertyChange("caretWidth", 0, 8); //8 is the new width, 0 is the "old" value that can't equal the new value

Change the blink rate of the cursor/caret

jTextField1.getCaret().setBlinkRate(100); //100 milliseconds between blinks, 500 is default

Selected text

int startIndex = jTextField1.getSelectionStart();
int endIndex = jTextField1.getSelectionEnd();

String text = jTextField1.getSelectedText();

Ensure a region of text is visible (by pixel)

jTextField1.setScrollOffset(100); //scroll region of visible rendered text to 100 pixels

jTextField1.setScrollOffset(0); //scroll to the beginning of the text

jTextField1.setScrollOffset(jTextField1.getHorizontalVisibility().getMaximum()); //scroll to the end of the text

Region of current visible text (in pixels)

int min = jTextField1.getHorizontalVisibility().getMinimum(); //probably 0
int value = jTextField1.getHorizontalVisibility().getValue(); //start of visible region
int extent = jTextField1.getHorizontalVisibility().getExtent(); //length of visible region
int max = jTextField1.getHorizontalVisibility().getMaximum(); //the total rendered text length

Alignment

jTextField1.setHorizontalAlignment(JTextField.RIGHT); // it is always vertically centered

Events

JTextComponent
JComponent
Container
Component