我想製作一個應用程序,以便使用Java SWT Canvas在繪畫中繪製窗體(矩形,線條,方形,箭頭)。我使用鼠標事件(向上,向下和移動)來獲取畫布Y和X位置。並且我有一個按鈕,用於獲取畫布鼠標位置的每個表單類型,並使用鼠標事件繪製選定的表單。我的問題是,當我繪製第一種形式(圓形,方形,線形)時,一切正常,但是在繪製第二種形式時,第一種刪除。如何在重畫畫布後使第一個窗體保持繪製狀態?Java SWT在畫布上使用鼠標事件繪製圖形
變量:
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():
private void mouseEvents(){
compCanvas.addListener(SWT.MouseDown, new Listener(){
public void handleEvent(Event e){
System.out.println("Mouse event on canvas DOWN: X VALUE:"+e.x+"Y VALUE:"+e.y);
startY = e.y;
startX = e.x;
drag = true;
}
});
compCanvas.addListener(SWT.MouseUp, new Listener(){
public void handleEvent(Event e){
System.out.println("Mouse event on canvas UP: X VALUE:"+e.x+"Y VALUE:"+e.y);
endY = e.y;
endX = e.x;
drag = false;
//compCanvas.redraw();
}
});
compCanvas.addListener(SWT.MouseMove, new Listener(){
public void handleEvent(Event e){
System.out.println("Mouse event on canvas MOVE: X VALUE:"+e.x+"Y VALUE:"+e.y);
if(drag){
endY = e.y;
endX = e.x;
compCanvas.redraw();
}
}
});
};
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.NONE'是因爲我在App Launch上設置了'Canvas'背景圖像,之後我需要在圖像上方繪製表單,並且需要保存它; 設置畫布背景代碼: 'compCanvas.setBackground(new Color(Display.getDefault(),54,54,54)); compCanvas.setBackgroundImage(canvasBcg); compCanvas.setBackgroundMode(SWT.INHERIT_FORCE);' – vinistig
有另一種方法來做到這一點? – vinistig