开发者

Clickable object on a canvas Image in SWT

I create an image using a filter on an image

private void createContents(final Shell shell) { 
shell.setLayout(new FillLayout());
// Create the canvas for drawing
canvas = new Canvas(shell,SWT.NO_BACKGROUND);


canvas.addPaintListener(new PaintListener() {
  public void paintControl(PaintEvent event) {
  Image image = new Image(shell.getDisplay(), canvas.getBounds());
  Image image2 = new Image(shell.getDisplay(), canvas.getBounds());
  //... I add some figure to the images

  ImageData data = image.getImageData();
  ImageData data2 = image2.getImageData();

  for(int j=0;j<rect.width;j++){
   for(int i=0;i<rect.height;i++){
     if(data.getPixel(j, i)<1){
       data.setPixel(j, i , data2.getPixel(j, i));
      }                 
    }
   }

How can I add some clickable开发者_运维问答 objects to the figure?


So the best way is to add a Mouse control listener to the canvas?

// Create the canvas for drawing
 canvas = new Canvas(shell,SWT.NO_BACKGROUND);
 canvas.addMouseListener(new MouseListener(){
    @Override
    public void mouseDoubleClick(MouseEvent e) {
       // TODO Auto-generated method stub   
    }
    @Override
    public void mouseDown(MouseEvent e) {
       // TODO Auto-generated method stub
       System.out.println("Click"); 
    }
    @Override
    public void mouseUp(MouseEvent e) {
       // TODO Auto-generated method stub   
    }       
});

And then control where the click is, maybe using the Rectangle.containt(int x, int y);


If you are painting the objects directly to the canvas, i.e. not adding them as components/widgets to the canvas, then you will need to determine what objects were clicked on your own. This is the case since the canvas doens't know anything about what you draw to it. You can add a mouse listener to the canvas that receives click events and then determine if any of those clicks are inside of the bounds of the objects that you drew.

You could alternatively subclass Control with your clickable object class. Then, add a mouseListener to your custom Control and add it to the canvas.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