Java SWT GC不在Canvas上绘制文本

时间:2014-01-26 12:35:44

标签: java canvas garbage-collection swt drawtext

我有以下代码:

   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++;

           }

            }
        });

我遇到问题的代码是:

 GC gc = new GC(canvas);

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

      gc.dispose();

gc.drawText();没有像我预期的那样在画布上绘制字符串"Test"

这是我的问题:

为什么gc.drawText("Test", 0, 0, true");无效,但e.gc.drawText("String", 170, 30, true);内的PaintListener有效?

1 个答案:

答案 0 :(得分:2)

每当需要重绘画布时调用paintControl()方法,这可能会发生任何次数。例如,在调整画布大小时使用PaintListener(尝试在paintControl()上放置一个断点,调整窗口大小,然后自己查看)。您需要做的所有绘图应该在PaintListener

此外,您不应在此处使用setBounds()。改为使用布局:

mainShell.setLayout(new FillLayout());