Java Code Examples for org.eclipse.swt.graphics.GC#dispose()

The following examples show how to use org.eclipse.swt.graphics.GC#dispose() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImageExportAction.java    From olca-app with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void run() {
	if (composite == null)
		return;

	log.trace("Take image snapshot");
	Point size = composite.getSize();
	Image image = new Image(composite.getDisplay(), size.x, size.y);
	GC gc = new GC(composite);
	gc.copyArea(image, 0, 0);

	try {
		writeToFile(image);
	} catch (Exception e) {
		log.error("Failed to save export image", e);
	} finally {
		gc.dispose();
		image.dispose();
	}
}
 
Example 2
Source File: ToolbarItem.java    From nebula with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Calculate size of item.
 */
public void calculateSize()
{
	Image calcSizeImage = new Image(Display.getDefault(), 1, 1);

	GC gc = new GC(calcSizeImage);
	gc.setAdvanced(true);
	gc.setAntialias(SWT.OFF);
	gc.setFont(parent.getFont());

	width = 10;

	if (image != null)
	{
		width += image.getImageData().width;
	}

	if (text.length() > 0)
	{
		width += getTextWidth(gc, text) + 9;
	}

	gc.dispose();
	calcSizeImage.dispose();
}
 
Example 3
Source File: SnippetBenchmarks.java    From nebula with Eclipse Public License 2.0 6 votes vote down vote up
private static void benchmarkSnippet8() {
	final Printer printer = new Printer();
	printer.startJob("benchmarkSnippet8");

	final PrintJob job = new PrintJob("Snippet8", Snippet8.createPrint());

	final GC gc = new GC(printer);
	new Benchmark().setName("getPageEnumeration").setRunCount(10).execute(
			new Runnable() {
				public void run() {
					PaperClips.getPageEnumeration(job, printer, gc)
							.nextPage();
				}
			});
	gc.dispose();

	new Benchmark().setName("getPages").setRunCount(10).execute(
			new Runnable() {
				public void run() {
					PaperClips.getPages(job, printer);
				}
			});

	printer.cancelJob();
	printer.dispose();
}
 
Example 4
Source File: InnerTagRender.java    From tmxeditor8 with GNU General Public License v2.0 6 votes vote down vote up
public Point calculateTagSize(InnerTagBean innerTagBean) {
	GC gc = new GC(Display.getDefault());
	gc.setFont(TAG_FONT);
	Point tempSize = gc.textExtent(String.valueOf(innerTagBean.getIndex()));
	// System.out.println("textSize: "+ tempSize);
	Point tagSize = new Point(tempSize.x + MARGIN_H * 2, tempSize.y + MARGIN_V * 2);
	int sawtooth = tagSize.y / 2;

	switch (innerTagBean.getType()) {
	case STANDALONE:
		tagSize.x += tagSize.y;
		break;

	default:
		tagSize.x += sawtooth;
		break;
	}
	// System.out.println("TagSize :"+tagSize);
	gc.dispose();
	return tagSize;
}
 
Example 5
Source File: ChartPrintJob.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
protected void startPrintJob(Composite elementToPrint, 
        PrinterData printerData) {
    Printer printer = new Printer(printerData);
    try {
        printer.startJob(jobName);

        GC gc = new GC(printer);
        try {
            Rectangle printArea = getPrintableArea(printer, BORDER);
            printer.startPage();
            printComposite(elementToPrint, gc, printArea);
            printer.endPage();
        } finally {
            gc.dispose();
        }
        printer.endJob();

    } finally {
        printer.dispose();
    }
}
 
Example 6
Source File: CComboContentAdapter.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
public Rectangle getInsertionBounds( Control control )
{
	// This doesn't take horizontal scrolling into affect.
	// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=204599
	CCombo combo = (CCombo) control;
	int position = combo.getSelection( ).y;
	String contents = ChartUIUtil.getText( combo );
	GC gc = new GC( combo );
	gc.setFont( combo.getFont( ) );
	Point extent = gc.textExtent( contents.substring( 0,
			Math.min( position, contents.length( ) ) ) );
	gc.dispose( );
	if ( COMPUTE_TEXT_USING_CLIENTAREA )
	{
		return new Rectangle( combo.getClientArea( ).x + extent.x,
				combo.getClientArea( ).y,
				1,
				combo.getClientArea( ).height );
	}
	return new Rectangle( extent.x, 0, 1, combo.getSize( ).y );
}
 
