如何不用repaint()绘制某些像素?

时间:2017-03-03 00:34:23

标签: java swing paintcomponent

我有一个带有paintComponent的JPanel,在面板上我绘制了根据Timer对象移动的粒子。我想要一些粒子(前十个)留下痕迹,即当它们被涂漆时,我希望这个位置保持涂色。我想重新绘制剩下的粒子。

使用repaint()时是否有某种方法可以保留某些组件? 我无法弄明白,所以我尝试了类似下面的内容。但是,当我取消注释中间循环时,窗口只是灰色,我无法看到粒子。就像现在一样,它令我满意。它只是变得太重了吗?当我只使用10个粒子运行它时,它仍然无法工作。

另外,神秘地(至少对我来说),它似乎只能在最后一个循环中使用repaint()方法,但是在最后一个循环之后。奇怪?

public void paintComponent(Graphics g){
        //Paints particles in appropriate color.
        super.paintComponent(g);
        Model traced = new Model();   //Initialize a Model-object to keep traced positions
        for(int i=10; i<myModel.size(); ++i){
            Particle particle = myModel.getParticle(i);
            if (particle.isMoving){
                g.setColor(Color.GRAY);
            }
            else{
                g.setColor(Color.MAGENTA);
            }
            int xInt = (int) Math.round(particle.x);
            int yInt = (int) Math.round(particle.y);
            g.fillOval(xInt, yInt, 2, 2);
            }

    /** for (Particle p : traced){   //I try to paint the traced positions
            g.setColor(Color.RED);
            g.drawOval((int) p.x,(int) p.y,1,1);
        }*/

        for(int i = 0; i<10; ++i){
            Particle particle = myModel.getParticle(i);
            traced.addParticle(particle); // Add the first ten to "traced" model.
            if (particle.isTracked){
                g.setColor(Color.GREEN);
                int xInt = (int) Math.round(particle.x);
                int yInt = (int) Math.round(particle.y);
                g.drawLine(xInt+2, 0, xInt+2, 250);
                g.drawLine(0, yInt+2, 250, yInt+2);
                g.setColor(Color.RED);
                g.fillOval(xInt, yInt, 4, 4);
                g.setColor(Color.WHITE);
                g.fillRect(xInt, yInt-12, 8, 12);
                g.setColor(Color.BLUE);
                g.drawString(Integer.toString(i), xInt, yInt);
            }
            repaint();
        }

这是最后几个错误:

at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:714)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

0 个答案:

没有答案