1 回答

TA貢獻1900條經驗 獲得超5個贊
問題在于你如何操縱繪畫。在changeColorOnFocus(由 調用FocusListener)方法內部有以下幾行:
if (c.getGraphics() != null) {
? ? c.paint(c.getGraphics());
}
在這里,您使用圖形并在負責組件繪畫層次結構中繪畫的方法之外進行一種自定義繪畫。我希望我能更好地解釋它,但長話短說,Graphics只使用將它們作為參數提供給您的方法(并調用其super方法)。在UI類中方法是paintSafely,在組件中是paintComponent。它們都給你Graphics對象,因此它們適合定制繪畫。
因此,解決方案是在您的內部FocusListener添加一個標志,以便了解組件是否獲得焦點,并調用changeColorOnFocus內部paintSafely(Graphics g)方法。您的 UI 類應該在以下部分中進行更改(我不會全部粘貼,因為它有點大)。
private boolean focused; //a field
protected class FocusListenerColorLine implements FocusListener {
? ? @Override
? ? public void focusGained(FocusEvent e) {
? ? ? ? firePropertyChange(PROPERTY_LINE_COLOR, colorLineInactive, colorLineActive);
? ? ? ? focused = true;
? ? }
? ? @Override
? ? public void focusLost(FocusEvent e) {
? ? ? ? firePropertyChange(PROPERTY_LINE_COLOR, colorLineActive, colorLineInactive);
? ? ? ? focused = false;
? ? }
}
@Override
public void paintSafely(Graphics g) {
? ? super.paintSafely(g);
? ? paintLine(g);
? ? changeColorOnFocus(g);
}
protected void changeColorOnFocus(Graphics g) {
? ? boolean hasFocus = focused;
? ? JTextComponent c = getComponent();
? ? if (c == null) {
? ? ? ? return;
? ? }
? ? if (hasFocus && (activeBackground != null) && (activeForeground != null)) {
? ? ? ? logicForChangeColorOnFocus(c, activeBackground, activeForeground);
? ? ? ? //TODO create a new changePropriety
? ? ? ? paintLine(c.getGraphics());
? ? }
? ? if (!hasFocus && (inactiveBackground != null) && (inactiveForeground != null)) {
? ? ? ? logicForChangeColorOnFocus(c, inactiveBackground, inactiveForeground);
? ? ? ? paintLine(c.getGraphics());
? ? }
}
添加回答
舉報