JTextField: Change the foreground color and save the content
Solution 1
For the colour change you have to implement a FocusListener
which sets the foreground with setForeground()
. If you want to have a String of the current content of the JTextField
you can achieve this with a DocumentListener
to the underlying Document
.
See this code as an example (I use blue and red for the colour and store the Text value of tf
in the String
content):
JTextField tf = new JTextFiedl();
tf.addFocusListener(new FocusListener()
{
@Override
public void focusGained(FocusEvent fe)
{
tf.setForeground(INACTIVE_COLOUR);
}
@Override
public void focusLost(FocusEvent fe)
{
tf.setForeground(ACTIVE_COLOUR);
}
});
A full working example is here:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TF
{
private final Color ACTIVE_COLOUR = Color.BLUE;
private final Color INACTIVE_COLOUR = Color.RED;
private String content; //text of the text field is stored here
private JTextField tf;
private JTextField lbl;
public TF()
{
JFrame mainFrame = new JFrame("Window");
tf = new JTextField("Hint");
lbl = new JTextField("click here to change focus");
tf.setForeground(ACTIVE_COLOUR);
setListeners();
mainFrame.add(tf, BorderLayout.NORTH);
mainFrame.add(lbl, BorderLayout.SOUTH);
mainFrame.pack();
mainFrame.setVisible(true);
}
private void setListeners()
{
tf.addFocusListener(new FocusListener()
{
@Override
public void focusGained(FocusEvent fe)
{
tf.setForeground(INACTIVE_COLOUR);
}
@Override
public void focusLost(FocusEvent fe)
{
tf.setForeground(ACTIVE_COLOUR);
}
});
tf.getDocument().addDocumentListener(new DocumentListener()
{
@Override
public void removeUpdate(DocumentEvent de)
{
content = tf.getText();
}
@Override
public void insertUpdate(DocumentEvent de)
{
content = tf.getText();
}
@Override
public void changedUpdate(DocumentEvent de)
{
content = tf.getText();
}
});
}
public static void main(String[] args)
{
TF tf = new TF();
}
}
Solution 2
See Text Prompt for another approach.
user2144555
Updated on June 17, 2022Comments
-
user2144555 almost 2 years
I have a frame with some
JTextFields
for the user insert some values. When the window is opened, the text fields have written, in gray, what the user should write in that container, like "value in seconds"...I want to change the color of those letters (I think it is the foreground) to dark when the user starts to write in the
JTextFields
, and save to aString
what is written by the user.