Java/SWT JFace Eclipse/Print
Содержание
Demonstrates printing images
//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.printing.*;
import org.eclipse.swt.widgets.*;
/**
* This class demonstrates printing images
*/
public class ImagePrinterExample {
/**
* The application entry point
* @param args the command line arguments
*/
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display, SWT.NONE);
try {
// Prompt the user for an image file
FileDialog fileChooser = new FileDialog(shell, SWT.OPEN);
String fileName = fileChooser.open();
if (fileName == null) { return; }
// Load the image
ImageLoader loader = new ImageLoader();
ImageData[] imageData = loader.load(fileName);
if (imageData.length > 0) {
// Show the Choose Printer dialog
PrintDialog dialog = new PrintDialog(shell, SWT.NULL);
PrinterData printerData = dialog.open();
if (printerData != null) {
// Create the printer object
Printer printer = new Printer(printerData);
// Calculate the scale factor between the screen resolution and printer
// resolution in order to correctly size the image for the printer
Point screenDPI = display.getDPI();
Point printerDPI = printer.getDPI();
int scaleFactor = printerDPI.x / screenDPI.x;
// Determine the bounds of the entire area of the printer
Rectangle trim = printer.ruputeTrim(0, 0, 0, 0);
// Start the print job
if (printer.startJob(fileName)) {
if (printer.startPage()) {
GC gc = new GC(printer);
Image printerImage = new Image(printer, imageData[0]);
// Draw the image
gc.drawImage(printerImage, 0, 0, imageData[0].width,
imageData[0].height, -trim.x, -trim.y,
scaleFactor * imageData[0].width,
scaleFactor * imageData[0].height);
// Clean up
printerImage.dispose();
gc.dispose();
printer.endPage();
}
}
// End the job and dispose the printer
printer.endJob();
printer.dispose();
}
}
} catch (Exception e) {
MessageBox messageBox = new MessageBox(shell, SWT.ICON_ERROR);
messageBox.setMessage("Error printing test image");
messageBox.open();
}
}
}
Demonstrates printing text
//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.printing.*;
import org.eclipse.swt.widgets.*;
import java.io.*;
/**
* This class demonstrates printing text
*/
public class TextPrinterExample {
/**
* Runs the application
*/
public void run() {
Display display = new Display();
Shell shell = new Shell(display);
// Get the file to print
FileDialog fileChooser = new FileDialog(shell, SWT.OPEN);
String fileName = fileChooser.open();
if (fileName != null) {
// Have user select a printer
PrintDialog dialog = new PrintDialog(shell);
PrinterData printerData = dialog.open();
if (printerData != null) {
// Create the printer
Printer printer = new Printer(printerData);
try {
// Print the contents of the file
new WrappingPrinter(printer, fileName, getFileContents(fileName)).print();
} catch (Exception e) {
MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
mb.setMessage(e.getMessage());
mb.open();
}
// Dispose the printer
printer.dispose();
}
}
display.dispose();
}
/**
* Read in the file and return its contents
* @param fileName
* @return
* @throws FileNotFoundException
* @throws IOException
*/
private String getFileContents(String fileName)
throws FileNotFoundException, IOException {
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
try {
// Read in the file
reader = new BufferedReader(new FileReader(fileName));
while (reader.ready()) {
contents.append(reader.readLine());
contents.append("\n"); // Throw away LF chars, and just replace CR
}
} finally {
if (reader != null) try {
reader.close();
} catch (IOException e) {}
}
return contents.toString();
}
/**
* The application entry point
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new TextPrinterExample().run();
}
}
/**
* This class performs the printing, wrapping text as necessary
*/
class WrappingPrinter {
private Printer printer; // The printer
private String fileName; // The name of the file to print
private String contents; // The contents of the file to print
private GC gc; // The GC to print on
private int xPos, yPos; // The current x and y locations for print
private Rectangle bounds; // The boundaries for the print
private StringBuffer buf; // Holds a word at a time
private int lineHeight; // The height of a line of text
/**
* WrappingPrinter constructor
* @param printer the printer
* @param fileName the fileName
* @param contents the contents
*/
WrappingPrinter(Printer printer, String fileName, String contents) {
this.printer = printer;
this.fileName = fileName;
this.contents = contents;
}
/**
* Prints the file
*/
void print() {
// Start the print job
if (printer.startJob(fileName)) {
// Determine print area, with margins
bounds = computePrintArea(printer);
xPos = bounds.x;
yPos = bounds.y;
// Create the GC
gc = new GC(printer);
// Determine line height
lineHeight = gc.getFontMetrics().getHeight();
// Determine tab width--use three spaces for tabs
int tabWidth = gc.stringExtent(" ").x;
// Print the text
printer.startPage();
buf = new StringBuffer();
char c;
for (int i = 0, n = contents.length(); i < n; i++) {
// Get the next character
c = contents.charAt(i);
// Check for newline
if (c == "\n") {
printBuffer();
printNewline();
}
// Check for tab
else if (c == "\t") {
xPos += tabWidth;
}
else {
buf.append(c);
// Check for space
if (Character.isWhitespace(c)) {
printBuffer();
}
}
}
printer.endPage();
printer.endJob();
gc.dispose();
}
}
/**
* Prints the contents of the buffer
*/
void printBuffer() {
// Get the width of the rendered buffer
int width = gc.stringExtent(buf.toString()).x;
// Determine if it fits
if (xPos + width > bounds.x + bounds.width) {
// Doesn"t fit--wrap
printNewline();
}
// Print the buffer
gc.drawString(buf.toString(), xPos, yPos, false);
xPos += width;
buf.setLength(0);
}
/**
* Prints a newline
*/
void printNewline() {
// Reset x and y locations to next line
xPos = bounds.x;
yPos += lineHeight;
// Have we gone to the next page?
if (yPos > bounds.y + bounds.height) {
yPos = bounds.y;
printer.endPage();
printer.startPage();
}
}
/**
* Computes the print area, including margins
* @param printer the printer
* @return Rectangle
*/
Rectangle computePrintArea(Printer printer) {
// Get the printable area
Rectangle rect = printer.getClientArea();
// Compute the trim
Rectangle trim = printer.ruputeTrim(0, 0, 0, 0);
// Get the printer"s DPI
Point dpi = printer.getDPI();
// Calculate the printable area, using 1 inch margins
int left = trim.x + dpi.x;
if (left < rect.x) left = rect.x;
int right = (rect.width + trim.x + trim.width) - dpi.x;
if (right > rect.width) right = rect.width;
int top = trim.y + dpi.y;
if (top < rect.y) top = rect.y;
int bottom = (rect.height + trim.y + trim.height) - dpi.y;
if (bottom > rect.height) bottom = rect.height;
return new Rectangle(left, top, right - left, bottom - top);
}
}
ImageViewer
/*******************************************************************************
* All Right Reserved. Copyright (c) 1998, 2004 Jackwind Li Guojie
*
* Created on 2004-5-2 14:57:37 by JACK $Id$
*
******************************************************************************/
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.rubo;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.printing.PrintDialog;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
public class SWTImageViewer {
Display display = new Display();
Shell shell = new Shell(display);
Canvas canvas;
Image image;
String fileName;
public SWTImageViewer() {
shell.setText("Image viewer");
shell.setLayout(new GridLayout(1, true));
ToolBar toolBar = new ToolBar(shell, SWT.FLAT);
ToolItem itemOpen = new ToolItem(toolBar, SWT.PUSH);
itemOpen.setText("Open");
itemOpen.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
String file = dialog.open();
if (file != null) {
if (image != null)
image.dispose();
image = null;
try {
image = new Image(display, file);
} catch (RuntimeException e) {
// e.printStackTrace();
}
if (image != null) {
fileName = file;
} else {
System.err.println(
"Failed to load image from file: " + file);
}
canvas.redraw();
}
}
});
ToolItem itemPrintPreview = new ToolItem(toolBar, SWT.PUSH);
itemPrintPreview.setText("Preview");
itemPrintPreview.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
ImagePrintPreviewDialog dialog =
new ImagePrintPreviewDialog(ImageViewer.this);
dialog.open();
}
});
ToolItem itemPrint = new ToolItem(toolBar, SWT.PUSH);
itemPrint.setText("Print");
itemPrint.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
print();
}
});
canvas = new Canvas(shell, SWT.BORDER);
canvas.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
canvas.setLayoutData(new GridData(GridData.FILL_BOTH));
canvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
if (image == null) {
e.gc.drawString("No image", 0, 0);
} else {
e.gc.drawImage(image, 0, 0);
}
}
});
image = new Image(display, "jexp.gif");
fileName = "scene.jpg";
shell.setSize(500, 400);
shell.open();
//textUser.forceFocus();
// Set up the event loop.
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
// If no more entries in event queue
display.sleep();
}
}
display.dispose();
}
/**
* Lets the user to select a printer and prints the image on it.
*
*/
void print() {
PrintDialog dialog = new PrintDialog(shell);
// Prompts the printer dialog to let the user select a printer.
PrinterData printerData = dialog.open();
if (printerData == null) // the user cancels the dialog
return;
// Loads the printer.
Printer printer = new Printer(printerData);
print(printer, null);
}
/**
* Prints the image current displayed to the specified printer.
*
* @param printer
*/
void print(final Printer printer, PrintMargin printMargin) {
if (image == null) // If no image is loaded, do not print.
return;
final Point printerDPI = printer.getDPI();
final Point displayDPI = display.getDPI();
System.out.println(displayDPI + " " + printerDPI);
final PrintMargin margin = (printMargin == null ? PrintMargin.getPrintMargin(printer, 1.0) : printMargin);
Thread printThread = new Thread() {
public void run() {
if (!printer.startJob(fileName)) {
System.err.println("Failed to start print job!");
printer.dispose();
return;
}
GC gc = new GC(printer);
if (!printer.startPage()) {
System.err.println("Failed to start a new page!");
gc.dispose();
return;
} else {
int imageWidth = image.getBounds().width;
int imageHeight = image.getBounds().height;
// Handles DPI conversion.
double dpiScaleFactorX = printerDPI.x * 1.0 / displayDPI.x;
double dpiScaleFactorY = printerDPI.y * 1.0 / displayDPI.y;
// If the image is too large to draw on a page, reduces its
// width and height proportionally.
double imageSizeFactor =
Math.min(
1,
(margin.right - margin.left)
* 1.0
/ (dpiScaleFactorX * imageWidth));
imageSizeFactor =
Math.min(
imageSizeFactor,
(margin.bottom - margin.top)
* 1.0
/ (dpiScaleFactorY * imageHeight));
// Draws the image to the printer.
gc.drawImage(
image,
0,
0,
imageWidth,
imageHeight,
margin.left,
margin.top,
(int) (dpiScaleFactorX * imageSizeFactor * imageWidth),
(int) (dpiScaleFactorY
* imageSizeFactor
* imageHeight));
gc.dispose();
}
printer.endPage();
printer.endJob();
printer.dispose();
System.out.println("Printing job done!");
}
};
printThread.start();
}
public static void main(String[] args) {
new SWTImageViewer();
}
}
class ImagePrintPreviewDialog extends Dialog {
ImageViewer viewer;
Shell shell;
Canvas canvas;
Printer printer;
PrintMargin margin;
Combo combo;
public ImagePrintPreviewDialog(ImageViewer viewer) {
super(viewer.shell);
this.viewer = viewer;
}
public void open() {
shell =
new Shell(
viewer.shell,
SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.RESIZE);
shell.setText("Print preview");
shell.setLayout(new GridLayout(4, false));
final Button buttonSelectPrinter = new Button(shell, SWT.PUSH);
buttonSelectPrinter.setText("Select a printer");
buttonSelectPrinter.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
PrintDialog dialog = new PrintDialog(shell);
// Prompts the printer dialog to let the user select a printer.
PrinterData printerData = dialog.open();
if (printerData == null) // the user cancels the dialog
return;
// Loads the printer.
final Printer printer = new Printer(printerData);
setPrinter(
printer,
Double.parseDouble(
combo.getItem(combo.getSelectionIndex())));
}
});
new Label(shell, SWT.NULL).setText("Margin in inches: ");
combo = new Combo(shell, SWT.READ_ONLY);
combo.add("0.5");
combo.add("1.0");
combo.add("1.5");
combo.add("2.0");
combo.add("2.5");
combo.add("3.0");
combo.select(1);
combo.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
double value =
Double.parseDouble(
combo.getItem(combo.getSelectionIndex()));
setPrinter(printer, value);
}
});
final Button buttonPrint = new Button(shell, SWT.PUSH);
buttonPrint.setText("Print");
buttonPrint.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
if (printer == null)
viewer.print();
else
viewer.print(printer, margin);
shell.dispose();
}
});
canvas = new Canvas(shell, SWT.BORDER);
GridData gridData = new GridData(GridData.FILL_BOTH);
gridData.horizontalSpan = 4;
canvas.setLayoutData(gridData);
canvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
int canvasBorder = 20;
if (printer == null || printer.isDisposed())
return;
Rectangle rectangle = printer.getBounds();
Point canvasSize = canvas.getSize();
double viewScaleFactor =
(canvasSize.x - canvasBorder * 2) * 1.0 / rectangle.width;
viewScaleFactor =
Math.min(
viewScaleFactor,
(canvasSize.y - canvasBorder * 2)
* 1.0
/ rectangle.height);
int offsetX =
(canvasSize.x - (int) (viewScaleFactor * rectangle.width))
/ 2;
int offsetY =
(canvasSize.y - (int) (viewScaleFactor * rectangle.height))
/ 2;
e.gc.setBackground(
shell.getDisplay().getSystemColor(SWT.COLOR_WHITE));
// draws the page layout
e.gc.fillRectangle(
offsetX,
offsetY,
(int) (viewScaleFactor * rectangle.width),
(int) (viewScaleFactor * rectangle.height));
// draws the margin.
e.gc.setLineStyle(SWT.LINE_DASH);
e.gc.setForeground(
shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
int marginOffsetX =
offsetX + (int) (viewScaleFactor * margin.left);
int marginOffsetY =
offsetY + (int) (viewScaleFactor * margin.top);
e.gc.drawRectangle(
marginOffsetX,
marginOffsetY,
(int) (viewScaleFactor * (margin.right - margin.left)),
(int) (viewScaleFactor * (margin.bottom - margin.top)));
if (viewer.image != null) {
int imageWidth = viewer.image.getBounds().width;
int imageHeight = viewer.image.getBounds().height;
double dpiScaleFactorX =
printer.getDPI().x
* 1.0
/ shell.getDisplay().getDPI().x;
double dpiScaleFactorY =
printer.getDPI().y
* 1.0
/ shell.getDisplay().getDPI().y;
double imageSizeFactor =
Math.min(
1,
(margin.right - margin.left)
* 1.0
/ (dpiScaleFactorX * imageWidth));
imageSizeFactor =
Math.min(
imageSizeFactor,
(margin.bottom - margin.top)
* 1.0
/ (dpiScaleFactorY * imageHeight));
e.gc.drawImage(
viewer.image,
0,
0,
imageWidth,
imageHeight,
marginOffsetX,
marginOffsetY,
(int) (dpiScaleFactorX
* imageSizeFactor
* imageWidth
* viewScaleFactor),
(int) (dpiScaleFactorY
* imageSizeFactor
* imageHeight
* viewScaleFactor));
}
}
});
shell.setSize(400, 400);
shell.open();
setPrinter(null, 1.0);
// Set up the event loop.
while (!shell.isDisposed()) {
if (!shell.getDisplay().readAndDispatch()) {
// If no more entries in event queue
shell.getDisplay().sleep();
}
}
}
/**
* Sets target printer.
*
* @param printer
*/
void setPrinter(Printer printer, double marginSize) {
if (printer == null) {
printer = new Printer(Printer.getDefaultPrinterData());
}
this.printer = printer;
margin = PrintMargin.getPrintMargin(printer, marginSize);
canvas.redraw();
}
}
/**
* Contains margin information (in pixels) for a print job.
*
*/
class PrintMargin {
// Margin to the left side, in pixels
public int left;
// Margins to the right side, in pixels
public int right;
// Margins to the top side, in pixels
public int top;
// Margins to the bottom side, in pixels
public int bottom;
private PrintMargin(int left, int right, int top, int bottom) {
this.left = left;
this.right = right;
this.top = top;
this.bottom = bottom;
}
/**
* Returns a PrintMargin object containing the true border margins for the
* specified printer with the given margin in inches.
* Note: all four sides share the same margin width.
* @param printer
* @param margin
* @return
*/
static PrintMargin getPrintMargin(Printer printer, double margin) {
return getPrintMargin(printer, margin, margin, margin, margin);
}
/**
* Returns a PrintMargin object containing the true border margins for the
* specified printer with the given margin width (in inches) for each side.
*/
static PrintMargin getPrintMargin(
Printer printer,
double marginLeft,
double marginRight,
double marginTop,
double marginBottom) {
Rectangle clientArea = printer.getClientArea();
Rectangle trim = printer.ruputeTrim(0, 0, 0, 0);
//System.out.println(printer.getBounds() + " - " + clientArea + "" +
// trim);
Point dpi = printer.getDPI();
int leftMargin = (int) (marginLeft * dpi.x) - trim.x;
int rightMargin =
clientArea.width
+ trim.width
- (int) (marginRight * dpi.x)
- trim.x;
int topMargin = (int) (marginTop * dpi.y) - trim.y;
int bottomMargin =
clientArea.height
+ trim.height
- (int) (marginBottom * dpi.y)
- trim.y;
return new PrintMargin(
leftMargin,
rightMargin,
topMargin,
bottomMargin);
}
public String toString() {
return "Margin { "
+ left
+ ", "
+ right
+ "; "
+ top
+ ", "
+ bottom
+ " }";
}
}
Print Hello World in black, outlined in red, to default printer
/*
* Printing example snippet: print "Hello World!" in black, outlined in red, to default printer
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class Snippet132 {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.open();
PrinterData data = Printer.getDefaultPrinterData();
if (data == null) {
System.out.println("Warning: No default printer.");
return;
}
Printer printer = new Printer(data);
if (printer.startJob("SWT Printing Snippet")) {
Color black = printer.getSystemColor(SWT.COLOR_BLACK);
Color white = printer.getSystemColor(SWT.COLOR_WHITE);
Color red = printer.getSystemColor(SWT.COLOR_RED);
Rectangle trim = printer.ruputeTrim(0, 0, 0, 0);
Point dpi = printer.getDPI();
int leftMargin = dpi.x + trim.x; // one inch from left side of
// paper
int topMargin = dpi.y / 2 + trim.y; // one-half inch from top edge
// of paper
GC gc = new GC(printer);
Font font = gc.getFont(); // example just uses printer"s default
// font
if (printer.startPage()) {
gc.setBackground(white);
gc.setForeground(black);
String testString = "Hello World!";
Point extent = gc.stringExtent(testString);
gc.drawString(testString, leftMargin, topMargin
+ font.getFontData()[0].getHeight());
gc.setForeground(red);
gc.drawRectangle(leftMargin, topMargin, extent.x, extent.y);
printer.endPage();
}
gc.dispose();
printer.endJob();
}
printer.dispose();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Printing Example
/******************************************************************************
* All Right Reserved.
* Copyright (c) 1998, 2004 Jackwind Li Guojie
*
* Created on 2004-5-2 11:03:19 by JACK
* $Id$
*
*****************************************************************************/
/*
* Printing example snippet: print text to printer, with word wrap and pagination
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.jface.window.WindowManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.StyledTextPrintOptions;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.printing.PrintDialog;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.FontDialog;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class PrintingExample {
ApplicationWindow applicationWindow;
WindowManager manager;
StyledTextPrintOptions styledTextPrintOptions;
StyledText styledText;
Display display;
Shell shell;
Text text;
Font font;
Color foregroundColor, backgroundColor;
Printer printer;
GC gc;
Font printerFont;
Color printerForegroundColor, printerBackgroundColor;
int lineHeight = 0;
int tabWidth = 0;
int leftMargin, rightMargin, topMargin, bottomMargin;
int x, y;
int index, end;
String textToPrint;
String tabs;
StringBuffer wordBuffer;
public static void main(String[] args) {
new PrintingExample().open();
}
void open() {
display = new Display();
font = new Font(display, "Courier", 10, SWT.NORMAL);
foregroundColor = display.getSystemColor(SWT.COLOR_BLACK);
backgroundColor = display.getSystemColor(SWT.COLOR_WHITE);
shell = new Shell(display);
shell.setLayout(new FillLayout());
shell.setText("Print Text");
shell.setMaximized(true);
text = new Text(shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
text.setFont(font);
text.setForeground(foregroundColor);
text.setBackground(backgroundColor);
Menu menuBar = new Menu(shell, SWT.BAR);
shell.setMenuBar(menuBar);
MenuItem item = new MenuItem(menuBar, SWT.CASCADE);
item.setText("&File");
Menu fileMenu = new Menu(shell, SWT.DROP_DOWN);
item.setMenu(fileMenu);
item = new MenuItem(fileMenu, SWT.PUSH);
item.setText("&Open...");
item.setAccelerator(SWT.CTRL + "O");
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
menuOpen();
}
});
item = new MenuItem(fileMenu, SWT.PUSH);
item.setText("Font...");
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
menuFont();
}
});
item = new MenuItem(fileMenu, SWT.PUSH);
item.setText("Foreground Color...");
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
menuForegroundColor();
}
});
item = new MenuItem(fileMenu, SWT.PUSH);
item.setText("Background Color...");
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
menuBackgroundColor();
}
});
item = new MenuItem(fileMenu, SWT.PUSH);
item.setText("&Print...");
item.setAccelerator(SWT.CTRL + "P");
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
menuPrint();
}
});
new MenuItem(fileMenu, SWT.SEPARATOR);
item = new MenuItem(fileMenu, SWT.PUSH);
item.setText("E&xit");
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
System.exit(0);
}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
if (font != null) font.dispose();
if (foregroundColor != null) foregroundColor.dispose();
if (backgroundColor != null) backgroundColor.dispose();
}
void menuOpen() {
final String textString;
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String[] {"*.java", "*.*"});
String name = dialog.open();
if ((name == null) || (name.length() == 0)) return;
try {
File file = new File(name);
FileInputStream stream= new FileInputStream(file.getPath());
try {
Reader in = new BufferedReader(new InputStreamReader(stream));
char[] readBuffer= new char[2048];
StringBuffer buffer= new StringBuffer((int) file.length());
int n;
while ((n = in.read(readBuffer)) > 0) {
buffer.append(readBuffer, 0, n);
}
textString = buffer.toString();
stream.close();
} catch (IOException e) {
MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
box.setMessage("Error reading file:\n" + name);
box.open();
return;
}
} catch (FileNotFoundException e) {
MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
box.setMessage("File not found:\n" + name);
box.open();
return;
}
text.setText(textString);
}
void menuFont() {
FontDialog fontDialog = new FontDialog(shell);
fontDialog.setFontList(font.getFontData());
FontData fontData = fontDialog.open();
if (fontData != null) {
if (font != null) font.dispose();
font = new Font(display, fontData);
text.setFont(font);
}
}
void menuForegroundColor() {
ColorDialog colorDialog = new ColorDialog(shell);
colorDialog.setRGB(foregroundColor.getRGB());
RGB rgb = colorDialog.open();
if (rgb != null) {
if (foregroundColor != null) foregroundColor.dispose();
foregroundColor = new Color(display, rgb);
text.setForeground(foregroundColor);
}
}
void menuBackgroundColor() {
ColorDialog colorDialog = new ColorDialog(shell);
colorDialog.setRGB(backgroundColor.getRGB());
RGB rgb = colorDialog.open();
if (rgb != null) {
if (backgroundColor != null) backgroundColor.dispose();
backgroundColor = new Color(display, rgb);
text.setBackground(backgroundColor);
}
}
void menuPrint() {
PrintDialog dialog = new PrintDialog(shell, SWT.NULL);
PrinterData data = dialog.open();
if (data == null) return;
if (data.printToFile) {
data.fileName = "print.out"; // you probably want to ask the user for a filename
}
/* Get the text to print from the Text widget (you could get it from anywhere, i.e. your java model) */
textToPrint = text.getText();
/* Do the printing in a background thread so that spooling does not freeze the UI. */
printer = new Printer(data);
Thread printingThread = new Thread("Printing") {
public void run() {
print(printer);
printer.dispose();
}
};
printingThread.start();
}
void print(Printer printer) {
if (printer.startJob("Text")) { // the string is the job name - shows up in the printer"s job list
Rectangle clientArea = printer.getClientArea();
Rectangle trim = printer.ruputeTrim(0, 0, 0, 0);
Point dpi = printer.getDPI();
leftMargin = dpi.x + trim.x; // one inch from left side of paper
rightMargin = clientArea.width - dpi.x + trim.x + trim.width; // one inch from right side of paper
topMargin = dpi.y + trim.y; // one inch from top edge of paper
bottomMargin = clientArea.height - dpi.y + trim.y + trim.height; // one inch from bottom edge of paper
/* Create a buffer for computing tab width. */
int tabSize = 4; // is tab width a user setting in your UI?
StringBuffer tabBuffer = new StringBuffer(tabSize);
for (int i = 0; i < tabSize; i++) tabBuffer.append(" ");
tabs = tabBuffer.toString();
/* Create printer GC, and create and set the printer font & foreground color. */
gc = new GC(printer);
FontData fontData = font.getFontData()[0];
printerFont = new Font(printer, fontData.getName(), fontData.getHeight(), fontData.getStyle());
gc.setFont(printerFont);
tabWidth = gc.stringExtent(tabs).x;
lineHeight = gc.getFontMetrics().getHeight();
RGB rgb = foregroundColor.getRGB();
printerForegroundColor = new Color(printer, rgb);
gc.setForeground(printerForegroundColor);
rgb = backgroundColor.getRGB();
printerBackgroundColor = new Color(printer, rgb);
gc.setBackground(printerBackgroundColor);
/* Print text to current gc using word wrap */
printText();
printer.endJob();
/* Cleanup graphics resources used in printing */
printerFont.dispose();
printerForegroundColor.dispose();
printerBackgroundColor.dispose();
gc.dispose();
}
}
void printText() {
printer.startPage();
wordBuffer = new StringBuffer();
x = leftMargin;
y = topMargin;
index = 0;
end = textToPrint.length();
while (index < end) {
char c = textToPrint.charAt(index);
index++;
if (c != 0) {
if (c == 0x0a || c == 0x0d) {
if (c == 0x0d && index < end && textToPrint.charAt(index) == 0x0a) {
index++; // if this is cr-lf, skip the lf
}
printWordBuffer();
newline();
} else {
if (c != "\t") {
wordBuffer.append(c);
}
if (Character.isWhitespace(c)) {
printWordBuffer();
if (c == "\t") {
x += tabWidth;
}
}
}
}
}
if (y + lineHeight <= bottomMargin) {
printer.endPage();
}
}
void printWordBuffer() {
if (wordBuffer.length() > 0) {
String word = wordBuffer.toString();
int wordWidth = gc.stringExtent(word).x;
if (x + wordWidth > rightMargin) {
/* word doesn"t fit on current line, so wrap */
newline();
}
gc.drawString(word, x, y, false);
x += wordWidth;
wordBuffer = new StringBuffer();
}
}
void newline() {
x = leftMargin;
y += lineHeight;
if (y + lineHeight > bottomMargin) {
printer.endPage();
if (index + 1 < end) {
y = topMargin;
printer.startPage();
}
}
}
}
Print text to printer, with word wrap and pagination
/*
* Printing example snippet: print text to printer, with word wrap and pagination
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.printing.PrintDialog;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.FontDialog;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class Snippet133 {
Display display;
Shell shell;
Text text;
Font font;
Color foregroundColor, backgroundColor;
Printer printer;
GC gc;
Font printerFont;
Color printerForegroundColor, printerBackgroundColor;
int lineHeight = 0;
int tabWidth = 0;
int leftMargin, rightMargin, topMargin, bottomMargin;
int x, y;
int index, end;
String textToPrint;
String tabs;
StringBuffer wordBuffer;
public static void main(String[] args) {
new Snippet133().open();
}
void open() {
display = new Display();
font = new Font(display, "Courier", 10, SWT.NORMAL);
foregroundColor = display.getSystemColor(SWT.COLOR_BLACK);
backgroundColor = display.getSystemColor(SWT.COLOR_WHITE);
shell = new Shell(display);
shell.setLayout(new FillLayout());
shell.setText("Print Text");
shell.setMaximized(true);
text = new Text(shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL
| SWT.H_SCROLL);
text.setFont(font);
text.setForeground(foregroundColor);
text.setBackground(backgroundColor);
Menu menuBar = new Menu(shell, SWT.BAR);
shell.setMenuBar(menuBar);
MenuItem item = new MenuItem(menuBar, SWT.CASCADE);
item.setText("&File");
Menu fileMenu = new Menu(shell, SWT.DROP_DOWN);
item.setMenu(fileMenu);
item = new MenuItem(fileMenu, SWT.PUSH);
item.setText("&Open...");
item.setAccelerator(SWT.CTRL + "O");
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
menuOpen();
}
});
item = new MenuItem(fileMenu, SWT.PUSH);
item.setText("Font...");
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
menuFont();
}
});
item = new MenuItem(fileMenu, SWT.PUSH);
item.setText("Foreground Color...");
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
menuForegroundColor();
}
});
item = new MenuItem(fileMenu, SWT.PUSH);
item.setText("Background Color...");
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
menuBackgroundColor();
}
});
item = new MenuItem(fileMenu, SWT.PUSH);
item.setText("&Print...");
item.setAccelerator(SWT.CTRL + "P");
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
menuPrint();
}
});
new MenuItem(fileMenu, SWT.SEPARATOR);
item = new MenuItem(fileMenu, SWT.PUSH);
item.setText("E&xit");
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
System.exit(0);
}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
if (font != null)
font.dispose();
if (foregroundColor != null)
foregroundColor.dispose();
if (backgroundColor != null)
backgroundColor.dispose();
}
void menuOpen() {
final String textString;
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String[] { "*.java", "*.*" });
String name = dialog.open();
if ((name == null) || (name.length() == 0))
return;
try {
File file = new File(name);
FileInputStream stream = new FileInputStream(file.getPath());
try {
Reader in = new BufferedReader(new InputStreamReader(stream));
char[] readBuffer = new char[2048];
StringBuffer buffer = new StringBuffer((int) file.length());
int n;
while ((n = in.read(readBuffer)) > 0) {
buffer.append(readBuffer, 0, n);
}
textString = buffer.toString();
stream.close();
} catch (IOException e) {
MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
box.setMessage("Error reading file:\n" + name);
box.open();
return;
}
} catch (FileNotFoundException e) {
MessageBox box = new MessageBox(shell, SWT.ICON_ERROR);
box.setMessage("File not found:\n" + name);
box.open();
return;
}
text.setText(textString);
}
void menuFont() {
FontDialog fontDialog = new FontDialog(shell);
fontDialog.setFontList(font.getFontData());
FontData fontData = fontDialog.open();
if (fontData != null) {
if (font != null)
font.dispose();
font = new Font(display, fontData);
text.setFont(font);
}
}
void menuForegroundColor() {
ColorDialog colorDialog = new ColorDialog(shell);
colorDialog.setRGB(foregroundColor.getRGB());
RGB rgb = colorDialog.open();
if (rgb != null) {
if (foregroundColor != null)
foregroundColor.dispose();
foregroundColor = new Color(display, rgb);
text.setForeground(foregroundColor);
}
}
void menuBackgroundColor() {
ColorDialog colorDialog = new ColorDialog(shell);
colorDialog.setRGB(backgroundColor.getRGB());
RGB rgb = colorDialog.open();
if (rgb != null) {
if (backgroundColor != null)
backgroundColor.dispose();
backgroundColor = new Color(display, rgb);
text.setBackground(backgroundColor);
}
}
void menuPrint() {
PrintDialog dialog = new PrintDialog(shell, SWT.NONE);
PrinterData data = dialog.open();
if (data == null)
return;
if (data.printToFile) {
data.fileName = "print.out"; // you probably want to ask the user
// for a filename
}
/*
* Get the text to print from the Text widget (you could get it from
* anywhere, i.e. your java model)
*/
textToPrint = text.getText();
/*
* Do the printing in a background thread so that spooling does not
* freeze the UI.
*/
printer = new Printer(data);
Thread printingThread = new Thread("Printing") {
public void run() {
print(printer);
printer.dispose();
}
};
printingThread.start();
}
void print(Printer printer) {
if (printer.startJob("Text")) { // the string is the job name - shows up
// in the printer"s job list
Rectangle clientArea = printer.getClientArea();
Rectangle trim = printer.ruputeTrim(0, 0, 0, 0);
Point dpi = printer.getDPI();
leftMargin = dpi.x + trim.x; // one inch from left side of paper
rightMargin = clientArea.width - dpi.x + trim.x + trim.width; // one
// inch
// from
// right
// side
// of
// paper
topMargin = dpi.y + trim.y; // one inch from top edge of paper
bottomMargin = clientArea.height - dpi.y + trim.y + trim.height; // one
// inch
// from
// bottom
// edge
// of
// paper
/* Create a buffer for computing tab width. */
int tabSize = 4; // is tab width a user setting in your UI?
StringBuffer tabBuffer = new StringBuffer(tabSize);
for (int i = 0; i < tabSize; i++)
tabBuffer.append(" ");
tabs = tabBuffer.toString();
/*
* Create printer GC, and create and set the printer font &
* foreground color.
*/
gc = new GC(printer);
FontData fontData = font.getFontData()[0];
printerFont = new Font(printer, fontData.getName(), fontData
.getHeight(), fontData.getStyle());
gc.setFont(printerFont);
tabWidth = gc.stringExtent(tabs).x;
lineHeight = gc.getFontMetrics().getHeight();
RGB rgb = foregroundColor.getRGB();
printerForegroundColor = new Color(printer, rgb);
gc.setForeground(printerForegroundColor);
rgb = backgroundColor.getRGB();
printerBackgroundColor = new Color(printer, rgb);
gc.setBackground(printerBackgroundColor);
/* Print text to current gc using word wrap */
printText();
printer.endJob();
/* Cleanup graphics resources used in printing */
printerFont.dispose();
printerForegroundColor.dispose();
printerBackgroundColor.dispose();
gc.dispose();
}
}
void printText() {
printer.startPage();
wordBuffer = new StringBuffer();
x = leftMargin;
y = topMargin;
index = 0;
end = textToPrint.length();
while (index < end) {
char c = textToPrint.charAt(index);
index++;
if (c != 0) {
if (c == 0x0a || c == 0x0d) {
if (c == 0x0d && index < end
&& textToPrint.charAt(index) == 0x0a) {
index++; // if this is cr-lf, skip the lf
}
printWordBuffer();
newline();
} else {
if (c != "\t") {
wordBuffer.append(c);
}
if (Character.isWhitespace(c)) {
printWordBuffer();
if (c == "\t") {
x += tabWidth;
}
}
}
}
}
if (y + lineHeight <= bottomMargin) {
printer.endPage();
}
}
void printWordBuffer() {
if (wordBuffer.length() > 0) {
String word = wordBuffer.toString();
int wordWidth = gc.stringExtent(word).x;
if (x + wordWidth > rightMargin) {
/* word doesn"t fit on current line, so wrap */
newline();
}
gc.drawString(word, x, y, false);
x += wordWidth;
wordBuffer = new StringBuffer();
}
}
void newline() {
x = leftMargin;
y += lineHeight;
if (y + lineHeight > bottomMargin) {
printer.endPage();
if (index + 1 < end) {
y = topMargin;
printer.startPage();
}
}
}
}
Simple Print
/******************************************************************************
* All Right Reserved.
* Copyright (c) 1998, 2004 Jackwind Li Guojie
*
* Created on 2004-5-2 21:35:30 by JACK
* $Id$
*
*****************************************************************************/
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.printing.PrintDialog;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class SimplePrint {
Display display = new Display();
Shell shell = new Shell(display);
public SimplePrint() {
shell.pack();
shell.open();
PrintDialog dialog = new PrintDialog(shell);
// Opens a dialog and let use user select the
// target printer and configure various settings.
PrinterData printerData = dialog.open();
if(printerData != null) { // If a printer is selected
// Creates a printer.
Printer printer = new Printer(printerData);
// Starts the print job.
if(printer.startJob("Text")) {
GC gc = new GC(printer);
// Starts a new page.
if(printer.startPage()) {
gc.drawString("Eclipse", 200, 200);
// Finishes the page.
printer.endPage();
}
gc.dispose();
// Ends the job.
printer.endJob();
}
// Disposes the printer object after use.
printer.dispose();
System.out.println("Print job done.");
}
// Set up the event loop.
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
// If no more entries in event queue
display.sleep();
}
}
display.dispose();
}
private void init() {
}
public static void main(String[] args) {
new SimplePrint();
}
}
SWT Print and 2D Graphics
/*******************************************************************************
* Copyright (c) 2004 Berthold Daum. All rights reserved. This program and the
* accompanying materials are made available under the terms of the Common
* Public License v1.0 which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors: Berthold Daum
******************************************************************************/
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.ArmEvent;
import org.eclipse.swt.events.ArmListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.printing.PrintDialog;
import org.eclipse.swt.printing.Printer;
import org.eclipse.swt.printing.PrinterData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.CoolBar;
import org.eclipse.swt.widgets.CoolItem;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
public class widgetTest3 {
public static void main(String[] args) {
// Create display instance
final Display display = new Display();
// Create top level shell (pass display as parent)
final Shell toplevelShell = new Shell(display);
// Set title
toplevelShell.setText("TopLevel.Titelzeile");
// Fill the shell completely with content
toplevelShell.setLayout(new FillLayout());
// Create tabbed folder
TabFolder folder = new TabFolder(toplevelShell, SWT.NONE);
// Protocol selection event
folder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
System.out.println("Tab selected: "
+ ((TabItem) (e.item)).getText());
}
});
// Fill tabbed folder completely with content
folder.setLayout(new FillLayout());
Composite page1 = createTabPage(folder, "tab1");
// We can now place more GUI elements onto page1
//...
Composite page2 = createTabPage(folder, "tab2");
// We can now place more GUI elements onto page2
//...
// Display shell
toplevelShell.open();
// Event loop
while (!toplevelShell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
private static Composite createTabPage(TabFolder folder, String label) {
// Create and label a new tab
TabItem tab = new TabItem(folder, SWT.NONE);
tab.setText(label);
// Create a new page as a Composite instance
Composite page = new Composite(folder, SWT.NONE);
//... and assign to tab
tab.setControl(page);
return page;
}
/** * Menu ** */
public static Menu createMenu(final Shell toplevelShell) {
// Menuleiste anlegen
Menu menuBar = new Menu(toplevelShell, SWT.BAR);
toplevelShell.setMenuBar(menuBar);
// Menutitel anlegen
MenuItem fileTitle = new MenuItem(menuBar, SWT.CASCADE);
fileTitle.setText("File");
// Untermenu fur diesen Menutitel anlegen
Menu fileMenu = new Menu(toplevelShell, SWT.DROP_DOWN);
fileTitle.setMenu(fileMenu);
// Menueintrag anlegen
MenuItem item = new MenuItem(fileMenu, SWT.NULL);
item.setText("Exit");
// Ereignisverarbeitung fur Menueintrag
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
toplevelShell.close();
}
});
return menuBar;
}
/** * Coolbar ** */
public CoolBar createCoolBar(Composite composite) {
// Create CoolBar
final CoolBar coolbar = new CoolBar(composite, SWT.NULL);
// Create ToolBar as a component of CoolBar
final ToolBar toolbar1 = new ToolBar(coolbar, SWT.NULL);
// Create pushbutton
final ToolItem toolitem1 = new ToolItem(toolbar1, SWT.PUSH);
toolitem1.setText("Push");
toolitem1.setToolTipText("Push button");
// Create event processing for pushbutton
toolitem1.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
System.out.println("Tool button was pressed: "
+ toolitem1.getText());
}
});
// Create check button
final ToolItem toolitem2 = new ToolItem(toolbar1, SWT.CHECK);
toolitem2.setText("Check");
toolitem2.setToolTipText("Check button");
// Create CoolItem instance
final CoolItem coolitem1 = new CoolItem(coolbar, SWT.NULL);
// Assign this tool bar to the CoolItem instance
coolitem1.setControl(toolbar1);
// Compute size of tool bar
Point size = toolbar1.ruputeSize(SWT.DEFAULT, SWT.DEFAULT);
// Compute required size of CoolItems instance
size = coolitem1.ruputeSize(size.x, size.y);
// Set size for this CoolItem instance
coolitem1.setSize(size);
// The minimum size of the CoolItem is the width of the first button
coolitem1.setMinimumSize(toolitem1.getWidth(), size.y);
// Create second ToolBar instance
final ToolBar toolbar2 = new ToolBar(coolbar, SWT.NULL);
// Create two radio buttons
final ToolItem toolitem3a = new ToolItem(toolbar2, SWT.RADIO);
toolitem3a.setText("Radio");
toolitem3a.setToolTipText("Radio button a");
final ToolItem toolitem3b = new ToolItem(toolbar2, SWT.RADIO);
toolitem3b.setText("Radio");
toolitem3b.setToolTipText("Radio button b");
// Create separator
new ToolItem(toolbar2, SWT.SEPARATOR);
// Create drop-down menu button
final ToolItem toolitem5 = new ToolItem(toolbar2, SWT.DROP_DOWN);
toolitem5.setText("Drop-down-Menu");
// Add event processing to drop-down menu button
toolitem5.addSelectionListener(
// In class DropDownSelectionListener we construct the menu
new DropDownSelectionListener(composite.getShell()));
// Create second CoolItem, assing Toolbar to it and set size
final CoolItem coolitem2 = new CoolItem(coolbar, SWT.NULL);
coolitem2.setControl(toolbar2);
size = toolbar2.ruputeSize(SWT.DEFAULT, SWT.DEFAULT);
size = coolitem2.ruputeSize(size.x, size.y);
coolitem2.setSize(size);
coolitem2.setMinimumSize(toolitem3a.getWidth(), size.y);
return coolbar;
}
class DropDownSelectionListener extends SelectionAdapter {
private Menu menu;
private Composite parent;
public DropDownSelectionListener(Composite parent) {
this.parent = parent;
}
public void widgetSelected(final SelectionEvent e) {
// Create menu lazily
if (menu == null) {
menu = new Menu(parent);
final MenuItem menuItem1 = new MenuItem(menu, SWT.NULL);
menuItem1.setText("Item1");
// Set SelectionListener for menuItem1
menuItem1.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent m) {
processMenuEvent(e, menuItem1);
}
});
menuItem1.addArmListener(new ArmListener() {
public void widgetArmed(ArmEvent m) {
System.out.println("Mouse is over menu item 1");
}
});
final MenuItem menuItem2 = new MenuItem(menu, SWT.NULL);
menuItem2.setText("Item2");
// Set SelectionListener foYr menuItem1
menuItem2.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent m) {
processMenuEvent(e, menuItem2);
}
});
menuItem2.addArmListener(new ArmListener() {
public void widgetArmed(ArmEvent m) {
System.out.println("Mouse is over menu item 2");
}
});
}
// Check, if it was the arrow button that was pressed
if (e.detail == SWT.ARROW) {
if (menu.isVisible()) {
// Set visible menu invisible
menu.setVisible(false);
} else {
// Retrieve ToolItem and ToolBar from the event object
final ToolItem toolItem = (ToolItem) e.widget;
final ToolBar toolBar = toolItem.getParent();
// Get position and size of the ToolItem
Rectangle toolItemBounds = toolItem.getBounds();
// Convert relative position to absolute position
Point point = toolBar.toDisplay(new Point(toolItemBounds.x,
toolItemBounds.y));
// Set menu position
menu.setLocation(point.x, point.y + toolItemBounds.height);
// Make menu visible
menu.setVisible(true);
}
} else {
final ToolItem toolItem = (ToolItem) e.widget;
System.out.println("Tool button was pressed: "
+ toolItem.getText());
}
}
private void processMenuEvent(final SelectionEvent e,
final MenuItem item) {
// Get text of menu item
final String s = item.getText();
// Get ToolItem
final ToolItem toolItem = (ToolItem) e.widget;
// Replace ToolItem label with text of the menu item
toolItem.setText(s);
// Hide menu
menu.setVisible(false);
}
}
/** * SashForm ** */
public static SashForm createSashForm(Shell toplevelShell) {
// Create outer SashForm
SashForm sf1 = new SashForm(toplevelShell, SWT.HORIZONTAL);
// Create inner SashForm
SashForm sf2 = new SashForm(sf1, SWT.VERTICAL);
// Create content for vertical SashForm
List list1 = new List(sf2, SWT.NONE);
list1.setItems(new String[] { "red", "green", "blue" });
List list2 = new List(sf2, SWT.NONE);
list2.setItems(new String[] { "A", "B", "C" });
// Apply even weights
sf2.setWeights(new int[] { 100, 100 });
// Create content for horizontal SashForm
List list3 = new List(sf1, SWT.NONE);
list3.setItems(new String[] { "one", "two", "three", "four", "five",
"six" });
// Apply uneven weights
sf1.setWeights(new int[] { 100, 200 });
return sf1;
}
/** * StackLayout ** */
public static void createStackLayout(Composite composite) {
// Neues Composite erzeugen
final Composite stackComposite = new Composite(composite, SWT.NULL);
final StackLayout stackLayout = new StackLayout();
// Text-Buttons erzeugen
final Button buttonA = new Button(stackComposite, SWT.PUSH);
buttonA.setText("Taste A");
final Button buttonB = new Button(stackComposite, SWT.PUSH);
buttonB.setText("Taste B");
// Auf Klickereignisse reagieren
buttonA.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
stackLayout.topControl = buttonB;
// Neues Layout erzwingen
stackComposite.layout();
// Fokus auf sichtbare Taste setzen
buttonB.setFocus();
}
});
buttonB.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
stackLayout.topControl = buttonA;
// Neues Layout erzwingen
stackComposite.layout();
// Fokus auf sichtbare Taste setzen
buttonA.setFocus();
}
});
// Layout initialisieren
stackLayout.topControl = buttonA;
stackLayout.marginWidth = 10;
stackLayout.marginHeight = 5;
// Layout setzen
stackComposite.setLayout(stackLayout);
}
/** * PaintListener ** */
public static void addPaintListener(Composite composite) {
composite.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent event) {
// Get Display intsance from event object
Display display = event.display;
// Get a green system color object - we don"t
// need to dispose that
Color green = display.getSystemColor(SWT.COLOR_DARK_GREEN);
// Get the graphics context from the event object
GC gc = event.gc;
// Set line color
gc.setForeground(green);
// Get size of the Composite"s client area
Rectangle rect = ((Composite) event.widget).getClientArea();
// Now draw an rectangle
gc.drawRectangle(rect.x + 2, rect.y + 2, rect.width - 4,
rect.height - 4);
}
});
}
/** * Fonts ** */
public static void drawItalic(Composite composite, GC gc) {
// Get Display instance
Display display = composite.getDisplay();
// Fetch system font
Font systemFont = display.getSystemFont();
// FontData objects contain the font properties.
// With some operating systems a font may possess multiple
// FontData instances. We only use the first one.
FontData[] data = systemFont.getFontData();
FontData data0 = data[0];
// Set the font style to italic
data0.setStyle(SWT.ITALIC);
// Create a new font
Font italicFont = new Font(display, data0);
// Set the new font in the graphics context
gc.setFont(italicFont);
// TODO: call italicFont.dispose() in the DisposeListener
// of composite
// Draw text at position (4,4) with a transparent background (true).
gc.drawText("Hello", 4, 4, true);
}
/** * Images ** */
public static void doubleBuffering(Composite composite) {
// Create canvas
final Canvas canvas = new Canvas(composite, SWT.BORDER);
// Get white system color
Color white = canvas.getDisplay().getSystemColor(SWT.COLOR_WHITE);
// Set canvas background to white
canvas.setBackground(white);
// Add paint listener
canvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
// Get Display instance from the event object
Display display = e.display;
// Get black and red system color - don"t dispose these
Color black = display.getSystemColor(SWT.COLOR_BLACK);
Color red = display.getSystemColor(SWT.COLOR_RED);
// Get the graphics context from event object
GC gc = e.gc;
// Get the widget that caused the event
Composite source = (Composite) e.widget;
// Get the size of this widgets client area
Rectangle rect = source.getClientArea();
// Create buffer for double buffering
Image buffer = new Image(display, rect.width, rect.height);
// Create graphics context for this buffer
GC bufferGC = new GC(buffer);
// perform drawing operations
bufferGC.setBackground(red);
bufferGC.fillRectangle(5, 5, rect.width - 10, rect.height - 10);
bufferGC.setForeground(black);
bufferGC.drawRectangle(5, 5, rect.width - 10, rect.height - 10);
bufferGC.setBackground(source.getBackground());
bufferGC.fillRectangle(10, 10, rect.width - 20,
rect.height - 20);
// Now draw the buffered image to the target drawable
gc.drawImage(buffer, 0, 0);
// Dispose of the buffer"s graphics context
bufferGC.dispose();
// Dispose of the buffer
buffer.dispose();
}
});
}
/** * Printing ** */
public static void createPrintButton(final Composite composite) {
// Create button for starting printing process
final Button printButton = new Button(composite, SWT.PUSH);
printButton.setText("Print");
// React to clicks
printButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
// Get Shell instance
Shell shell = composite.getShell();
// Create printer selection dialog
PrintDialog printDialog = new PrintDialog(shell);
// and open it
PrinterData printerData = printDialog.open();
// Check if OK was pressed
if (printerData != null) {
// Create new Printer instance
Printer printer = new Printer(printerData);
// Create graphics context for this printer
GC gc = new GC(printer);
// Open printing task
if (!printer.startJob("Hello"))
System.out.println("Starting printer task failed");
else {
// Print first page
if (!printer.startPage())
System.out.println("Printing of page 1 failed");
else {
// Get green system color from printer
// and set it as text color
Color green = printer
.getSystemColor(SWT.COLOR_DARK_GREEN);
gc.setForeground(green);
// Draw text
gc.drawText("Hello World", 4, 4, true);
// Close page
printer.endPage();
}
// Print second page
if (!printer.startPage())
System.out.println("Printing of page 2 failed");
else {
// Get blue system color from printer
// and set it as text color
Color blue = printer.getSystemColor(SWT.COLOR_BLUE);
gc.setForeground(blue);
// Draw text
gc.drawText("Hello Eclipse", 4, 4, true);
// Close page
printer.endPage();
}
// Close printing task
printer.endJob();
}
// Release operating system resources
gc.dispose();
printer.dispose();
}
}
});
}
}