org.eclipse.swt.widgets.Button Maven / Gradle / Ivy
/******************************************************************************* * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.swt.widgets; import org.eclipse.swt.*; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.internal.cocoa.*; /** * Instances of this class represent a selectable user interface object that * issues notification when pressed and released. *
,*
*- Styles:
*- ARROW, CHECK, PUSH, RADIO, TOGGLE, FLAT, WRAP
*- UP, DOWN, LEFT, RIGHT, CENTER
*- Events:
*- Selection
** Note: Only one of the styles ARROW, CHECK, PUSH, RADIO, and TOGGLE * may be specified. *
* Note: Only one of the styles LEFT, RIGHT, and CENTER may be specified. *
* Note: Only one of the styles UP, DOWN, LEFT, and RIGHT may be specified * when the ARROW style is specified. *
* IMPORTANT: This class is not intended to be subclassed. *
* * @see Button snippets * @see SWT Example: ControlExample * @see Sample code and further information * @noextend This class is not intended to be subclassed by clients. */ public class Button extends Control { String text; Image image; boolean grayed; static final int EXTRA_HEIGHT = 2; static final int EXTRA_WIDTH = 6; static final int IMAGE_GAP = 2; static final int SMALL_BUTTON_HEIGHT = 28; static final int REGULAR_BUTTON_HEIGHT = 32; static final int MAX_SIZE = 40000; /** * Constructs a new instance of this class given its parent * and a style value describing its behavior and appearance. ** The style value is either one of the style constants defined in * class
* * @param parent a composite control which will be the parent of the new instance (cannot be null) * @param style the style of control to construct * * @exception IllegalArgumentExceptionSWT
which is applicable to instances of this * class, or must be built by bitwise OR'ing together * (that is, using theint
"|" operator) two or more * of thoseSWT
style constants. The class description * lists the style constants that are applicable to the class. * Style bits are also inherited from superclasses. **
* @exception SWTException- ERROR_NULL_ARGUMENT - if the parent is null
**
* * @see SWT#ARROW * @see SWT#CHECK * @see SWT#PUSH * @see SWT#RADIO * @see SWT#TOGGLE * @see SWT#FLAT * @see SWT#UP * @see SWT#DOWN * @see SWT#LEFT * @see SWT#RIGHT * @see SWT#CENTER * @see Widget#checkSubclass * @see Widget#getStyle */ public Button (Composite parent, int style) { super (parent, checkStyle (style)); } /** * Adds the listener to the collection of listeners who will * be notified when the control is selected by the user, by sending * it one of the messages defined in the- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent
*- ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass
*SelectionListener
* interface. **
*widgetSelected
is called when the control is selected by the user. *widgetDefaultSelected
is not called. ** When the
* * @param listener the listener which should be notified * * @exception IllegalArgumentExceptionSWT.RADIO
style bit is set, thewidgetSelected
method is * also called when the receiver loses selection because another item in the same radio group * was selected by the user. DuringwidgetSelected
the application can use *getSelection()
to determine the current selected state of the receiver. **
* @exception SWTException- ERROR_NULL_ARGUMENT - if the listener is null
**
* * @see SelectionListener * @see #removeSelectionListener * @see SelectionEvent */ public void addSelectionListener(SelectionListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener(listener); addListener(SWT.Selection,typedListener); addListener(SWT.DefaultSelection,typedListener); } @Override NSSize cellSizeForBounds (long /*int*/ id, long /*int*/ sel, NSRect cellFrame) { NSSize size = super.cellSizeForBounds(id, sel, cellFrame); if (image != null && ((style & (SWT.CHECK|SWT.RADIO)) !=0)) { NSSize imageSize = image.handle.size(); size.width += imageSize.width + IMAGE_GAP; size.height = Math.max(size.height, imageSize.height); } if (((style & (SWT.PUSH|SWT.TOGGLE)) !=0) && (style & (SWT.FLAT|SWT.WRAP)) == 0) { if (image != null) { NSCell cell = new NSCell(id); if (cell.controlSize() == OS.NSSmallControlSize) size.height += EXTRA_HEIGHT; } // TODO: Why is this necessary? size.width += EXTRA_WIDTH; } if ((style & SWT.WRAP) != 0 && text.length() != 0 && cellFrame.width < MAX_SIZE) { NSCell cell = new NSCell (id); NSRect titleRect = cell.titleRectForBounds(cellFrame); NSSize wrapSize = new NSSize(); wrapSize.width = titleRect.width; wrapSize.height = MAX_SIZE; NSAttributedString attribStr = createString(text, null, foreground, style, true, true, true); NSRect rect = attribStr.boundingRectWithSize(wrapSize, OS.NSStringDrawingUsesLineFragmentOrigin); attribStr.release(); double /*float*/ trimHeight = size.height - titleRect.height; size.height = rect.height; if (image != null && ((style & (SWT.CHECK|SWT.RADIO)) !=0)) { NSSize imageSize = image.handle.size(); size.height = Math.max(size.height, imageSize.height); } size.height += trimHeight; } return size; } static int checkStyle (int style) { style = checkBits (style, SWT.PUSH, SWT.ARROW, SWT.CHECK, SWT.RADIO, SWT.TOGGLE, 0); if ((style & (SWT.PUSH | SWT.TOGGLE)) != 0) { return checkBits (style, SWT.CENTER, SWT.LEFT, SWT.RIGHT, 0, 0, 0); } if ((style & (SWT.CHECK | SWT.RADIO)) != 0) { return checkBits (style, SWT.LEFT, SWT.RIGHT, SWT.CENTER, 0, 0, 0); } if ((style & SWT.ARROW) != 0) { style |= SWT.NO_FOCUS; return checkBits (style, SWT.UP, SWT.DOWN, SWT.LEFT, SWT.RIGHT, 0, 0); } return style; } void click () { sendSelectionEvent (SWT.Selection); } @Override public Point computeSize (int wHint, int hHint, boolean changed) { checkWidget(); if ((style & SWT.ARROW) != 0) { // TODO use some OS metric instead of hardcoded values int width = wHint != SWT.DEFAULT ? wHint : 14; int height = hHint != SWT.DEFAULT ? hHint : 14; return new Point (width, height); } NSSize size = null; NSCell cell = ((NSButton)view).cell (); if ((style & SWT.WRAP) != 0 && wHint != SWT.DEFAULT) { NSRect rect = new NSRect (); rect.width = wHint; rect.height = hHint != SWT.DEFAULT ? hHint : MAX_SIZE; size = cell.cellSizeForBounds (rect); } else { size = cell.cellSize (); } int width = (int)Math.ceil (size.width); int height = (int)Math.ceil (size.height); if (wHint != SWT.DEFAULT) width = wHint; if (hHint != SWT.DEFAULT) height = hHint; return new Point (width, height); } NSAttributedString createString() { NSAttributedString attribStr = createString(text, null, foreground, style, false, true, true); attribStr.autorelease(); return attribStr; } @Override void createHandle () { if ((style & SWT.PUSH) == 0) state |= THEME_BACKGROUND; NSButton widget = (NSButton)new SWTButton().alloc(); widget.init(); NSButtonCell cell = (NSButtonCell)new SWTButtonCell ().alloc ().init (); widget.setCell (cell); cell.release (); if ((style & (SWT.PUSH | SWT.TOGGLE)) != 0 && (style & SWT.FLAT) == 0) { NSView superview = parent.view; while (superview != null) { if (superview.isKindOfClass(OS.class_NSTableView)) { style |= SWT.FLAT; break; } superview = superview.superview(); } } int type = OS.NSMomentaryLightButton; if ((style & SWT.PUSH) != 0) { if ((style & SWT.FLAT) != 0) { widget.setBezelStyle(OS.NSShadowlessSquareBezelStyle); } else { widget.setBezelStyle((style & SWT.WRAP) != 0 ? OS.NSRegularSquareBezelStyle : OS.NSRoundedBezelStyle); } } else if ((style & SWT.CHECK) != 0) { type = OS.NSSwitchButton; } else if ((style & SWT.RADIO) != 0) { type = OS.NSRadioButton; } else if ((style & SWT.TOGGLE) != 0) { type = OS.NSPushOnPushOffButton; if ((style & SWT.FLAT) != 0) { widget.setBezelStyle(OS.NSShadowlessSquareBezelStyle); } else { widget.setBezelStyle((style & SWT.WRAP) != 0 ? OS.NSRegularSquareBezelStyle : OS.NSRoundedBezelStyle); } } else if ((style & SWT.ARROW) != 0) { widget.setBezelStyle(OS.NSShadowlessSquareBezelStyle); } widget.setButtonType(type); widget.setTitle(NSString.string()); widget.setImagePosition(OS.NSImageLeft); widget.setTarget(widget); widget.setAction(OS.sel_sendSelection); view = widget; _setAlignment(style); } @Override void createWidget() { text = ""; super.createWidget (); } @Override Font defaultFont () { return Font.cocoa_new (display, defaultNSFont ()); } @Override NSFont defaultNSFont() { NSCell cell = ((NSControl)view).cell(); return NSFont.systemFontOfSize (NSFont.systemFontSizeForControlSize (cell.controlSize())); } @Override void deregister () { super.deregister (); display.removeWidget(((NSControl)view).cell()); } @Override boolean dragDetect(int x, int y, boolean filter, boolean[] consume) { boolean dragging = super.dragDetect(x, y, filter, consume); consume[0] = dragging; return dragging; } @Override void drawImageWithFrameInView (long /*int*/ id, long /*int*/ sel, long /*int*/ image, NSRect rect, long /*int*/ view) { /* * Feature in Cocoa. Images touch the edge of rounded buttons * when set to small size. The fix to subclass the button cell * and offset the image drawing. * This workaround is not required for OSX 10.9 and later as * the problem doesn't happen there. */ if (OS.VERSION_MMB < OS.VERSION_MMB(10, 9, 0)) { NSCell cell = ((NSControl)this.view).cell(); if (cell != null && cell.controlSize() == OS.NSRegularControlSize) { if ((style & (SWT.PUSH | SWT.TOGGLE)) != 0 && (style & (SWT.FLAT | SWT.WRAP)) == 0) { rect.y += EXTRA_HEIGHT / 2; rect.height += EXTRA_HEIGHT; } } } super.drawImageWithFrameInView(id, sel, image, rect, view); } @Override void drawInteriorWithFrame_inView (long /*int*/ id, long /*int*/ sel, NSRect cellRect, long /*int*/ viewid) { if ((style & (SWT.CHECK|SWT.RADIO)) != 0 && backgroundImage != null) { fillBackground (new NSView(viewid), NSGraphicsContext.currentContext(), cellRect, -1); } super.drawInteriorWithFrame_inView(id, sel, cellRect, viewid); if (image != null && ((style & (SWT.CHECK|SWT.RADIO)) !=0)) { NSSize imageSize = image.handle.size(); NSCell nsCell = new NSCell(id); double /*float*/ x = 0; double /*float*/ y = (imageSize.height - cellRect.height)/2f; NSRect imageRect = nsCell.imageRectForBounds(cellRect); NSSize stringSize = ((NSButton)view).attributedTitle().size(); switch (style & (SWT.LEFT|SWT.RIGHT|SWT.CENTER)) { case SWT.LEFT: x = imageRect.x + imageRect.width + IMAGE_GAP; break; case SWT.CENTER: x = cellRect.x + imageRect.x + imageRect.width + ((cellRect.width-stringSize.width)/2f) - imageSize.width - IMAGE_GAP; break; case SWT.RIGHT: x = cellRect.x + cellRect.width - stringSize.width - imageSize.width - IMAGE_GAP; break; } NSRect destRect = new NSRect(); destRect.x = x; destRect.y = y; destRect.width = imageSize.width; destRect.height = imageSize.height; NSGraphicsContext.static_saveGraphicsState(); NSAffineTransform transform = NSAffineTransform.transform(); transform.scaleXBy(1, -1); transform.translateXBy(0, -imageSize.height); transform.concat(); image.handle.drawInRect(destRect, new NSRect(), OS.NSCompositeSourceOver, 1); NSGraphicsContext.static_restoreGraphicsState(); } } @Override NSRect drawTitleWithFrameInView (long /*int*/ id, long /*int*/ sel, long /*int*/ title, NSRect titleRect, long /*int*/ view) { boolean wrap = (style & SWT.WRAP) != 0 && text.length() != 0; if (wrap) { NSSize wrapSize = new NSSize(); wrapSize.width = titleRect.width; wrapSize.height = MAX_SIZE; NSAttributedString attribStr = createString(text, null, foreground, style, true, true, true); NSRect rect = attribStr.boundingRectWithSize(wrapSize, OS.NSStringDrawingUsesLineFragmentOrigin); switch (style & (SWT.LEFT | SWT.RIGHT | SWT.CENTER)) { case SWT.LEFT: rect.x = titleRect.x; break; case SWT.CENTER: rect.x = titleRect.x + (titleRect.width - rect.width) / 2f; break; case SWT.RIGHT: rect.x = titleRect.x + titleRect.width - rect.width; break; } rect.y = titleRect.y + (titleRect.height - rect.height) / 2; attribStr.drawInRect(rect); attribStr.release (); return rect; } return super.drawTitleWithFrameInView(id, sel, title, titleRect, view); } @Override boolean drawsBackground() { return background != null || backgroundImage != null; } @Override void drawWidget (long /*int*/ id, NSGraphicsContext context, NSRect rect) { if ((style & SWT.ARROW) != 0) { NSRect frame = view.frame(); int arrowSize = Math.min((int)frame.height, (int)frame.width) / 2; context.saveGraphicsState(); NSPoint p1 = new NSPoint(); p1.x = -arrowSize / 2; p1.y = -arrowSize / 2; NSPoint p2 = new NSPoint(); p2.x = arrowSize / 2; p2.y = p1.y; NSPoint p3 = new NSPoint(); p3.y = arrowSize / 2; NSBezierPath path = NSBezierPath.bezierPath(); path.moveToPoint(p1); path.lineToPoint(p2); path.lineToPoint(p3); path.closePath(); NSAffineTransform transform = NSAffineTransform.transform(); if ((style & SWT.LEFT) != 0) { transform.rotateByDegrees(90); } else if ((style & SWT.UP) != 0) { transform.rotateByDegrees(180); } else if ((style & SWT.RIGHT) != 0) { transform.rotateByDegrees(-90); } path.transformUsingAffineTransform(transform); transform = NSAffineTransform.transform(); transform.translateXBy(frame.width / 2, frame.height / 2); path.transformUsingAffineTransform(transform); NSColor color = isEnabled() ? NSColor.blackColor() : NSColor.disabledControlTextColor(); color.set(); path.fill(); context.restoreGraphicsState(); } super.drawWidget (id, context, rect); } @Override NSRect focusRingMaskBoundsForFrame (long /*int*/ id, long /*int*/ sel, NSRect cellFrame, long /*int*/ view) { return cellFrame; } /** * Returns a value which describes the position of the * text or image in the receiver. The value will be one of *- ERROR_WIDGET_DISPOSED - if the receiver has been disposed
*- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
*LEFT
,RIGHT
orCENTER
* unless the receiver is anARROW
button, in * which case, the alignment will indicate the direction of * the arrow (one ofLEFT
,RIGHT
, *UP
orDOWN
). * * @return the alignment * * @exception SWTException*
*/ public int getAlignment () { checkWidget (); if ((style & SWT.ARROW) != 0) { if ((style & SWT.UP) != 0) return SWT.UP; if ((style & SWT.DOWN) != 0) return SWT.DOWN; if ((style & SWT.LEFT) != 0) return SWT.LEFT; if ((style & SWT.RIGHT) != 0) return SWT.RIGHT; return SWT.UP; } if ((style & SWT.LEFT) != 0) return SWT.LEFT; if ((style & SWT.CENTER) != 0) return SWT.CENTER; if ((style & SWT.RIGHT) != 0) return SWT.RIGHT; return SWT.LEFT; } /** * Returns- ERROR_WIDGET_DISPOSED - if the receiver has been disposed
*- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
*true
if the receiver is grayed, * and false otherwise. When the widget does not have * theCHECK
style, return false. * * @return the grayed state of the checkbox * * @exception SWTException*
* * @since 3.4 */ public boolean getGrayed() { checkWidget (); if ((style & SWT.CHECK) == 0) return false; return grayed; } /** * Returns the receiver's image if it has one, or null * if it does not. * * @return the receiver's image * * @exception SWTException- ERROR_WIDGET_DISPOSED - if the receiver has been disposed
*- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
**
*/ public Image getImage () { checkWidget(); return image; } @Override String getNameText () { return getText (); } /** * Returns- ERROR_WIDGET_DISPOSED - if the receiver has been disposed
*- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
*true
if the receiver is selected, * and false otherwise. ** When the receiver is of type
CHECK
orRADIO
, * it is selected when it is checked. When it is of typeTOGGLE
, * it is selected when it is pushed in. If the receiver is of any other type, * this method returns false. * * @return the selection state * * @exception SWTException*
*/ public boolean getSelection () { checkWidget (); if ((style & (SWT.CHECK | SWT.RADIO | SWT.TOGGLE)) == 0) return false; if ((style & SWT.CHECK) != 0 && grayed) return ((NSButton)view).state() == OS.NSMixedState; return ((NSButton)view).state() == OS.NSOnState; } /** * Returns the receiver's text, which will be an empty * string if it has never been set or if the receiver is * an- ERROR_WIDGET_DISPOSED - if the receiver has been disposed
*- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
*ARROW
button. * * @return the receiver's text * * @exception SWTException*
*/ public String getText () { checkWidget (); return text; } @Override boolean isDescribedByLabel () { return false; } /* * Feature in Cocoa. If a checkbox is in multi-state mode, nextState cycles from off to mixed to on and back to off again. * This will cause the on state to momentarily appear while clicking on the checkbox. To avoid this, we override [NSCell nextState] * to go directly to the desired state if we have a grayed checkbox. */ @Override long /*int*/ nextState(long /*int*/ id, long /*int*/ sel) { if ((style & SWT.CHECK) != 0 && grayed) { return ((NSButton)view).state() == OS.NSMixedState ? OS.NSOffState : OS.NSMixedState; } return super.nextState(id, sel); } @Override void register() { super.register(); display.addWidget(((NSControl)view).cell(), this); } @Override void releaseWidget () { super.releaseWidget (); image = null; text = null; } /** * Removes the listener from the collection of listeners who will * be notified when the control is selected by the user. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException- ERROR_WIDGET_DISPOSED - if the receiver has been disposed
*- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
**
* @exception SWTException- ERROR_NULL_ARGUMENT - if the listener is null
**
* * @see SelectionListener * @see #addSelectionListener */ public void removeSelectionListener(SelectionListener listener) { checkWidget(); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook(SWT.Selection, listener); eventTable.unhook(SWT.DefaultSelection,listener); } void selectRadio () { /* * This code is intentionally commented. When two groups * of radio buttons with the same parent are separated by * another control, the correct behavior should be that * the two groups act independently. This is consistent * with radio tool and menu items. The commented code * implements this behavior. */ // int index = 0; // Control [] children = parent._getChildren (); // while (index < children.length && children [index] != this) index++; // int i = index - 1; // while (i >= 0 && children [i].setRadioSelection (false)) --i; // int j = index + 1; // while (j < children.length && children [j].setRadioSelection (false)) j++; // setSelection (true); Control [] children = parent._getChildren (); for (int i=0; i- ERROR_WIDGET_DISPOSED - if the receiver has been disposed
*- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
*LEFT RIGHT
orCENTER
* unless the receiver is anARROW
button, in * which case, the argument indicates the direction of * the arrow (one ofLEFT
,RIGHT
, *UP
orDOWN
). * * @param alignment the new alignment * * @exception SWTException
-
*
- ERROR_WIDGET_DISPOSED - if the receiver has been disposed *
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
-
*
- ERROR_WIDGET_DISPOSED - if the receiver has been disposed *
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
null
indicating that no image should be displayed.
* * Note that a Button can display an image and text simultaneously * on Windows (starting with XP), GTK+ and OSX. On other platforms, * a Button that has an image and text set into it will display the * image or text that was set most recently. *
* @param image the image to display on the receiver (may benull
)
*
* @exception IllegalArgumentException -
*
- ERROR_INVALID_ARGUMENT - if the image has been disposed *
-
*
- ERROR_WIDGET_DISPOSED - if the receiver has been disposed *
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
CHECK
,
* RADIO
, or TOGGLE
.
*
*
* When the receiver is of type CHECK
or RADIO
,
* it is selected when it is checked. When it is of type TOGGLE
,
* it is selected when it is pushed in.
*
* @param selected the new selection state
*
* @exception SWTException
-
*
- ERROR_WIDGET_DISPOSED - if the receiver has been disposed *
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *
* This method sets the button label. The label may include * the mnemonic character but must not contain line delimiters. *
** Mnemonics are indicated by an '&' that causes the next * character to be the mnemonic. When the user presses a * key sequence that matches the mnemonic, a selection * event occurs. On most platforms, the mnemonic appears * underlined but may be emphasized in a platform specific * manner. The mnemonic indicator character '&' can be * escaped by doubling it in the string, causing a single * '&' to be displayed. *
* Note that a Button can display an image and text simultaneously * on Windows (starting with XP), GTK+ and OSX. On other platforms, * a Button that has an image and text set into it will display the * image or text that was set most recently. *
* Also note, if control characters like '\n', '\t' etc. are used * in the string, then the behavior is platform dependent. *
* @param string the new text * * @exception IllegalArgumentException-
*
- ERROR_NULL_ARGUMENT - if the text is null *
-
*
- ERROR_WIDGET_DISPOSED - if the receiver has been disposed *
- ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver *