2013-08-18 46 views
2

是否可以請求JWindow臨時焦點?有一種方法protected boolean requestFocusInWindow(boolean temporary),但該方法受到保護。如何請求JWindow臨時焦點? (Java 1.7)

+0

可以爲那些可獲得焦點(JTextComponents)JComponents是可能的,但你可能玩頂級容器,在這裏搜索@camickr關於AncestorListener的關於Dialog Focus/RequestFocusListener的帖子,這可能是你如何鎖定Focus的方式.... – mKorbel

+0

@mKorbel是的,你是對的。看看我的答案 - 找到新的解決方案:)自定義插入符號,當JTextField失去了焦點和臨時焦點請求父JWindow。 –

回答

2

已經找到了解決方案 - 類延伸的JWindow創建此方法:

@Override 
public boolean requestFocusInWindow(boolean temporary) { 
    return super.requestFocusInWindow(temporary); 
} 

現在我可以請求臨時焦點延伸JWindow組件。我使用它爲JTextField其中,如果選擇當彈出菜單可見改變插入顏色我的自定義彈出菜單(當然 - textField.setCaret(new HighlightCaret());是必要的):

private class HighlightCaret extends DefaultCaret { 

    private final Highlighter.HighlightPainter unfocusedPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.RED); 
    private final Highlighter.HighlightPainter focusedPainter = new DefaultHighlighter.DefaultHighlightPainter(new Color(10, 36, 106)); 
    private boolean isTemporary; 

    private HighlightCaret() { 
     setBlinkRate(500); 
    } 

    @Override 
    protected Highlighter.HighlightPainter getSelectionPainter() { 
     return isTemporary ? unfocusedPainter : focusedPainter; 
    } 

    @Override 
    public void setSelectionVisible(boolean hasFocus) { 
     super.setSelectionVisible(false); 
     if (hasFocus) { 
      super.setSelectionVisible(true); 
     } 
    } 

    @Override 
    public void focusGained(FocusEvent e) { 
     isTemporary = false; 
     super.focusGained(e); 
    } 

    @Override 
    public void focusLost(FocusEvent e) { 
     isTemporary = e.isTemporary(); 
     super.focusLost(e); 
    } 
}