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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.