如何将对象添加到ArrayList?

时间:2018-09-13 17:35:59

标签: oop arraylist jframe jpanel

我在编程方面还很陌生,我正在尝试制作一个小游戏,以便可以自学OOP,但是我有一个问题,根本无法解决。

我有一个ComponentsPanel类,从中我将另一个(JavaFish)称为ArrayList。 addFish()方法将JavaFish添加到ArrayList中。当我从构造函数中调用addFish()方法时,效果很好。

问题是,当我从start(),另一个类和程序包调用它时,它没有向ArrayList添加任何元素。

主班

    package framework;

    public class Core {

            JFrame window;
            ComponentsPanel panel;
            int width = 600;
            int height = 400;

            public void start() {
                window = new JFrame();
                window.setTitle("Java Game");
                window.setPreferredSize(new Dimension(width, height));
                window.setMinimumSize(new Dimension(width, height));
                window.setMaximumSize(new Dimension(width, height));
                window.setResizable(false);

                panel = new ComponentsPanel();
                window.add(panel, BorderLayout.CENTER);
                window.setVisible(true);
                window.pack();
            }

            public void stop() {
                window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            }

        }

ComponentsPanel

        package framework;

        public class ComponentsPanel extends JPanel {
            ArrayList<JavaFish> javaFishes = new ArrayList<JavaFish>();

            public ComponentsPanel() {
                javaFishes = new ArrayList<JavaFish>();
                //addFish(new JavaFish(100, 100, 25, 25));
            }

            public void addFish(JavaFish javaFish) {    
                javaFishes.add(javaFish);
                repaint();
            }

            public void start() {
                addFish(new JavaFish(100, 100, 25, 25));
            }

            @Override
            public void paint(Graphics g) { 
                for (JavaFish jFish : javaFishes) {
                    jFish.draw(g);
                }
            }
       } 

鱼种

        package framework;

        public class JavaFish {

            BufferedImage img;
            private int x_pos;
            private int y_pos;
            private int sizeX;
            private int sizeY;

            public JavaFish(int x_pos, int y_pos, int sizeX, int sizeY) {
                this.x_pos = x_pos;
                this.y_pos = y_pos;
                this.sizeX = sizeX;
                this.sizeY = sizeY;
            }

            public void draw(Graphics g) {
                BufferedImage JavaFish = LoadImage("img/JavaFish.png");
                Graphics2D g2d = (Graphics2D) g;
                g2d.drawImage(JavaFish, x_pos, y_pos, sizeX, sizeY, null);

            }

            BufferedImage LoadImage(String FileName) {
                img = null;
                try {
                    img = ImageIO.read(new File (FileName));
                } catch (IOException e) {
                    e.printStackTrace();
                }   
                return img;

            }

    }

模拟课

        package user;

        import framework.ComponentsPanel;
        import framework.Core;

        public class Simulation {
            Core c;
            ComponentsPanel panel;
            boolean endSim = false;

            public Simulation() {
                c = new Core();
                panel = new ComponentsPanel();
            }

            private void populate() {
                panel.start()
            }

            private void updateWorld() {
                while (!endSim) {
                    c.start();
                    break;
                }
                c.stop();
            }

            public static void main(String[] args) {
                Simulation simulation = new Simulation();
                simulation.populate();
                simulation.updateWorld();
            }

        }

2 个答案:

答案 0 :(得分:0)

ComponentsPanel中存在的

start()方法不是生命周期方法。因此,除非您手动调用start()方法,否则它将不会被调用。您可以添加打印语句以跟踪呼叫。

答案 1 :(得分:0)

@Cristea感谢您提供更新的代码。

如果您在Core类的start()方法中创建的ComponentsPanel实例上调用addFish()方法,如下所示。

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, ListView} from 'react-native';
import axios from 'axios';

export default class App extends Component {

  constructor(props){
    super(props);
    this.state = {
      isolate: true,
      movies: []
    }

  }

  componentWillMount(){
    axios.get('https://facebook.github.io/react-native/movies.json')
    .then(function (response){
      var moviesList = new ListView.DataSource({
        rowHasChanged: (r1,r2) => r1 !== r2
      });
      this.setState({
        isolate: false,
        movies: moviesList.cloneWithRows(response.data.movies)
      });
    }).catch(function(error){
alert(error);
    });
  }
  render() {
if(this.state.isolate){
  return (<View>

    <Text>Loading....</Text>
  </View>);
}

    return (
      <View style={styles.container}>
        <ListView 
        dataSource={this.state.movies}
        renderRow={
          (rowData) => <Text> {rowData.title} </Text>
        }
        >
        </ListView>
      </View>
    );
  }
}

您的代码存在的问题是,您正在创建两个ComponentsPanel类的实例。在您创建的第一个实例(我们将其称为panel-1)上,您正在通过以下方法调用addFish()方法。在面板1上调用此start()方法。

public void start() {
    window = new JFrame();
    window.setTitle("Java Game");
    window.setPreferredSize(new Dimension(width, height));
    window.setMinimumSize(new Dimension(width, height));
    window.setMaximumSize(new Dimension(width, height));
    window.setResizable(false);

    panel = new ComponentsPanel(); // This panel is passed to the JFrame
    panel.addFish(new JavaFish(100, 100, 25, 25));  // so do addFish() here. 
    window.add(panel, BorderLayout.CENTER);
    window.setVisible(true);
    window.pack();
}

然后,您要从Core类的start()方法创建ComponentsPanel类的第二个实例(我们将其称为panel-2),而panel-2不执行addFish()。但是此实例(panel-2)是添加到JFrame的对象,将用于paint()。由于panel-2不执行addFish(),因此paint()找不到任何JavaFishes。

请记住,实例变量javaFishes特定于ComponentsPanel的每个实例。 panel-1无法添加由panel-1添加的javaFishs。