交叉发布:https://forums.oracle.com/forums/thread.jspa?threadID=2512538&tstart=0
各位大家好。
有没有办法以编程方式刷新待处理的AWT事件?我希望能够在这样的代码中使用它:
if (comp.requestFocusInWindow())
{
// flush pending AWT events...
KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
if (focusManager.getPermanentFocusOwner() == comp)
{
// do something...
}
}
谢谢。
马科斯
PS:我知道我可以在comp中使用FocusListener,但在我的情况下它不是一个选项。
更新
我的问题的本质是这样的:关注JTable 的实际编辑组件开始编辑的键被分派给它。所以我提出了这个解决方案:
private class TextFieldColumnEditor extends MyCustomTextField
{
// TODO
private static final long serialVersionUID = 1L;
private FocusListener _keyDispatcher;
@Override
protected boolean processKeyBinding(final KeyStroke ks, final KeyEvent e, int condition, boolean pressed)
{
InputMap bindings = getInputMap(condition);
ActionMap actions = getActionMap();
if (bindings != null && actions != null && isEnabled())
{
Object binding = bindings.get(ks);
final Action action = binding == null ? null : actions.get(binding);
if (action != null)
{
if (!isFocusOwner() && requestFocusInWindow())
{
// In case something went wrong last time and the
// listener wasn't unregistered.
removeFocusListener(_keyDispatcher);
_keyDispatcher =
new FocusListener()
{
@Override
public void focusGained(FocusEvent evt)
{
removeFocusListener(this);
SwingUtilities.invokeLater(
new Runnable()
{
@Override
public void run()
{
SwingUtilities.notifyAction(action, ks, e, CampoTextoDadosEditorColuna.this, e.getModifiers());
}
}
);
}
@Override
public void focusLost(FocusEvent e)
{
}
};
addFocusListener(_keyDispatcher);
return true;
}
else
{
return SwingUtilities.notifyAction(action, ks, e, this, e.getModifiers());
}
}
}
return false;
}
类TextFieldColumnEditor是我在自定义单元格编辑器中使用的组件。正如您所看到的,解决方案并不完美,原因很多:
我暂时坚持使用这个解决方案。您的意见和建议将不胜感激。
马科斯
更新2
最终(简化)版本,经@VGR建议:
private class CellEditorTextField extends JTextField
{
@Override
protected boolean processKeyBinding(final KeyStroke ks, final KeyEvent e, int condition, boolean pressed)
{
InputMap bindings = getInputMap(condition);
ActionMap actions = getActionMap();
if (bindings != null && actions != null && isEnabled())
{
Object binding = bindings.get(ks);
final Action action = binding == null ? null : actions.get(binding);
if (action != null)
{
if (e.getSource() == YourJTable.this && action.isEnabled() && requestFocusInWindow())
{
SwingUtilities.invokeLater(
new Runnable()
{
@Override
public void run()
{
SwingUtilities.notifyAction(action, ks, e, CellEditorTextField.this, e.getModifiers());
}
}
);
return true;
}
else
{
return SwingUtilities.notifyAction(action, ks, e, this, e.getModifiers());
}
}
}
return false;
}
}
赞赏评论和改进。