Example 7
Source File: SwtUniversalImageBitmap.java    From hop with Apache License 2.0 6 votes vote down vote up
@Override
protected Image renderRotated( Device device, int width, int height, double angleRadians ) {
  Image result = new Image( device, width * 2, height * 2 );

  GC gc = new GC( result );

  int bw = bitmap.getBounds().width;
  int bh = bitmap.getBounds().height;
  Transform affineTransform = new Transform( device );
  affineTransform.translate( width, height );
  affineTransform.rotate( (float) Math.toDegrees( angleRadians ) );
  affineTransform.scale( (float) zoomFactor * width / bw, (float) zoomFactor * height / bh );
  gc.setTransform( affineTransform );

  gc.drawImage( bitmap, 0, 0, bw, bh, -bw / 2, -bh / 2, bw, bh );

  gc.dispose();

  return result;
}
 
Example 8
Source File: InnerTagRender.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
public Point calculateTagSize(InnerTagBean innerTagBean) {
	GC gc = new GC(Display.getDefault());
	gc.setFont(TAG_FONT);
	Point tempSize = gc.textExtent(String.valueOf(innerTagBean.getIndex()));
	// System.out.println("textSize: "+ tempSize);
	Point tagSize = new Point(tempSize.x + MARGIN_H * 2, tempSize.y + MARGIN_V * 2);
	int sawtooth = tagSize.y / 2;

	switch (innerTagBean.getType()) {
	case STANDALONE:
		tagSize.x += tagSize.y;
		break;

	default:
		tagSize.x += sawtooth;
		break;
	}
	// System.out.println("TagSize :"+tagSize);
	gc.dispose();
	return tagSize;
}
 
Example 9
Source File: PlaceBidOrderWizard.java    From offspring with MIT License 6 votes vote down vote up
@Override
public Control createReadonlyControl(Composite parent) {
  Composite composite = new Composite(parent, SWT.NONE);
  GridLayoutFactory.fillDefaults().numColumns(2).spacing(10, 0)
      .margins(0, 0).applyTo(composite);

  textPriceReadonly = new Text(composite, SWT.BORDER);
  GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER)
      .grab(true, false).applyTo(textPriceReadonly);
  textPriceReadonly.setText("");

  labelPriceTotalReadonly = new Label(composite, SWT.NONE);
  GC gc = new GC(labelPriceTotalReadonly);
  GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER)
      .hint(gc.textExtent(THIRD_COLUMN).x, SWT.DEFAULT)
      .applyTo(labelPriceTotalReadonly);
  gc.dispose();
  labelPriceTotalReadonly.setText("0.0");
  return composite;

  // textPriceReadonly = new Text(parent, SWT.BORDER);
  // textPriceReadonly.setEditable(false);
  // return textPriceReadonly;
}
 
Example 10
Source File: ColorsPreferencePage.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
protected void updateColorImage() {
	Display display = colorButton.getDisplay();
	Image i = new Image(colorButton.getDisplay(), fExtent.x + 30, fExtent.y);
	imageList.add(i);
	GC gc = new GC(i);
	gc.setForeground(display.getSystemColor(SWT.COLOR_BLACK));
	gc.drawRectangle(0, 2, fExtent.x + 28, fExtent.y - 3);
	if (colorButton.getBackground() != null) {
		colorButton.getBackground().dispose();
	}
	Color c = new Color(display, getColorSelector().getColorValue());
	colorList.add(c);
	gc.setBackground(c);
	gc.fillRectangle(0, 2, fExtent.x + 32, fExtent.y + 5);
	gc.dispose();
	colorButton.setImage(i);
}
 
Example 11
Source File: SWTResourceManager.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @return the small {@link Image} that can be used as placeholder for missing image.
 */
private static Image getMissingImage() {
	Image image = new Image(Display.getCurrent(), MISSING_IMAGE_SIZE, MISSING_IMAGE_SIZE);
	//
	GC gc = new GC(image);
	gc.setBackground(getColor(SWT.COLOR_RED));
	gc.fillRectangle(0, 0, MISSING_IMAGE_SIZE, MISSING_IMAGE_SIZE);
	gc.dispose();
	//
	return image;
}
 
Example 12
Source File: ModeLineFlasher.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the width hint for this label.
 *
 * @param control the root control of this label
 * @return the width hint for this label
 * @since 2.1
 */
private int getWidthHint(Composite control) {
	if (fFixedWidth < 0) {
		GC gc= new GC(control);
		gc.setFont(control.getFont());
		fFixedWidth = (int) gc.getFontMetrics().getAverageCharacterWidth() * fWidthInChars;
		fFixedWidth += INDENT * 2;
		gc.dispose();
	}
	return fFixedWidth;
}
 
Example 13
Source File: SWTGraphicUtil.java    From nebula with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param text
 * @return the width of text
 */
public static int computeWidth(final String text) {
	final GC gc = new GC(Display.getDefault());
	final int width = gc.textExtent(text).x;
	gc.dispose();
	return width;
}
 
Example 14
Source File: SimpleGroupStrategy.java    From nebula with Eclipse Public License 2.0 5 votes vote down vote up
/** 
 * @see org.eclipse.nebula.widgets.pgroup.AbstractGroupStrategy#update()
 */
