簡體   English   中英

在Java文本框中設置文本顏色

[英]Set the text color in a Java textbox

如何在運行時設置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);
    }
});

您確定已啟用JTextBox嗎? 您可以對其調用setEnabled(true)以確保。 不嘗試不禮貌,這只是最可能的原因(Swing中的代碼強制禁用的組件灰顯)。

如果仍不能解決問題,您還可以通過調用txtScheduleInfo.repaint()觸發重新繪制,這可能導致重新繪制。

如果上述兩種方法均無濟於事,則可以發布一些代碼,以便我們了解發生了什么。

試試這個代替

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

(唯一的變化是交換順序。現在您要在清除文本之前設置前景色。)

Swing通常不會執行此行為(當文本框獲得焦點以進行編輯時更改顏色)嗎? 嘗試禁用所有變色代碼,然后查看其是否正常運行。 如果您願意將代碼以可編譯的形式發布到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)

由於if語句中的條件,焦點事件偵聽器可能永遠不會觸發更改顏色。 此外,您知道調用該方法后無論如何都會獲得焦點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM