是否可以请求JWindow临时焦点?有方法protected boolean requestFocusInWindow(boolean temporary)
,但该方法受保护。
最佳答案
已经找到了解决方案-在扩展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);
}
}