在Java文本框中设置文本颜色 [英] Set the text color in a Java textbox

查看:1543
本文介绍了在Java文本框中设置文本颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在运行时在Java Swing文本框中设置文本的颜色?在启动时,颜色是灰色的,当用户输入文本框时,我希望将颜色更改为正常的文本颜色。我目前使用以下代码:

How does one set the color of text in a Java Swing textbox at run-time? At startup, the color is grayish and when the user enters the textbox, I wish to change the color to the normal text color. I am currently using the following code:

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

此时,当代码运行时,

At this time, when the code runs, the text still shows up in gray.

其他代码:

声明(作为字段):

Additional Code:
Declaration (as a field):

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


推荐答案


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

(唯一的变化是交换订单。 '在清除文本之前设置前景颜色。)

(The only change is swapping the order. Now you're setting the foreground colour before clearing the text.)

这篇关于在Java文本框中设置文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