java - Swing - 列表在 PaintComponent 方法内不起作用的问题

标签 java swing paint

我正在尝试渲染多个 fighters 的位置在屏幕上。相关代码如下:

public void run() {
        double ns = 1000000000.0 / tps;
        double delta = 0;

        int frames = 0;
        int updates = 0;

        long lastTime = System.nanoTime();
        long timer = System.currentTimeMillis();

        while (running) {
            long now = System.nanoTime();

            delta += (now - lastTime) / ns;
            lastTime = now;

            while(delta >= 1) {
                update();
                updates++;
                delta--;
            }

            frame.getContentPane().repaint();
            frames++;

            if(System.currentTimeMillis() - timer >= 1000) {
                timer += 1000;
                frame.setTitle(title + "  |  " + updates + " ups, " + frames + " fps");
                frames = 0;
                updates = 0;
            }
        }

        stop();
    }

    private void update() {

         if (Math.random() < .1) {

            Fighter newFighter = new Fighter();
            fighterList.add(newFighter);

        } 

    }
    public void paintComponent(Graphics g) {
          super.paintComponent(g);  // paint background
          setBackground(Color.BLUE);
          System.out.println(fighterList.size());
          for (int i = 0; i<fighters; i++) {
              System.out.println("Attempted");
              g.setColor(Color.GREEN);
              g.drawRect((int) fighterList.get(i).xPos,
                      (int) fighterList.get(i).yPos,
                      fighterList.get(i).radius,
                      fighterList.get(i).radius);
              System.out.println("Rendered");
          }

       }
public static void main(String[] args) {
        Game game = new Game();
        game.frame.setContentPane(new Game());
        game.frame.setResizable(false);
        game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        game.frame.setLocationRelativeTo(null); 
        game.frame.setVisible(true); 

        game.start();


    } 

问题是,屏幕上没有绘制任何内容。此外,运行 System.out.println(fighterList.size());根据运行位置给出不同的输出 - 当在 paintComponent 内运行时它总是返回零,而在 update 内运行时它返回适当的金额。这是范围问题,还是我还遗漏了其他内容?

最佳答案

很可能是同步问题。您的 paintComponent() 方法始终从 EDT(事件调度线程)调用,而您的 run() 方法在其自己的单独线程中运行。这是调用 update() 的地方,它将新的 Fighter 添加到列表中。

您需要适当的同步,以便两个(或所有)线程都能看到相同的一致数据。

此外,由于您的模型(数据)可能会在重新绘制期间修改,因此您还应该“克隆”模型以避免绘制不一致的模型。或者,如果您不想克隆它,请同步对模型的访问,以便在绘制模型时无法对其进行修改。

关于java - Swing - 列表在 PaintComponent 方法内不起作用的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27166717/

相关文章:

java - 按照 MVC 模式在 Java 中实现 JFileChooser

java - 重新画一个正方形?

android - 在位图上绘制文本时旋转文本

java - 在不依赖操作系统时间的情况下获取 UTC 时间

java - Hashmap 持有不同的数据类型作为值,例如 Integer、String 和 Object

java - 如果显示区域太小,JComboBox 会带有工具提示,同时保持外观和感觉

java - 查找注册到某个操作的所有组件

java - 更改 logback 级别并保存到 logback.xml

java - 测试期间 GWT 中的控制台日志不会出现在 Chrome 驱动程序中

java - MouseListener 帮助 Java