public void update()
{
    GC gc = new GC(getGroup());

    titleHeight = 0;
    int imageHeight = 0;

    if (getGroup().getImage() != null)
        imageHeight = getGroup().getImage().getBounds().height;
    titleHeight = Math.max(gc.getFontMetrics().getHeight() + (2 * titleTextMargin)
                           + (2 * vMargin), imageHeight + (2 * vMargin));
    if (getGroup().getToggleRenderer() != null)
    {
        int toggleHeight = getGroup().getToggleRenderer().getSize().y + (2 * vMargin);
        titleHeight = Math.max(toggleHeight + (2 * vMargin), titleHeight);
    }
    heightWithoutLine = titleHeight;
    if (getGroup().getLinePosition() == SWT.BOTTOM)
    {
        titleHeight += separatorHeight;
        titleHeight += (2 * lineMargin);
    }

    fontHeight = gc.getFontMetrics().getHeight();

    textWidth = gc.stringExtent(getGroup().getText()).x;

    gc.dispose();

}
 
Example 15
Source File: SourceViewerInformationControl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public Point computeSizeConstraints(int widthInChars, int heightInChars) {
	GC gc= new GC(fText);
	gc.setFont(fTextFont);
	int width= gc.getFontMetrics().getAverageCharWidth();
	int height= fText.getLineHeight(); //https://bugs.eclipse.org/bugs/show_bug.cgi?id=377109
	gc.dispose();

	return new Point(widthInChars * width, heightInChars * height);
}
 
Example 16
Source File: AbstractChartView.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public void print ()
{
    if ( Printer.getPrinterList ().length == 0 )
    {
        MessageDialog.openInformation ( this.shell, "No printer", "No installed printer could be found" );
        return;
    }

    final PrintDialog dlg = new PrintDialog ( this.shell, SWT.APPLICATION_MODAL );

    final PrinterData initialPd = Printer.getDefaultPrinterData ();
    initialPd.orientation = PrinterData.LANDSCAPE;
    dlg.setPrinterData ( initialPd );

    final PrinterData pd = dlg.open ();

    if ( pd != null )
    {
        final Printer printer = new Printer ( pd );
        final ResourceManager rm = new DeviceResourceManager ( printer );
        try
        {
            printer.startJob ( "Chart" );
            printer.startPage ();

            final GC gc = new GC ( printer );
            try
            {
                final SWTGraphics g = new SWTGraphics ( gc, rm );
                try
                {
                    this.viewer.getChartRenderer ().paint ( g );
                }
                finally
                {
                    g.dispose ();
                }
            }
            finally
            {
                gc.dispose ();
            }

            printer.endPage ();
            printer.endJob ();
        }
        finally
        {
            rm.dispose ();
            printer.dispose ();
        }
    }
}
 
Example 17
Source File: AnalysisView.java    From ice with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Given an SWT Canvas, this method creates a save file dialog and will save
 * the Canvas as an image file. Supported extensions include PNG, JPG, and
 * BMP.
 * 
 * @param canvas
 *            The Canvas to save as an image.
 */
protected static void saveCanvasImage(Canvas canvas) {
	// FIXME - It's possible to get a graphical glitch where there are black
	// pixels at the bottom of the image. My guess is that the GC never
	// actually bothers to paint because that part is not visible on the
	// screen. Currently, this issue is unresolved.

	// Store the allowed extensions in a HashMap.
	HashMap<String, Integer> extensions = new HashMap<String, Integer>(4);
	extensions.put("png", SWT.IMAGE_PNG);
	extensions.put("jpg", SWT.IMAGE_JPEG);
	extensions.put("bmp", SWT.IMAGE_BMP);

	// Make the array of strings needed to pass to the file dialog.
	String[] extensionStrings = new String[extensions.keySet().size()];
	int i = 0;
	for (String extension : extensions.keySet()) {
		extensionStrings[i++] = "*." + extension;
	}

	// Create the file save dialog.
	FileDialog fileDialog = new FileDialog(canvas.getShell(), SWT.SAVE);
	fileDialog.setFilterExtensions(extensionStrings);
	fileDialog.setOverwrite(true);

	// Get the path of the new/overwritten image file.
	String path = fileDialog.open();

	// Return if the user cancelled.
	if (path == null) {
		return;
	}
	// Get the image type to save from the path's extension.
	String[] splitPath = path.split("\\.");
	int extensionSWT = extensions.get(splitPath[splitPath.length - 1]);

	// Get the image from the canvas.
	Rectangle bounds = canvas.getBounds();
	Image image = new Image(null, bounds.width, bounds.height);
	GC gc = new GC(image);
	// SWT XYGraph uses this method to center the saved image.
	canvas.print(gc);
	gc.dispose();

	// Save the file.
	ImageLoader loader = new ImageLoader();
	loader.data = new ImageData[] { image.getImageData() };
	loader.save(path, extensionSWT);
	image.dispose();

	return;
}
 
