我有一个带有一些JTextField的框架,供用户插入一些值.
打开窗口时,文本字段已用灰色写出用户应在该容器中写的内容,例如“以秒为单位的值” …
当用户开始在JTextFields中写入内容时,我想将这些字母的颜色(我认为是前景)更改为深色,并将用户写入的内容保存到String中.
解决方法:
对于颜色更改,您必须实现一个FocusListener,它使用setForeground()设置前景.如果要使用JTextField当前内容的字符串,则可以使用基础文档的DocumentListener来实现.
参见以下代码作为示例(我将蓝色和红色用作颜色,并将tf的Text值存储在String内容中):
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);
}
});
一个完整的工作示例在这里:
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();
}
}