不paint()怎么显示你的组件?

解决方案 »

  1.   

    问题每个动作paint()的次数很多,如果paint()里内容很多的话就会有很严重的影响。本来设想是做了一个动作之后paint()就可以了,可是我发现做动作时在动作传给Listener之前就已经paint()了一遍,做动作自己又必须paint()一遍,做完了动作它又自动paint()。盼望有熟悉swing内部机制的高手赐教。 拜了。
      

  2.   

    不知道可以避免paint()的方法
      只知道在awt中可以override update()方法来避免清除背景,直接调用paint()来避免闪烁,而swing中内置了double-buffering方法,一般可以避免闪烁问题。
    并且当paint components in swing,它不会invoke update()方法,因此swing编程不需改update()方法, 还有swing中的paint()实际上是调用paintComponent(),paintBorder(),paintChildren()方法来工作的,通常只需要override paintComponent();
      我看过一本书说假设paint是time-consuming的话,一般用paint发生变化的区域来提高性能
    继续关注中
    Although, in general, using Swing components does avoid the flicker problem, you may need to make your painting code a little smarter. Because Swing doesn’t allow you to override the update() method, your entire component (background and foreground in this example) gets painted each time paintComponent() is called. If your paint code is time-consuming, you may have to use the clipping region more often and repaint only the areas that need repainting. Understanding the paint/repaint/update mechanisms allows you to produce significantly better code.
      

  3.   

    class Painter extends JComponent {
        private int count = 0;
        public void repaint(){    }
        public void paint(Graphics g) {
            g.setColor(SystemColor.blue);
            g.drawString("Test(20, 20)", 20, 20);
            g.drawString("Test(200, 200)", 200, 200);
            g.drawRect(100, 100, 250, 250);
            g.drawRect(200, 200, 500, 500);
            count ++;
            System.out.println("painted " + count);
            super.repaint();
        }
    }