Java 实施";选择“聚焦”;Eclipse文本控件的行为 球门
我正在尝试为Eclipse控件实现“聚焦选择”行为:Java 实施";选择“聚焦”;Eclipse文本控件的行为 球门,java,eclipse,textbox,swt,eclipse-3.6,Java,Eclipse,Textbox,Swt,Eclipse 3.6,我正在尝试为Eclipse控件实现“聚焦选择”行为: 当控件已聚焦时: 单击和拖动的行为正常 当控件未聚焦时: 单击并拖动以选择文本的行为正常 单击而不选择文本将选择所有文本 使用键盘对焦将选择所有文本 问题 只需为SWT.FocusIn选择所有文本,鼠标单击对焦时不会选择文本 SWT.FocusIn在SWT.MouseDown之前被触发,因此当用户按下鼠标时,无法判断控件是否已经有焦点 问题 为什么Eclipse会按这种顺序触发事件?那对我来说毫无意义。这是对某些受支持操作
- 当控件已聚焦时:
- 单击和拖动的行为正常
- 当控件未聚焦时:
- 单击并拖动以选择文本的行为正常
- 单击而不选择文本将选择所有文本
- 使用键盘对焦将选择所有文本
- 只需为
选择所有文本,鼠标单击对焦时不会选择文本SWT.FocusIn
在SWT.FocusIn
之前被触发,因此当用户按下鼠标时,无法判断控件是否已经有焦点SWT.MouseDown
很高兴你找到了答案。将对此进行书签以备将来使用。很高兴您找到了答案。将对此设置书签以备将来使用。
/**
* This method adds select-on-focus functionality to a {@link Text} component.
*
* Specific behavior:
* - when the Text is already focused -> normal behavior
* - when the Text is not focused:
* -> focus by keyboard -> select all text
* -> focus by mouse click -> select all text unless user manually selects text
*
* @param text
*/
public static void addSelectOnFocusToText(Text text) {
Listener listener = new Listener() {
private boolean hasFocus = false;
private boolean hadFocusOnMousedown = false;
@Override
public void handleEvent(Event e) {
switch(e.type) {
case SWT.FocusIn: {
Text t = (Text) e.widget;
// Covers the case where the user focuses by keyboard.
t.selectAll();
// The case where the user focuses by mouse click is special because Eclipse,
// for some reason, fires SWT.FocusIn before SWT.MouseDown, and on mouse down
// it cancels the selection. So we set a variable to keep track of whether the
// control is focused (can't rely on isFocusControl() because sometimes it's wrong),
// and we make it asynchronous so it will get set AFTER SWT.MouseDown is fired.
t.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
hasFocus = true;
}
});
break;
}
case SWT.FocusOut: {
hasFocus = false;
((Text) e.widget).clearSelection();
break;
}
case SWT.MouseDown: {
// Set the variable which is used in SWT.MouseUp.
hadFocusOnMousedown = hasFocus;
break;
}
case SWT.MouseUp: {
Text t = (Text) e.widget;
if(t.getSelectionCount() == 0 && !hadFocusOnMousedown) {
((Text) e.widget).selectAll();
}
break;
}
}
}
};
text.addListener(SWT.FocusIn, listener);
text.addListener(SWT.FocusOut, listener);
text.addListener(SWT.MouseDown, listener);
text.addListener(SWT.MouseUp, listener);
}