Question

I have the following code:

   final Canvas canvas = new Canvas(mainshell, SWT.NO_REDRAW_RESIZE);

     canvas.setBounds(0, 0, mainshell.getSize().x, mainshell.getSize().y);

     canvas.setBackgroundImage( new Image(display, "BlueBack.jpg" ));
     canvas.setFont(font);

      GC gc = new GC(canvas);

      gc.drawText("Test", 0, 0, true);

      gc.dispose();

        canvas.addPaintListener(new PaintListener() {
            public void paintControl(PaintEvent e) {    

           e.gc.drawText("String", 170, 30, true);

           e.gc.drawText("Another Unimportant String", 80, 90, true);


           int I = 140;
           int i = 1;

         String[] strings = Stuff.getUnimportantStringArray();

         if(strings != null)
           for(String string : strings){

               e.gc.drawText( i + "      " + string , 120, I, true);

               I += 50;
               i++;

           }

            }
        });

The code that I am having the problem with is this:

 GC gc = new GC(canvas);

      gc.drawText("Test", 0, 0, true);

      gc.dispose();

The gc.drawText(); is not drawing the String "Test" on the canvas as I expected it would.

Here is my Question:

Why is the gc.drawText("Test", 0, 0, true"); not working, but the e.gc.drawText("String", 170, 30, true); inside the PaintListeneris working ?

Was it helpful?

Solution

The paintControl() method is called whenever the canvas needs to be redrawn which could happen any number of times. For example, the PaintListener is used when the canvas is resized (try putting a breakpoint on paintControl(), resize the window, and see for yourself). All drawing you need to do should be in the PaintListener.

Also, you shouldn't use setBounds() here. Use a layout instead:

mainShell.setLayout(new FillLayout());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top