下面列出了怎么用org.eclipse.swt.widgets.Display的API类实例代码及写法,或者点击链接到github查看源代码。
private static final Image createCloseImage(Display display, Color bg, Color fg) {
int size = 11, off = 1;
Image image = new Image(display, size, size);
GC gc = new GC(image);
gc.setBackground(bg);
gc.fillRectangle(image.getBounds());
gc.setForeground(fg);
gc.drawLine(0 + off, 0 + off, size - 1 - off, size - 1 - off);
gc.drawLine(1 + off, 0 + off, size - 1 - off, size - 2 - off);
gc.drawLine(0 + off, 1 + off, size - 2 - off, size - 1 - off);
gc.drawLine(size - 1 - off, 0 + off, 0 + off, size - 1 - off);
gc.drawLine(size - 1 - off, 1 + off, 1 + off, size - 1 - off);
gc.drawLine(size - 2 - off, 0 + off, 0 + off, size - 2 - off);
/*
* gc.drawLine(1, 0, size-2, 0); gc.drawLine(1, size-1, size-2, size-1);
* gc.drawLine(0, 1, 0, size-2); gc.drawLine(size-1, 1, size-1, size-2);
*/
gc.dispose();
return image;
}
public Color getForeground(Object element) {
if (currentLogEntry == null) {
return null;
}
ISVNResource resource = currentLogEntry.getResource();
if (resource == null) return null;
boolean isPartOfSelection = false;
if (element instanceof HistoryFolder) {
HistoryFolder historyFolder = (HistoryFolder)element;
isPartOfSelection = (resource.getRepository().getUrl().toString() + historyFolder.getPath()).startsWith(currentLogEntry.getResource().getUrl().toString());
}
if (element instanceof LogEntryChangePath) {
LogEntryChangePath logEntryChangePath = (LogEntryChangePath)element;
isPartOfSelection = (resource.getRepository().getUrl().toString() + logEntryChangePath.getPath()).startsWith(currentLogEntry.getResource().getUrl().toString());
}
if (!isPartOfSelection) return Display.getDefault().getSystemColor(SWT.COLOR_GRAY);
return null;
}
private void refreshLineNumberColumn(){
Display.getDefault().asyncExec(() ->{
IVerticalRuler ruler= getVerticalRuler();
// The following sequence mimics what happens during the setInput method.
// For now, this is the only known way to get the LineNumberColumn to update its visible status.
// called at the end of org.eclipse.ui.texteditor.AbstractTextEditor.createPartControl(Composite)
if (ruler instanceof CompositeRuler) {
updateContributedRulerColumns((CompositeRuler) ruler);
}
// called at the end of AbstractDecoratedTextEditor.doSetInput(IEditorInput)
RulerColumnDescriptor lineNumberColumnDescriptor= RulerColumnRegistry.getDefault().getColumnDescriptor(LineNumberColumn.ID);
if (lineNumberColumnDescriptor != null) {
IColumnSupport columnSupport= (IColumnSupport)getAdapter(IColumnSupport.class);
columnSupport.setColumnVisible(lineNumberColumnDescriptor, isLineNumberRulerVisible() || isPrefQuickDiffAlwaysOn());
}
// force redraw of the ruler`s content.
IVerticalRuler verticalRuler = getVerticalRuler();
if (verticalRuler != null) {
verticalRuler.update();
}
});
}
private static int getVisibleItems(SWTBotTimeGraph timegraph) {
return UIThreadRunnable.syncExec(Display.getDefault(), new IntResult() {
@Override
public Integer run() {
int count = 0;
TimeGraphControl control = timegraph.widget;
ITimeGraphEntry[] expandedElements = control.getExpandedElements();
for (ITimeGraphEntry entry : expandedElements) {
Rectangle itemBounds = control.getItemBounds(entry);
if (itemBounds.height > 0) {
count++;
}
}
return count;
}
});
}
/**
* Constructor
*
* You must dispose the color setting when it is no longer required.
*
* @param foreground
* The foreground color, or null to use the default system color
* @param background
* The background color, or null to use the default system color
* @param tickColorRGB
* The color for the time graph ticks, or null to use the default system color
* @param filter
* The filter tree node, or null
*/
public ColorSetting(@Nullable RGB foreground, @Nullable RGB background, @Nullable RGB tickColorRGB, @Nullable ITmfFilterTreeNode filter) {
fForegroundRGB = foreground;
fBackgroundRGB = background;
fTickColorRGB = (tickColorRGB != null) ? tickColorRGB : checkNotNull(Display.getDefault().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB());
fFilter = filter;
Display display = Display.getDefault();
fForegroundColor = (fForegroundRGB != null) ? new Color(display, fForegroundRGB) : null;
fBackgroundColor = (fBackgroundRGB != null) ? new Color(display, fBackgroundRGB) : null;
fDimmedForegroundColor = new Color(display, ColorUtil.blend(
(fForegroundRGB != null) ? fForegroundRGB : display.getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(),
(fBackgroundRGB != null) ? fBackgroundRGB : display.getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB()));
fDimmedBackgroundColor = (fBackgroundRGB == null) ? null : new Color(display, ColorUtil.blend(
fBackgroundRGB, display.getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB()));
fTickColor = new Color(display, fTickColorRGB);
}
private void drawHoveringCross(GC gc) {
if (fHoveredPoint == null) {
return;
}
gc.setLineWidth(1);
gc.setLineStyle(SWT.LINE_SOLID);
gc.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
gc.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
/* Vertical line */
gc.drawLine(fHoveringPoint.x, 0, fHoveringPoint.x, getChart().getPlotArea().getSize().y);
/* Horizontal line */
gc.drawLine(0, fHoveringPoint.y, getChart().getPlotArea().getSize().x, fHoveringPoint.y);
}
/**
* 输出字数统计结果到结果窗体中
* @param WordsFAResultMap
*/
public void printWordsFAReslut() {
String htmlPath = createFAResultHtml();
try {
model.getAnalysisIFileList().get(0).getProject().getFolder("Intermediate").getFolder("Report").refreshLocal(IResource.DEPTH_INFINITE, null);
} catch (CoreException e1) {
e1.printStackTrace();
}
final FileEditorInput input = new FileEditorInput(ResourceUtils.fileToIFile(htmlPath));
Display.getDefault().asyncExec(new Runnable() {
public void run() {
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().openEditor(input, QAConstant.FA_HtmlBrowserEditor, true);
} catch (PartInitException e) {
logger.error(Messages.getString("qa.fileAnalysis.WordsFA.log5"), e);
e.printStackTrace();
}
}
});
}
protected void createTitle(Composite parent) {
Composite titleComposite = widgetFactory.createComposite(parent);
titleComposite.setLayout(GridLayoutFactory.fillDefaults().numColumns(2).create());
titleComposite.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create());
Label label = widgetFactory.createLabel(titleComposite, getTitle(), SWT.NONE);
label.setLayoutData(GridDataFactory.swtDefaults().grab(false, false).create());
ControlDecoration controlDecoration = new ControlDecoration(label, SWT.RIGHT, titleComposite);
controlDecoration.setShowOnlyOnFocus(false);
controlDecoration.setDescriptionText(getTitleDescripiton());
controlDecoration.setImage(Pics.getImage(PicsConstants.hint));
Composite toolBarComposite = widgetFactory.createComposite(titleComposite);
toolBarComposite.setLayout(GridLayoutFactory.fillDefaults().create());
toolBarComposite.setLayoutData(GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).grab(true, false).create());
ToolBar toolBar = new ToolBar(toolBarComposite, SWT.HORIZONTAL | SWT.RIGHT | SWT.NO_FOCUS | SWT.FLAT);
widgetFactory.adapt(toolBar);
toolBar.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_WIDGET_FOREGROUND));
createToolItems(toolBar);
}
/**
* This method was copy/pasted from JFace.
*/
private static Monitor getClosestMonitor(final Display toSearch, final Point toFind) {
int closest = Integer.MAX_VALUE;
final Monitor[] monitors = toSearch.getMonitors();
Monitor result = monitors[0];
for (final Monitor current : monitors) {
final Rectangle clientArea = current.getClientArea();
if (clientArea.contains(toFind)) { return current; }
final int distance = Geometry.distanceSquared(Geometry.centerPoint(clientArea), toFind);
if (distance < closest) {
closest = distance;
result = current;
}
}
return result;
}
public static void aquireAndRun(IPersistentObject lockPo, ILockHandler lockhandler){
Display display = Display.getDefault();
LockResponse result = LocalLockServiceHolder.get().acquireLock(lockPo);
if (result.isOk()) {
display.syncExec(new Runnable() {
@Override
public void run(){
lockhandler.lockAcquired();
}
});
LocalLockServiceHolder.get().releaseLock(lockPo);
} else {
display.syncExec(new Runnable() {
@Override
public void run(){
lockhandler.lockFailed();
LockResponseHelper.showInfo(result, lockPo, logger);
}
});
}
}
/**
* Called when an atomic test has finished, whether the test succeeds or fails.
*
* @param description
* the description of the test that just ran
*/
@Override
public void testFinished(Description description) throws Exception {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
IWorkbenchWindow[] windows = N4IDEXpectUIPlugin.getDefault().getWorkbench().getWorkbenchWindows();
try {
N4IDEXpectView view = (N4IDEXpectView) windows[0].getActivePage().showView(
N4IDEXpectView.ID);
view.notifyFinishedExecutionOf(description);
} catch (PartInitException e) {
N4IDEXpectUIPlugin.logError("cannot refresh test view window", e);
}
}
});
}
private File fetchArchive(String filePath) throws FetchRemoteBosArchiveException {
File myFile;
FetchRemoteBosArchiveOperation operation = new FetchRemoteBosArchiveOperation(filePath);
try {
wizardContainer.run(true, false, operation);
} catch (InvocationTargetException | InterruptedException ex) {
exceptionDialogHandler.openErrorDialog(Display.getDefault().getActiveShell(),
Messages.errorOccuredWhileParsingBosArchive, ex);
}
if(!operation.getStatus().isOK()) {
throw new FetchRemoteBosArchiveException(operation.getStatus().getException());
}
urlTempPath = operation.getURLTempPath();
myFile = urlTempPath.getTmpPath().toFile();
return myFile;
}
/**
* Update the vertical scrollbar if present.
*/
public void updateYScrollBar() {
if (Display.getCurrent() != null) {
Display.getCurrent().syncExec(new Runnable() {
public void run() {
ScrollBar scroll = getVerticalBar();
// scroll may be null
if (scroll != null) {
_oldVerticalScroll = -1; // guarantee a clean repaint
scroll.setMinimum(0);
scroll.setMaximum(getTotalHeight() - getFixedRowsHeight());
int height = getHeight();
if (_tableRect != null) {
height = _tableRect.height;
}
scroll.setThumb(height); // - getFixedRowsHeight() - getHeaderHeight());
scroll.setIncrement(50); // increment for arrows
scroll.setPageIncrement(getHeight()); // page increment areas
scroll.setSelection(getAbsBeginYForRowIdx(_firstRowIdx) + _firstRowPixelOffset
+ getFixedRowsHeight());
}
}
});
}
}
/**
* @see org.eclipse.gef.tools.DirectEditManager#commit()
*/
protected void commit() {
Shell activeShell = Display.getCurrent().getActiveShell();
if (activeShell != null && getCellEditor().getControl().getShell().equals(activeShell.getParent())) {
Control[] children = activeShell.getChildren();
if (children.length == 1 && children[0] instanceof Table) {
/*
* CONTENT ASSIST: focus is lost to the content assist pop up -
* stay in focus
*/
getCellEditor().getControl().setVisible(true);
((XtextStyledTextCellEditorEx) getCellEditor()).setDeactivationLock(true);
return;
}
}
// content assist hacks
if (committed) {
bringDown();
return;
}
committed = true;
super.commit();
}
private static int getVisibleItems(SWTBotTimeGraph timegraph) {
return UIThreadRunnable.syncExec(Display.getDefault(), new IntResult() {
@Override
public Integer run() {
int count = 0;
TimeGraphControl control = timegraph.widget;
ITimeGraphEntry[] expandedElements = control.getExpandedElements();
for (ITimeGraphEntry entry : expandedElements) {
Rectangle itemBounds = control.getItemBounds(entry);
if (itemBounds.height > 0) {
count++;
}
}
return count;
}
});
}
/**
* Takes a font and gives it a bold typeface.
*
* @param font Font to modify
* @return Font with bold typeface
*/
public static Font applyBoldFont(final Font font) {
if (font == null) {
return null;
}
final FontData[] fontDataArray = font.getFontData();
if (fontDataArray == null) {
return null;
}
for (int index = 0; index < fontDataArray.length; index++) {
final FontData fData = fontDataArray[index];
fData.setStyle(SWT.BOLD);
}
return new Font(Display.getDefault(), fontDataArray);
}
protected void paintControlBorder(final PaintEvent e) {
final GC gc = e.gc;
final Display display = e.display;
if (display != null && gc != null && !gc.isDisposed()) {
final Control focused = display.getFocusControl();
final GC parentGC = gc;
parentGC.setAdvanced(true);
final Rectangle r = ContentAssistText.this.getBounds();
if (focused == null || focused.getParent() != null && !focused.getParent().equals(ContentAssistText.this)) {
parentGC.setForeground(display.getSystemColor(SWT.COLOR_GRAY));
} else {
parentGC.setForeground(display.getSystemColor(SWT.COLOR_WIDGET_BORDER));
}
parentGC.setLineWidth(1);
parentGC.drawRectangle(0, 0, r.width - 1, r.height - 1);
}
}
public void handleEvent(Event e) {
GC gc = new GC(b);
Image image = new Image(b.getDisplay(), e.width, e.height);
gc.copyArea(image, 0, 0);
ImageData data = image.getImageData();
gc.dispose();
image.dispose();
images.put(key, data);
keys.put(data, key);
if(requests.containsKey(key)) {
for(Iterator<VButton> iter = requests.get(key).iterator(); iter.hasNext();) {
iter.next().redraw();
iter.remove();
}
requests.remove(key);
}
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if(!b.isDisposed() && b == b.getDisplay().getFocusControl()) {
b.getParent().forceFocus();
}
b.dispose();
}
});
}
/**
* Called when an atomic test flags that it assumes a condition that is false
*
* describes the test that failed and the {@link AssumptionViolatedException} that was thrown
*/
@Override
public void testAssumptionFailure(Failure failure) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
IWorkbenchWindow[] windows = N4IDEXpectUIPlugin.getDefault().getWorkbench().getWorkbenchWindows();
try {
N4IDEXpectView view = (N4IDEXpectView) windows[0].getActivePage().showView(
N4IDEXpectView.ID);
view.notifyFailedExecutionOf(failure);
} catch (PartInitException e) {
N4IDEXpectUIPlugin.logError("cannot refresh test view window", e);
}
}
});
}
public TableComboExampleTab() {
super();
// create bold and italic font.
ExamplesView.setFont("tableComboCustFont", new FontData[]{
new FontData("Arial", 8, SWT.BOLD | SWT.ITALIC)});
boldFont = ExamplesView.getFont("tableComboCustFont");
// create images
testImage = ExamplesView.getImage("icons/in_ec_ov_success_16x16.gif");
test2Image = ExamplesView.getImage("icons/in_ec_ov_warning_16x16.gif");
test3Image = ExamplesView.getImage("icons/invalid_build_tool_16x16.gif");
// create colors
darkRed = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_RED);
darkBlue = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_BLUE);
darkGreen = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN);
}
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout());
DateChooser cal = new DateChooser(shell, SWT.BORDER);
cal.setTheme(DateChooserTheme.BLUE);
cal.setWeeksVisible(true);
cal.setFooterVisible(true);
shell.open();
while ( ! shell.isDisposed() ) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
/**
* @param treeContent
* @param mappings
* @return
*/
private Dialog openMapperDialog(final String[] treeContent,
final String[] mappings) {
Dialog dialog = new Dialog(Display.getDefault().getActiveShell()) {
@Override
public Composite createDialogArea(Composite parent) {
Composite res = (Composite)super.createDialogArea(parent);
TreeMapper<String, String, String> mapper = new TreeMapper<String, String, String>(
parent,
new ObjectSemanticSupport(),
new TreeMapperUIConfigProvider(ColorConstants.blue, 2, ColorConstants.darkBlue, 4));
mapper.setContentProviders(new ArrayTreeContentProvider(), new ArrayTreeContentProvider());
mapper.setInput(treeContent, treeContent, Arrays.asList(mappings));
return res;
}
};
dialog.setBlockOnOpen(false);
dialog.open();
return dialog;
}
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Demo ControlList");
shell.setBounds(100, 100, 300, 400);
FillLayout layout = new FillLayout();
layout.type = SWT.VERTICAL;
shell.setLayout(layout);
createContents(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
/**
* Executes the GridPrintNoBreak example.
*
* @param args
* the command line arguments.
*/
public static void main(String[] args) {
final Display display = new Display();
Shell shell = new Shell(display, SWT.SHELL_TRIM);
shell.setLayout(new GridLayout());
shell.setSize(600, 600);
PrintJob job = new PrintJob("GridPrintNoBreakExample", createPrint());
final PrintPreview preview = new PrintPreview(shell, SWT.BORDER);
preview.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
preview.setPrintJob(job);
shell.open();
while (!shell.isDisposed())
if (!display.readAndDispatch())
display.sleep();
PaperClips.print(job, new PrinterData());
}
/**
* Check to see if the user wants to launch on a specific port and check if that port is available for use. If it is
* not, ask the user if they want to cancel the launch or continue anyway
*
* Visible for testing
*
* @param configuration
* A Launch Configuration
* @return true if launch should continue, false if user terminated
* @throws CoreException
*/
boolean promptUserToContinueIfPortNotAvailable(ILaunchConfiguration configuration) throws CoreException {
// ignore the auto select case
if (WebAppLaunchConfiguration.getAutoPortSelection(configuration)) {
return true;
}
// check to see if the port is available for the web app to launch
// allows user to trigger launch cancellation
final AtomicBoolean continueLaunch = new AtomicBoolean(true);
final String port = WebAppLaunchConfiguration.getServerPort(configuration);
if (!NetworkUtilities.isPortAvailable(port)) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
continueLaunch.set(MessageDialog.openQuestion(null, "Port in Use",
"The port " + port + " appears to be in use (perhaps by another launch), "
+ "do you still want to continue with this launch?"));
}
});
}
return continueLaunch.get();
}
protected DesignElementHandle createElement( String type ) throws Exception
{
DesignElementHandle handle = super.createElement( type );
BaseTitleAreaDialog dialog = null;
if ( ReportDesignConstants.PARAMETER_GROUP_ELEMENT.equals( type ) )
{
dialog = new ParameterGroupDialog( Display.getCurrent( )
.getActiveShell( ),
Messages.getString( "ParametersNodeProvider.dialogue.title.group" ) ); //$NON-NLS-1$
( (ParameterGroupDialog) dialog ).setInput( handle );
}
else if ( ReportDesignConstants.SCALAR_PARAMETER_ELEMENT.equals( type ) )
{
dialog = new ParameterDialog( PlatformUI.getWorkbench( )
.getDisplay( )
.getActiveShell( ),
Messages.getString( "ParametersNodeProvider.dialogue.title.parameter" ) );//$NON-NLS-1$
// required default value
( (ParameterDialog) dialog ).setInput( handle );
}
if ( dialog == null )
return null;
if ( dialog.open( ) == Dialog.CANCEL )
{
return null;
}
return (DesignElementHandle) dialog.getResult( );
}
void comboEvent(Event event) {
switch (event.type) {
case SWT.Dispose:
if (popup != null && !popup.isDisposed()) {
list.removeListener(SWT.Dispose, listener);
popup.dispose();
}
Shell shell = getShell();
shell.removeListener(SWT.Deactivate, listener);
Display display = getDisplay();
display.removeFilter(SWT.FocusIn, filter);
popup = null;
text = null;
list = null;
arrow = null;
break;
case SWT.FocusIn:
Control focusControl = getDisplay().getFocusControl();
if (focusControl == arrow || focusControl == list)
return;
if (isDropped()) {
list.setFocus();
} else {
text.setFocus();
}
break;
case SWT.Move:
dropDown(false);
break;
case SWT.Resize:
internalLayout(false);
break;
}
}
public void changeControlPressed(DialogField field) {
ElementListSelectionDialog dialog= new ElementListSelectionDialog(
Display.getCurrent().getActiveShell(), new JavaElementLabelProvider());
dialog.setIgnoreCase(false);
dialog.setTitle(NLSUIMessages.PackageBrowseAdapter_package_selection);
dialog.setMessage(NLSUIMessages.PackageBrowseAdapter_choose_package);
dialog.setElements(createPackageListInput(fCu, null));
if (dialog.open() == Window.OK) {
IPackageFragment selectedPackage= (IPackageFragment)dialog.getFirstResult();
if (selectedPackage != null) {
fReceiver.setPackage(selectedPackage);
}
}
}
/**
* Open the dialog.
*
* @return the result
*/
public Object open() {
createContents();
shell.open();
shell.layout();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
return null;
}
private void sendSootClearEvent(){
Display.getCurrent().syncExec(new Runnable(){
public void run() {
SootPlugin.getDefault().fireSootOutputEvent(new SootOutputEvent(SootLauncher.this, ISootOutputEventConstants.SOOT_CLEAR_EVENT));
};
});
}