I’m having trouble with printing a rectangle to a shell using PaintListeners and
GCs in SWT. If necessary I can post the main method as well, but all that method does is produce an input screen and then open the shell below. I think the error is in SimDisp.
Using the class at the website below, the same process was used and a rectangle actually showed up.
http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/HowtodrawdirectlyonanSWTControl.htm
Does anyone know why GC gc = event.gc; produces an error? – gc cannot be resolved or is not a field.
import java.awt.event.PaintEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import java.util.ResourceBundle;
public static Shell SimDisp (Shell s1){
final Shell shell2 = new Shell(s1.getDisplay());
shell2.setText("Linear Magnetic Accelerator Simulation");
/*
Canvas canvas = new Canvas(shell2, SWT.NONE);
LightweightSystem lws = new LightweightSystem(canvas);
RectangleFigure rect = new RectangleFigure();
rect.setBounds(new org.eclipse.draw2d.geometry.Rectangle(20,20,100,100));
rect.setBackgroundColor(ColorConstants.green);
rect.setForegroundColor(ColorConstants.gray);
lws.setContents(rect);
*/
/*
Canvas canvas = new Canvas(shell2, SWT.NONE);
Rectangle rect = new Rectangle (20,20,100,100);
GC gc = new GC (canvas);
gc.drawRectangle(rect);
*/
final Color red = new Color(s1.getDisplay(), 0xFF, 0, 0);
shell2.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent event) {
GC gc = event.gc; // This line produces an error - gc cannot be resolved or is not a field.
gc.setForeground(red);
Rectangle rect = shell2.getClientArea();
gc.drawRectangle(rect.x + 10, rect.y + 10, rect.width - 20,
rect.height - 20);
gc.drawString("Hello_world", rect.x + 20,
rect.y + 20);}
@Override
public void paintControl(org.eclipse.swt.events.PaintEvent e) {
// TODO Auto-generated method stub
}});
return shell2;}
Because you imported
java.awt.event.PaintEventinstead oforg.eclipse.swt.events.PaintEvent.