【发布时间】:2010-10-28 08:57:24
【问题描述】:
如何在运行时设置 Java Swing 文本框中的文本颜色?在启动时,颜色是灰色的,当用户进入文本框时,我希望将颜色更改为正常的文本颜色。我目前正在使用以下代码:
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);
}
});
【问题讨论】:
-
你能发布一个更完整的例子吗?
-
您是否在运行时使用调试器检查过您的条件是否为真?
-
是的,我做到了。