Java 从ArrayList重新绘制类的实例

Java 从ArrayList重新绘制类的实例,java,swing,arraylist,paint,repaint,Java,Swing,Arraylist,Paint,Repaint,好的,所以我对JavaSwing非常陌生,而且是Java的初学者。我现在的问题是我设计了一个“城市景观”。我正在研究一个飞碟,但我随机生成的建筑继续得到再生我想知道是否有一种方法可以像我尝试的那样将我的建筑实例保存到ArrayList中,并在每次调用paint时从该列表中绘制该选择。我尝试了我想到的方法,我相信它在运行时会崩溃,因为它甚至没有打开JFrame,而是一次又一次地产生错误。以下是我所拥有的: 城市景观等级(主要等级): 建筑物类(生成建筑物的类): import java.awt.*

好的,所以我对JavaSwing非常陌生,而且是Java的初学者。我现在的问题是我设计了一个“城市景观”。我正在研究一个飞碟,但我随机生成的建筑继续得到再生我想知道是否有一种方法可以像我尝试的那样将我的建筑实例保存到ArrayList中,并在每次调用paint时从该列表中绘制该选择。我尝试了我想到的方法,我相信它在运行时会崩溃,因为它甚至没有打开JFrame,而是一次又一次地产生错误。以下是我所拥有的:

城市景观等级(主要等级):

建筑物类(生成建筑物的类):

