canvas.addPaintListener(new PaintListener()
{
@Override
public void paintControl(PaintEvent e)
{
// Get the Graphics Context (GC) from the PaintEvent
GC gc = e.gc;
// Get the width of the canvas
int canvasWidth = canvas.getSize().x;
String text = "The Quick Brown Fox";
// Use the method stringExtent(String) which returns a org.eclipse.swt.graphics.Point
// and access the x variable of the Point which contains the width of the given String
// when plotted with the current Font on the Canvas
int textWidth = gc.stringExtent(text).x;
// Plot centred by subtracting half the width of the string from the centre of the Canvas width
gc.drawText(text, canvasWidth / 2 - textWidth / 2, 0);
}
});
{
@Override
public void paintControl(PaintEvent e)
{
// Get the Graphics Context (GC) from the PaintEvent
GC gc = e.gc;
// Get the width of the canvas
int canvasWidth = canvas.getSize().x;
String text = "The Quick Brown Fox";
// Use the method stringExtent(String) which returns a org.eclipse.swt.graphics.Point
// and access the x variable of the Point which contains the width of the given String
// when plotted with the current Font on the Canvas
int textWidth = gc.stringExtent(text).x;
// Plot centred by subtracting half the width of the string from the centre of the Canvas width
gc.drawText(text, canvasWidth / 2 - textWidth / 2, 0);
}
});