【问题标题】:Nothing shows up to the screen when I call the repaint() method当我调用 repaint() 方法时,屏幕上什么也没有显示
【发布时间】:2014-05-18 00:09:17
【问题描述】:

这可能是一个常见问题,但可能对每种情况都是独一无二的。

这是我在代码中调用.repaint() 的地方:

timer = new Timer(5, new ActionListener() {
        double t = 0;
        public void actionPerformed(ActionEvent e) {

            ArrayList<Particle> fireworks = manager.getFireworks(t/1000);
            showFireworks(fireworks,t/1000);
            t = t + timer.getDelay();
            for (Particle projectile : fireworks) {
                canvas = new FireworksDisplay(projectile);
                canvas.repaint();
                add(canvas);
            }
        }
    });

它正在创建一个烟花粒子的 ArrayList(它可以正常工作,因为我测试了在控制台窗口中打印 (x,y) 位置并且它运行良好)。 我希望我的程序在屏幕上为我的 ArrayList 列表中的每个成员绘制一个小粒子

这是我的 DrawPanel

    private class FireworksDisplay extends JPanel {
    private Color colour;
    private int xPos;
    private int yPos;
    private int size;
    public FireworksDisplay(Particle particle) {
        super();
        String string = particle.getColour();
        string = string.toLowerCase();
        switch(string) {
        case "blue":    this.colour = Color.blue;
                        break;
        case "red":     this.colour = Color.red;
                        break;
        case "green":   this.colour = Color.green;
                        break;
        case "orange":  this.colour = Color.orange;
                        break;
        case "cyan":    this.colour = Color.cyan;
                        break;
        case "magenta": this.colour = Color.magenta;
                        break;
        case "yellow":  this.colour = Color.yellow;
                        break;
        case "pink":    this.colour = Color.pink;
                        break;
        default:        this.colour = Color.white;
                        break;
        }
        double[] positions = particle.getPosition();
        this.xPos = (int) (getWidth()*positions[0]*(50) + tubeImage.getSize().width/2);
        this.yPos = (int) (getHeight()*positions[1]*(50) + tubeImage.getSize().height - 100);

        this.size = particle.getRenderSize();

    }
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(colour);
        g.fillOval(xPos, yPos, size, size);
    }
}

由于某种原因,即使我绘制的所有其他时间都成功,它也没有绘制到屏幕上。

我发布的代码有问题,还是您认为其他地方有问题?

【问题讨论】:

  • 使用整个 JComponent/JPanel 来表示单个椭圆是一种浪费。 JComponent 不是“精灵”。但是,您打电话给add(canvas) - 它在哪里?也就是说,您在哪个组件上调用add?它有 LayoutManager 吗?您没有设置 FireworksDisplay 实例的大小和/或边界......

标签: java swing arraylist paintcomponent repaint


【解决方案1】:

记住,实例化后需要调用Timerstart()方法。

此外,每次Timer 触发时,您都会添加一个新的 JPanel。您可能需要重写代码,以便简单地绘制新的Particles。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2019-08-21
    • 2021-10-09
    • 1970-01-01
    • 2011-12-28
    相关资源
    最近更新 更多