4.6 Enabling and Disabling
Every control has an associated property called its enabled state. A control whose enabled state is false is said to be disabled, and the act of setting the enabled state to false is called disabling the control. A control whose enabled state is true is said to be enabled, and the act of setting the enabled state to true is called enabling the control. When a control is enabled, it responds to mouse clicks, takes focus, and handles key presses. A disabled control is unresponsive to events and typically draws using a "grayed" look. When a parent control is disabled, all children of the control will behave as though they are disabled.
setEnabled(boolean enabled)
Enables or disables the control, depending on the boolean argument. getEnabled()
Returns true if the control is enabled and false if it is disabled. isEnabled()
Returns true if the control and all ancestors are enabled, or false if it or any of its ancestors is disabled.
|
As is true of getVisible() and isVisible(), despite their JavaBeans naming convention, these methods are not equivalent. |
Disabling a control causes the mouse events that were to be delivered to the control to be delivered to the parent instead. This makes sense because a disabled control should never process the mouse. Interestingly, this behavior can be used to intercept mouse events for a control.
4.6.1 Using setEnabled() to Intercept Mouse Events
The following example allows the user to drag a button by disabling the parent, causing mouse events to be delivered to the shell. Mouse listeners on the shell determine whether the mouse was pressed inside the button and drag the button when the mouse is moved.
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
Composite composite = new Composite(shell, SWT.NULL);
composite.setEnabled(false);
final Button button = new Button(composite, SWT.PUSH);
button.setText("Drag Me");
button.pack();
Listener listener = new Listener() {
Point offset = null;
public void handleEvent(Event e) {
switch (e.type) {
case SWT.MouseDown:
Rectangle rect = button.getBounds();
if (!rect.contains(e.x, e.y)) break;
Point pt = button.getLocation();
offset = new Point(e.x-pt.x, e.y-pt.y);
break;
case SWT.MouseMove:
if (offset == null) break;
button.setLocation(
e.x - offset.x,
e.y - offset.y);
break;
case SWT.MouseUp:
offset = null;
break;
}
}
};
shell.addListener(SWT.MouseDown, listener);
shell.addListener(SWT.MouseUp, listener);
shell.addListener(SWT.MouseMove, listener);
shell.setSize(300, 300);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
|