import java.awt.*;
公营楼宇
{
私有整数maxX=784;
私有整数maxY=712;
私有整数宽度=(int)(Math.random()*100+100);
私有整数高度=(整数)(Math.random()*350+100);
私有整数行=数学圆((高度)/25);
私有int列=数学圆(宽度/25);
公共建筑物()
{
RememberBuildings.addBuilding();
}
公共空间涂料(图g)
{ 
Graphics2D g2d=(Graphics2D)g;
颜色泛黄=新颜色(255,255,0,59);
g2d.setColor(Color.BLACK);
g2d.fillRect(0,0,maxX,maxY);
g2d.setColor(Color.WHITE);
g2d.fillRect(5,5,25,25);
int a=0;
对于(int i=10;i
  • 避免覆盖
    paint
    ,改用
    paintComponent
    。在执行任何自定义绘制之前,始终调用
    super
    paint方法以确保绘制链得到维护。有关更多详细信息,请参阅和
  • 注意,Swing不是线程安全的,从事件调度线程的上下文之外更新任何组件(或组件可能依赖的任何变量)都是不明智的。一个简单的解决方案可能是使用Swing
    计时器,而不是
    while(true)
    循环和
    线程。sleep
    。有关更多详细信息,请参阅
  • 您还应该仅从事件调度线程的上下文中创建和修改UI组件,有关更多详细信息,请参阅
  • <> LI>如果你的代码不起作用,你应该考虑提供一个演示你的问题的代码。这不是一个代码转储,而是你正在做的一个例子,它突出了你所面临的问题。这将导致更少的混乱和更好的响应。很难知道它为什么不工作以及如何修复它
      • 避免覆盖
        paint
        ,改用
        paintComponent
        。在执行任何自定义绘制之前,始终调用
        super
        paint方法以确保绘制链得到维护。有关更多详细信息,请参阅和
      • 注意,Swing不是线程安全的,从事件调度线程的上下文之外更新任何组件(或组件可能依赖的任何变量)都是不明智的。一个简单的解决方案可能是使用Swing
        计时器,而不是
        while(true)
        循环和
        线程。sleep
        。有关更多详细信息,请参阅
      • 您还应该仅从事件调度线程的上下文中创建和修改UI组件,有关更多详细信息,请参阅
      • <> LI>如果你的代码不起作用,你应该考虑提供一个演示你的问题的代码。这不是一个代码转储,而是你正在做的一个例子,它突出了你所面临的问题。这将导致更少的混乱和更好的响应。很难知道它为什么不工作以及如何修复它
      因此,每次调用
      Buildings#paint
      时,它都会重新生成所有构建,这是随机完成的

      public void paint(Graphics g) {
          Graphics2D g2d = (Graphics2D) g;
      
          Color transYellow = new Color(255, 255, 0, 59);
      
          g2d.setColor(Color.BLACK);
          g2d.fillRect(0, 0, maxX, maxY);
      
          g2d.setColor(Color.WHITE);
          g2d.fillRect(5, 5, 25, 25);
      
          int a = 0;
      
          for (int i = 10; i < 634; i += (a + 10))//buildings
          {
      
              g2d.setColor(Color.GRAY);
              g2d.drawRect(i, maxY - height, width, height);
              g2d.fillRect(i, maxY - height, width, height);
      
              rows = Math.round((height) / 25);
              columns = Math.round(width / 25);
      
              for (int j = 1; j <= columns; j++)//windows
              {
                  for (int k = 1; k <= rows; k++) {
                      g2d.setColor(Color.BLACK);
                      g2d.drawRect(i + 5 * j + 20 * (j - 1), (maxY - height) + 5 * k + 20 * (k - 1), 20, 20);
                      if (Math.random() < 0.7) {
                          g2d.setColor(Color.YELLOW);
                          g2d.fillRect(i + 5 * j + 20 * (j - 1), (maxY - height) + 5 * k + 20 * (k - 1), 20, 20);
                      } else {
                          g2d.setColor(Color.BLACK);
                          g2d.fillRect(i + 5 * j + 20 * (j - 1), (maxY - height) + 5 * k + 20 * (k - 1), 20, 20);
                          g2d.setColor(transYellow);
                          g2d.fillRect(i + 5 * j + 20 * (j - 1), (maxY - height) + 5 * k + 20 * (k - 1), 20, 20);
                      }
                  }
              }
              addBuilding();
              a = width;
              height = (int) (Math.random() * 462 + 100);
              width = (int) (Math.random() * 100 + 100);
      
          }
      }
      
      这允许您为
      建筑
      生成主要参数,并简单地缓存结果,必要时只需绘制

      例如

      public class Buildings {
      
          private int maxX = 784;
          private int maxY = 712;
      
          private List<Building> buildings;
      
          public Buildings() {
              buildings = new ArrayList<>(25);
              for (int i = 10; i < 634; i += 10)//buildings
              {
                  int width = (int) (Math.random() * 100 + 100);
                  int height = (int) (Math.random() * 350 + 100);
                  int x = i;
                  int y = maxY - height;
      
                  buildings.add(new Building(x, y, width, height));
              }
          }
      
          public void paint(Graphics g) {
              Graphics2D g2d = (Graphics2D) g;
              for (Building building : buildings) {
                  building.paint(g2d);
              }
          }
      }
      
      作为一个可运行的例子

      public class Buildings {
      
          private int maxX = 784;
          private int maxY = 712;
      
          private List<Building> buildings;
      
          public Buildings() {
              buildings = new ArrayList<>(25);
              for (int i = 10; i < 634; i += 10)//buildings
              {
                  int width = (int) (Math.random() * 100 + 100);
                  int height = (int) (Math.random() * 350 + 100);
                  int x = i;
                  int y = maxY - height;
      
                  buildings.add(new Building(x, y, width, height));
              }
          }
      
          public void paint(Graphics g) {
              Graphics2D g2d = (Graphics2D) g;
              for (Building building : buildings) {
                  building.paint(g2d);
              }
          }
      }
      

      导入java.awt.Color;
      导入java.awt.EventQueue;
      导入java.awt.Graphics;
      导入java.awt.Graphics2D;
      导入java.awt.event.ActionEvent;
      导入java.awt.event.ActionListener;
      导入java.util.ArrayList;
      导入java.util.List;
      导入javax.swing.JFrame;
      导入javax.swing.JPanel;
      导入javax.swing.Timer;
      导入javax.swing.UIManager;
      导入javax.swing.UnsupportedLookAndFeelException;
      公共级城市景观扩展JPanel{
      建筑物a=新建筑物();
      不明飞行物b=新的不明飞行物();
      @凌驾
      受保护组件(图形g){
      super.paintComponent(g);//若要更改生成方法的主体,请选择工具|模板。
      a、 油漆(g);
      b、 油漆(g);
      }
      公开作废动议(){
      b、 move();
      }
      公共静态void main(字符串[]args)引发InterruptedException{
      invokeLater(新的Runnable(){
      @凌驾
      公开募捐{
      试一试{
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
      }catch(ClassNotFoundException |实例化Exception | IllegalacessException |不支持ookandfeelException ex){
      例如printStackTrace();
      }
      JFrame框架=新的JFrame(“框架”);
      城市景观jpe=新城市景观();
      frame.add(jpe);
      框架设置尺寸(800750);
      框架.立根背景(颜色.黑色);
      frame.setLocationRelativeTo(空);
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      System.out.println(frame.getContentPane().getSize());
      计时器计时器=新计时器(10,新ActionListener(){
      @凌驾
      已执行的公共无效操作(操作事件e){
      jpe.move();//更新坐标
      jpe.re
      
      import java.awt.*;
      import javax.swing.*;
      public class UFO extends JPanel
      {
        private int x = 20; //x and y coordinates of the ball
        private int y = 20;
        private int xa = 1;
        public void move() //Increase both the x and y coordinates
        {
          if (x + xa < 0) {
            xa = 1;
          }
          if (x + xa > 784-75) 
          {
            xa = -1;
          }
          x = x + xa; 
        }
        public void paint(Graphics g)
        {
          super.paint(g); //Clears the panel, for a fresh start
          Graphics2D g2d = (Graphics2D) g;
          g2d.setColor(Color.LIGHT_GRAY);
          g2d.fillOval(x,y,75,25); //Draw the ball at the desired point
        }
      }
      
      public void paint(Graphics g) {
          Graphics2D g2d = (Graphics2D) g;
      
          Color transYellow = new Color(255, 255, 0, 59);
      
          g2d.setColor(Color.BLACK);
          g2d.fillRect(0, 0, maxX, maxY);
      
          g2d.setColor(Color.WHITE);
          g2d.fillRect(5, 5, 25, 25);
      
          int a = 0;
      
          for (int i = 10; i < 634; i += (a + 10))//buildings
          {
      
              g2d.setColor(Color.GRAY);
              g2d.drawRect(i, maxY - height, width, height);
              g2d.fillRect(i, maxY - height, width, height);
      
              rows = Math.round((height) / 25);
              columns = Math.round(width / 25);
      
              for (int j = 1; j <= columns; j++)//windows
              {
                  for (int k = 1; k <= rows; k++) {
                      g2d.setColor(Color.BLACK);
                      g2d.drawRect(i + 5 * j + 20 * (j - 1), (maxY - height) + 5 * k + 20 * (k - 1), 20, 20);
                      if (Math.random() < 0.7) {
                          g2d.setColor(Color.YELLOW);
                          g2d.fillRect(i + 5 * j + 20 * (j - 1), (maxY - height) + 5 * k + 20 * (k - 1), 20, 20);
                      } else {
                          g2d.setColor(Color.BLACK);
                          g2d.fillRect(i + 5 * j + 20 * (j - 1), (maxY - height) + 5 * k + 20 * (k - 1), 20, 20);
                          g2d.setColor(transYellow);
                          g2d.fillRect(i + 5 * j + 20 * (j - 1), (maxY - height) + 5 * k + 20 * (k - 1), 20, 20);
                      }
                  }
              }
              addBuilding();
              a = width;
              height = (int) (Math.random() * 462 + 100);
              width = (int) (Math.random() * 100 + 100);
      
          }
      }
      
      public class Building {
      
          protected static final Color TRANS_YELLOW = new Color(255, 255, 0, 59);
      
          private int x, y, width, height;
          private List<Light> lights;
      
          public Building(int x, int y, int width, int height) {
              this.x = x;
              this.y = y;
              this.width = width;
              this.height = height;
      
              lights = new ArrayList<>(25);
              int rows = Math.round((height) / 25);
              int columns = Math.round(width / 25);
      
              for (int j = 1; j <= columns; j++)//windows
              {
                  for (int k = 1; k <= rows; k++) {
                      Color color = null;
                      if (Math.random() < 0.7) {
                          color = Color.YELLOW;
                      } else {
                          color = TRANS_YELLOW;
                      }
                      lights.add(new Light(x + 5 * j + 20 * (j - 1), y + 5 * k + 20 * (k - 1), color));
                  }
              }
          }
      
          public void paint(Graphics2D g2d) {
              g2d.setColor(Color.GRAY);
              g2d.drawRect(x, y, width, height);
              g2d.fillRect(x, y, width, height);
              for (Light light : lights) {
                  light.paint(g2d);
              }
          }
      
          public class Light {
      
              private int x, y;
              private Color color;
      
              public Light(int x, int y, Color color) {
                  this.x = x;
                  this.y = y;
                  this.color = color;
              }
      
              public void paint(Graphics2D g2d) {
                  g2d.setColor(Color.BLACK);
                  g2d.fillRect(x, y, 20, 20);
                  g2d.setColor(color);
                  g2d.fillRect(x, y, 20, 20);
              }
          }
      
      }
      
      public class Buildings {
      
          private int maxX = 784;
          private int maxY = 712;
      
          private List<Building> buildings;
      
          public Buildings() {
              buildings = new ArrayList<>(25);
              for (int i = 10; i < 634; i += 10)//buildings
              {
                  int width = (int) (Math.random() * 100 + 100);
                  int height = (int) (Math.random() * 350 + 100);
                  int x = i;
                  int y = maxY - height;
      
                  buildings.add(new Building(x, y, width, height));
              }
          }
      
          public void paint(Graphics g) {
              Graphics2D g2d = (Graphics2D) g;
              for (Building building : buildings) {
                  building.paint(g2d);
              }
          }
      }
      
      public class CityScape extends JPanel {
      
          Buildings a = new Buildings();
          UFO b = new UFO();
      
          @Override
          protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              a.paint(g);
              b.paint(g);
          }
      
      import java.awt.Color;
      import java.awt.EventQueue;
      import java.awt.Graphics;
      import java.awt.Graphics2D;
      import java.awt.event.ActionEvent;
      import java.awt.event.ActionListener;
      import java.util.ArrayList;
      import java.util.List;
      import javax.swing.JFrame;
      import javax.swing.JPanel;
      import javax.swing.Timer;
      import javax.swing.UIManager;
      import javax.swing.UnsupportedLookAndFeelException;
      
      public class CityScape extends JPanel {
      
          Buildings a = new Buildings();
          UFO b = new UFO();
      
          @Override
          protected void paintComponent(Graphics g) {
              super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
              a.paint(g);
              b.paint(g);
          }
      
          public void move() {
              b.move();
          }
      
          public static void main(String[] args) throws InterruptedException {
              EventQueue.invokeLater(new Runnable() {
                  @Override
                  public void run() {
                      try {
                          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                      } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                          ex.printStackTrace();
                      }
      
                      JFrame frame = new JFrame("Frame");
                      CityScape jpe = new CityScape();
                      frame.add(jpe);
                      frame.setSize(800, 750);
                      frame.setBackground(Color.BLACK);
                      frame.setLocationRelativeTo(null);
                      frame.setVisible(true);
                      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                      System.out.println(frame.getContentPane().getSize());
      
                      Timer timer = new Timer(10, new ActionListener() {
                          @Override
                          public void actionPerformed(ActionEvent e) {
                              jpe.move(); //Updates the coordinates
                              jpe.repaint(); //Calls the paint method
                          }
                      });
                      timer.start();
                  }
              });
          }
      
          public class Buildings {
      
              private int maxX = 784;
              private int maxY = 712;
      
              private List<Building> buildings;
      
              public Buildings() {
                  buildings = new ArrayList<>(25);
                  for (int i = 10; i < 634; i += 10)//buildings
                  {
                      int width = (int) (Math.random() * 100 + 100);
                      int height = (int) (Math.random() * 350 + 100);
                      int x = i;
                      int y = maxY - height;
      
                      buildings.add(new Building(x, y, width, height));
                  }
              }
      
              public void paint(Graphics g) {
                  Graphics2D g2d = (Graphics2D) g;
                  for (Building building : buildings) {
                      building.paint(g2d);
                  }
              }
          }
      
          public static class Building {
      
              protected static final Color TRANS_YELLOW = new Color(255, 255, 0, 59);
      
              private int x, y, width, height;
              private List<Light> lights;
      
              public Building(int x, int y, int width, int height) {
                  this.x = x;
                  this.y = y;
                  this.width = width;
                  this.height = height;
      
                  lights = new ArrayList<>(25);
                  int rows = Math.round((height) / 25);
                  int columns = Math.round(width / 25);
      
                  for (int j = 1; j <= columns; j++)//windows
                  {
                      for (int k = 1; k <= rows; k++) {
                          Color color = null;
                          if (Math.random() < 0.7) {
                              color = Color.YELLOW;
                          } else {
                              color = TRANS_YELLOW;
                          }
                          lights.add(new Light(x + 5 * j + 20 * (j - 1), y + 5 * k + 20 * (k - 1), color));
                      }
                  }
              }
      
              public void paint(Graphics2D g2d) {
                  g2d.setColor(Color.GRAY);
                  g2d.drawRect(x, y, width, height);
                  g2d.fillRect(x, y, width, height);
                  for (Light light : lights) {
                      light.paint(g2d);
                  }
              }
      
              public class Light {
      
                  private int x, y;
                  private Color color;
      
                  public Light(int x, int y, Color color) {
                      this.x = x;
                      this.y = y;
                      this.color = color;
                  }
      
                  public void paint(Graphics2D g2d) {
                      g2d.setColor(Color.BLACK);
                      g2d.fillRect(x, y, 20, 20);
                      g2d.setColor(color);
                      g2d.fillRect(x, y, 20, 20);
                  }
              }
      
          }
      
          public class UFO {
      
              private int x = 20; //x and y coordinates of the ball
              private int y = 20;
              private int xa = 1;
      
              public void move() //Increase both the x and y coordinates
              {
                  if (x + xa < 0) {
                      xa = 1;
                  }
                  if (x + xa > 784 - 75) {
                      xa = -1;
                  }
                  x = x + xa;
              }
      
              public void paint(Graphics g) {
                  Graphics2D g2d = (Graphics2D) g;
                  g2d.setColor(Color.LIGHT_GRAY);
                  g2d.fillOval(x, y, 75, 25); //Draw the ball at the desired point
              }
          }
      }
      
      CityScape extends JPanel:
          variables:
              Building[] buildings;    //might be useful to use an arraylist/stack/queue instead of an array depending on implementation
              UFO craft;
      
          constructor:
              setup new Building objects and add to list buildings
              initialize craft to new UFO
      
          paintComponent:
              calls the paint methods for each building & the ufo craft
      
      Building:
          variables:
              int x, y; // position of building
              int height, width; // of this building
      
          constructor:
              initializes x, y // probably needs to be inputed from CityScape with this setup
              calc height and width randomly // stored in this.height/width
      
          paint:
              paints single building based on it's variables
      
      //side-note, you'll probably need getters for the x/y/width to build each building from CityScape