Example 18
Source File: PixelConverter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public PixelConverter(Font font) {
	GC gc = new GC(font.getDevice());
	gc.setFont(font);
	fFontMetrics= gc.getFontMetrics();
	gc.dispose();
}
 
Example 19
Source File: GlobalActions.java    From elexis-3-core with Eclipse Public License 1.0 4 votes vote down vote up
protected void printAdr(final Kontakt k){
	// 25.01.2010 patch tschaller: there was always the printer selection
	// dialog. With printEtikette it wasn't so I copied the hardcoded string
	// from there
	// PrinterData pd =
	// getPrinterData(Messages.getString("GlobalActions.printersticker"));
	// //$NON-NLS-1$
	PrinterData pd = getPrinterData("Etiketten"); //$NON-NLS-1$
	if (pd != null) {
		// 25.01.2010 patch tschaller: page orientation of printer driver is
		// not handled correctly (we always get porttrait even when the
		// printer settings have landscape stored)
		Integer iOrientation = -1;
		String sOrientation = CoreHub.localCfg.get("Drucker/Etiketten/Ausrichtung", null); //$NON-NLS-1$
		try {
			iOrientation = Integer.parseInt(sOrientation);
		} catch (NumberFormatException ex) {}
		if (iOrientation != -1)
			pd.orientation = iOrientation;
		Printer prn = new Printer(pd);
		if (prn.startJob("Etikette drucken") == true) { //$NON-NLS-1$
			GC gc = new GC(prn);
			int y = 0;
			prn.startPage();
			FontMetrics fmt = gc.getFontMetrics();
			String pers = k.getPostAnschrift(true);
			String[] lines = pers.split("\n"); //$NON-NLS-1$
			for (String line : lines) {
				gc.drawString(line, 0, y);
				y += fmt.getHeight();
			}
			gc.dispose();
			prn.endPage();
			prn.endJob();
			prn.dispose();
		} else {
			MessageDialog.openError(mainWindow.getShell(),
				Messages.GlobalActions_PrinterErrorTitle,
				Messages.GlobalActions_PrinterErrorMessage); //$NON-NLS-1$ //$NON-NLS-2$
			
		}
		
	}
}
 
Example 20
Source File: XBookmarksDialog.java    From xds-ide with Eclipse Public License 1.0 4 votes vote down vote up
@Override
 protected Control createDialogArea(Composite parent) {
     Composite composite = (Composite) super.createDialogArea(parent);
     GridLayoutFactory.fillDefaults().extendedMargins(Util.isWindows() ? 0 : 3, 3, 2, 2).applyTo(composite);

     Composite tableComposite = new Composite(composite, SWT.NONE);
     tableComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
     tableComposite.setLayout(new GridLayout(1, false));
     
     tableViewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
             | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
     
     table = tableViewer.getTable();
     table.setLayoutData(new GridData(GridData.FILL_BOTH));
     tableViewer.setContentProvider(new MenuTableContentProvider());
     tableViewer.setLabelProvider(new MenuTableLabelProvider());

     { // Columns:
         GC gc= new GC(table);
         try {
         	int maxW = gc.stringExtent("WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW").x; //$NON-NLS-1$
         	int gap  = gc.stringExtent("WW").x; //$NON-NLS-1$
         	int widths[] = new int[model.columns];
         	for (int i=0; i<model.columns; ++i) {
         		widths[i] = 0;
         	}
         	for (Model.Row r : model.getRows()) {
         		for (int i=0; i<model.columns; ++i) {
         			if (!r.getField(i).isEmpty()) {
         				int w     = Math.min(gc.stringExtent(r.getField(i)).x + gap, maxW);
         				widths[i] = Math.max(widths[i], w);
         			}
         		}
         	}
         	
         	for (int i=0; i<model.columns; ++i) {
         		TableColumn tc = new TableColumn(table, SWT.LEFT);
         		tc.setWidth(widths[i]);
         	}
         	table.setHeaderVisible(false);
         	table.setLinesVisible(false);
} finally {
	gc.dispose();
}
     }
     
     Listener eventListener = new Listener() {
         @Override
         public void handleEvent(Event event) {
             if (event.type == SWT.MouseDoubleClick || 
                (event.type == SWT.KeyDown && event.character == SWT.CR)) 
             {
                 doSelect();
             }
         }
         
     };
     
     addListener (SWT.KeyDown, eventListener);
     addListener (SWT.MouseDoubleClick, eventListener);
         
     tableViewer.setInput(model);
     table.select(0);

     return composite;
 }