Java SWT使用鼠标事件在画布上绘制形状
我想制作一个应用程序,以便使用JavaSWT画布绘制类似于绘画的表单(矩形、直线、正方形、箭头)。我使用鼠标事件(向上、向下和移动)来获得画布的Y和X位置。每个表单类型都有一个按钮,可以获得画布鼠标位置,并使用鼠标事件绘制所选表单。我的问题是,当我画第一个形状(圆、正方形、线)时,一切都正常,但当我画第二个形状时,第一个就消失了。重画画布后,如何使第一个表单保持绘制状态 变量:Java SWT使用鼠标事件在画布上绘制形状,java,canvas,swt,draw,draw2d,Java,Canvas,Swt,Draw,Draw2d,我想制作一个应用程序,以便使用JavaSWT画布绘制类似于绘画的表单(矩形、直线、正方形、箭头)。我使用鼠标事件(向上、向下和移动)来获得画布的Y和X位置。每个表单类型都有一个按钮,可以获得画布鼠标位置,并使用鼠标事件绘制所选表单。我的问题是,当我画第一个形状(圆、正方形、线)时,一切都正常,但当我画第二个形状时,第一个就消失了。重画画布后,如何使第一个表单保持绘制状态 变量: private static boolean drag = false; private Canvas compCan
private static boolean drag = false;
private Canvas compCanvas;
private Button btnSend, btnAdd,btnFreeHand,btnArrow,btnCircle,btnSquare,btnLine;
private Composite mainPanel;
compCanvas = new Canvas(mainPanel, SWT.NONE);
mouseEvents():
btnSquare.selectionListener()和声明:
btnSquare = new Button(compSendAdd, SWT.NONE);
btnSquare.setLayoutData(new RowData(25, 25));
btnSquare.setImage(squareIcon);
btnSquare.addSelectionListener(new SelectionListener(){
private void btnSquare(){
mouseEvents();
//LightweightSystem lws = new LightweightSystem(compCanvas);
compCanvas.addListener(SWT.Paint, new Listener(){
public void handleEvent(Event e){
if(drag){
GC gc = e.gc;
//gc.setAlpha(128);
int minX = Math.min(startX,endX);
int minY = Math.min(startY,endY);
int maxX = Math.max(startX, endX);
int maxY = Math.max(startY, endY);
int width = maxX - minX;
int height = maxY - minY;
gc.fillRectangle(minX, minY,width,height);
}
}
});
}
public void widgetSelected(SelectionEvent event) {
btnSquare();
}
public void widgetDefaultSelected(SelectionEvent event) {
btnSquare();
}
});
默认情况下,每次调用
SWT.Paint
侦听器时,控件都会填充当前背景色。你需要关掉这个
为此,请在画布上指定SWT.NO_BACKGROUND
样式
compCanvas = new Canvas(mainPanel, SWT.NO_BACKGROUND);
您还需要在第一次绘制画布时填充背景。使用x、y、width和height字段创建类形状
class Shape {
public int x; // coordiates
public int y;
public int width;
public int heigth;
String type; // "rect" for example
public Shape(int x, int y, int width, int height, String type) {
this.x = x;
this.y = y;
this.width = width;
this.heigth = height;
this.type = type;
}
}
鼠标悬停后,根据选择的按钮将形状存储在列表中
List<Shape> shapes = new ArrayList<Shape>();
shapes.add(new Shape(x, y, width, height, getType()));
嗨,格雷格,谢谢你的回答。我指定了SWT.NONE
,因为我在应用程序启动时设置了Canvas
背景图像,然后我需要在图像上方绘制表单并保存它;设置画布背景代码:compCanvas.setBackground(新颜色(Display.getDefault(),54,54,54));compCanvas.setBackgroundImage(canvasBcg);compCanvas.setBackgroundMode(SWT.INHERIT_FORCE)代码>还有别的方法吗?
List<Shape> shapes = new ArrayList<Shape>();
shapes.add(new Shape(x, y, width, height, getType()));
for(Shape s: shapes) {
//draw shape s
}