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();
}
}