首先在工程中导入Draw2D包。
建立一个Java Project之后,在Package Explorer中右击工程名,选择下图所示菜单:
这样,工程下会出现一个META-INF文件夹,双击打开其中的.MF文件,选择Dependencies选项,在Required Plug-ins中单击Add...按钮,输入*.draw2d,添加draw2d后保存改.MF文件。
这样就可以使用Draw2D绘图了。
在工程下新建两个.java文件,分别如下:
DrawLineListener.java
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.MouseEvent;
import org.eclipse.draw2d.MouseListener;
import org.eclipse.draw2d.MouseMotionListener;
import org.eclipse.draw2d.PolylineConnection;
import org.eclipse.swt.SWT;
public class DrawLineListener extends MouseMotionListener.Stub implements MouseListener{
PolylineConnection connection=null;
IFigure figure;
public void addDrawLineListener(IFigure figure){
this.figure=figure;
figure.addMouseMotionListener(this);
figure.addMouseListener(this);
}
@Override
public void mousePressed(MouseEvent me) {
connection=new PolylineConnection();
connection.setLineStyle(SWT.LINE_DOT);
connection.removeAllPoints();
connection.addPoint(me.getLocation());
figure.add(connection);
}
@Override
public void mouseReleased(MouseEvent me) {
connection.setLineStyle(SWT.LINE_CUSTOM);
}
@Override
public void mouseDoubleClicked(MouseEvent me) {
// TODO Auto-generated method stub
}
public void mouseDragged(MouseEvent e) {
connection.addPoint(e.getLocation());
}
}
DrawLineFrame.java
import org.eclipse.draw2d.LightweightSystem;
import org.eclipse.draw2d.Panel;
import org.eclipse.draw2d.XYLayout;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class DrawLineFrame {
protected Shell shell;
public static void main(String[] args) {
try {
DrawLineFrame window = new DrawLineFrame();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
protected void createContents() {
shell = new Shell();
shell.setSize(400, 300);;
shell.setText("画线演示");
Panel panel = new Panel();
panel.setLayoutManager(new XYLayout());
DrawLineListener drawLine=new DrawLineListener();
drawLine.addDrawLineListener(panel);
LightweightSystem lws = new LightweightSystem(shell);
lws.setContents(panel);
}
}
运行结果如下:
上图中松开鼠标后,虚线变成实线。