Search code examples
javaswtuigraphicscontext

Scroll not working with Canvas & GC in Java SWT


I am trying to draw some shapes and lines on a SWT Canvas object using GC[Graphics Context ]. The Canvas object is initialized with fixed size & V_SCROLL|H_SCROLL. I want the Canvas to be scroll-able once GC exceeds the Canvas boundaries. Though the scroll bars are getting appeared they are not working and the last part of lines are getting truncated.

Group grpSchema = new Group(shell, SWT.NONE);
    grpSchema.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
    grpSchema.setText("Picture");

    Button btnPaint = new Button(shell, SWT.NONE);
    btnPaint.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1));
    btnPaint.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            if(null != canvas){
                canvas.dispose();
            }
            canvas = new Canvas(grpSchema, SWT.V_SCROLL|SWT.H_SCROLL);
            canvas.setBounds(10, 20, 200, 200);
            canvas.addPaintListener(new PaintListener() {
                @Override
                public void paintControl(PaintEvent arg0) {
                    GC gc = arg0.gc;
                    gc.drawLine(0, 0, 200, 500);
                }
            });
        }
    });
    btnPaint.setText("paint");

Solution

  • I just got scroll-able Group with an Image drawn using GC in SWT. You need to create and image using GC and then set to a Group which is created inside a ScrollableComposite.

    ScrolledComposite scroll = new ScrolledComposite(shell, SWT.V_SCROLL|SWT.H_SCROLL);
    scroll.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
    
    Group grpDraw = new Group(scroll, SWT.V_SCROLL|SWT.H_SCROLL);
    grpDraw.setText("Picture");
    grpDraw.setBounds(0, 0, 200, 200);
    
    Button btnPaint = new Button(shell, SWT.NONE);
    btnPaint.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1));
    btnPaint.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                Image image = new Image(display, 1000, 1000);
                GC gc = new GC(image);
                gc.setBackground(display.getSystemColor(SWT.COLOR_YELLOW));
                gc.fillOval(50,50,100,100);
                gc.setForeground(display.getSystemColor(SWT.COLOR_DARK_GREEN));
                gc.dispose();
                grpDraw.setBackgroundImage(image);
                scroll.setContent(grpDraw);
            }
        });
    btnPaint.setText("paint");
    

    enter image description here