2009-05-22 118 views
0

如何在运行时设置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); 
    } 
}); 
+0

你可以发布一个更完整的例子吗? – willcodejavaforfood 2009-05-22 23:52:23

+0

我已经做到了。 – 2009-05-23 21:29:23

回答

1

试试这个,而不是

private void txtScheduleInfoFocusGained(java.awt.event.FocusEvent evt)            
    {             
     try 
     { 
      if (currentClassIsNewClass() && txtScheduleInfo.getDocument().getText(0, txtScheduleInfo.getDocument().getLength()).equals(PASTE_SI_HERE)) 
      { 
       txtScheduleInfo.setForeground(java.awt.SystemColor.textText); 
       txtScheduleInfo.setText(""); 
      } 
     } 
     catch (BadLocationException ex) 
     { 
      JOptionPane.showMessageDialog(this, "BLE\nContact Zian", "Unexpected Problem", JOptionPane.ERROR_MESSAGE); 
     } 
    } 

(唯一的变化是交换的顺序。现在你清除设置文本之前前景色。)

2

你确保JTextBox启用?您可以拨打setEnabled(true)来确认。不要试图粗鲁,这只是最有可能的原因(Swing中的代码强制禁用已禁用组件)。

如果这样不能解决问题,还可以通过调用txtScheduleInfo.repaint()来触发重绘,这可能会导致重绘。

如果这些都无济于事,可以发布一些代码,以便我们可以看到发生了什么。

0

不能正常摆动执行此行为(当文本框获得焦点进行编辑时更改颜色)?尝试禁用所有颜色更改代码并查看它是否正常工作。 如果您愿意以PasteBin的可编译形式发布代码,其他人实际上也可以进行全面调试。

其他东西我可以建议:

  • 检查java.awt.SystemColor.textText真的是你想要的颜色(它的使用方法来获取十六进制颜色,然后在颜色选择器显示它)
  • 删除行txtScheduleInfo.setForeground(java.awt.SystemColor.textInactiveText);,因为它可能以某种方式覆盖默认的绘画,如果你的焦点处理程序被破坏。
  • 更换
    if (currentClassIsNewClass() && txtScheduleInfo.getDocument().getText(0, txtScheduleInfo.getDocument().getLength()).equals(PASTE_SI_HERE))
    if(true)

你的焦点事件侦听器可能永远不会被触发改变颜色因,如果语句的条件。此外,当你调用该方法时,你知道重点已经获得了。