Using the SWT PrintDialog Class

The final standard dialog is the PrintDialog , which permits the user to select a print device to which output will be directed. It should be used in any application that permits the user to send jobs to a printer.

How do I do that?

Creating the Print dialog and obtaining the printer settings is a simple task that is performed in much the same manner as obtaining a font from Font dialog or a color from Color dialog. Example 17-6 demonstrates the technique.

Example 17-6. Using PrintDialog

import org.eclipse.swt.widgets.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.printing.*;


public class PrintDialogExample {
    Display d;
    Shell s;
    PrintDialogExample( )    {
         d = new Display( );
         s = new Shell(d);
        s.setSize(400,400);
        s.setImage(new Image(d, "c:\\icons\\JavaCup.ico"));
        s.setText("A PrintDialog Example");
        s.setLayout(new FillLayout(SWT.VERTICAL));    
        final Text t = new Text(s, SWT.BORDER | SWT.MULTI);
        final Button b = new Button(s, SWT.PUSH | SWT.BORDER);
        b.setText("Print");
        b.addSelectionListener(new SelectionAdapter( ) {
            public void widgetSelected(SelectionEvent e) {
                PrintDialog printDialog = new PrintDialog(s, SWT.NONE);
                printDialog.setText("Print");
                PrinterData printerData = printDialog.open( );
                if(!(printerData==null)) { Printer p = new Printer(printerData); p.startJob("PrintJob"); p.startPage( ); Rectangle trim = p.computeTrim(0, 0, 0, 0); Point ...

Get SWT: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.