如何在运行时设置Java Swing文本框中的文本颜色?启动时,颜色是灰色的,当用户输入文本框时,我希望将颜色更改为普通文本颜色。我目前使用下面的代码:在Java文本框中设置文本颜色
private void txtScheduleInfoFocusGained(java.awt.event.FocusEvent evt)
{
try
{
if (currentClassIsNewClass() && txtScheduleInfo.getDocument().getText(0, txtScheduleInfo.getDocument().getLength()).equals(PASTE_SI_HERE))
{
txtScheduleInfo.setText("");
txtScheduleInfo.setForeground(java.awt.SystemColor.textText);
}
}
catch (BadLocationException ex)
{
JOptionPane.showMessageDialog(this, "BLE\nContact Zian", "Unexpected Problem", JOptionPane.ERROR_MESSAGE);
}
}
此时,代码运行时,文本仍然显示为灰色。
附加代码:
声明(如字段):
private javax.swing.JTextPane txtScheduleInfo;
实例化:
txtScheduleInfo = new javax.swing.JTextPane();
初始化:
txtScheduleInfo.setForeground(java.awt.SystemColor.textInactiveText);
txtScheduleInfo.setText("Paste schedule information here");
txtScheduleInfo.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
txtScheduleInfoFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
txtScheduleInfoFocusLost(evt);
}
});
你可以发布一个更完整的例子吗? – willcodejavaforfood 2009-05-22 23:52:23
我已经做到了。 – 2009-05-23 21:29:23