在SWT窗口中使用Draw2D绘制任意曲线

首先在工程中导入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);
	}
}

运行结果如下:

上图中松开鼠标后,虚线变成实线。

转载于:https://my.oschina.net/plumsoft/blog/29505

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值