从一个类调用数组到另一个类

时间:2014-07-28 07:24:22

标签: java swing oop

我试图为我的学校项目创建一个战舰游戏,但它仍然失控。我是Java新手,这是个人问题。

我有六个课程,我试图将包含我的船只的2d arraylist从我的主班传递到另一个班级。

我的主要课程:

import javax.swing.*;
import java.awt.*;
import java.util.*;


public class Main {

    public static void main(String[] args) {



        Boat_Class patrol1 = new Boat_Class("PatrolBoat",2);
        Boat_Class Destroyer1 = new Boat_Class("Destroyer",3);
        Boat_Class Battleship1 = new Boat_Class("Battleship",4);
        Boat_Class Aircraftcarrier1 = new Boat_Class("AircraftCarrier",5);

        /*Boat_Class patrol2 = new Boat_Class();
        Boat_Class Destroyer2 = new Boat_Class();
        Boat_Class Battleship2 = new Boat_Class();
        Boat_Class Aircraftcarrier2 = new Boat_Class();*/

        ArrayList<Boat_Class> player1 = new ArrayList<Boat_Class>();
        player1.add(patrol1);
        player1.add(Destroyer1);
        player1.add(Battleship1);
        player1.add(Aircraftcarrier1);

        /*ArrayList<Boat_Class> player2 = new ArrayList<Boat_Class>();
        player2.add(patrol1);
        player2.add(Destroyer1);
        player2.add(Battleship1);
        player2.add(Aircraftcarrier1);*/

        Cell [][] GridCellP1 = new Cell [10][10];
        //Cell [][] GridCellP2 = new Cell [10][10];

        JFrame frame = new JFrame("Battleship");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setVisible(true);


        North_Panel Top = new North_Panel(player1);
        frame.add(Top, BorderLayout.NORTH);

        Center_Panel Center = new Center_Panel();
        frame.add(Center, BorderLayout.CENTER);

        South_Panel South = new South_Panel();
        frame.add(South , BorderLayout.SOUTH);


         /*Cell c = new Cell ();
         c.setColIndex(-2);
         c.setRowIndex(4);
         Center.add(c);*/



    }

}

中心小组课程是我希望我的arraylist通过。

public class Center_Panel extends JPanel {



    public Center_Panel() {

        this.setLayout(new GridLayout(1, 2, 10, 10));
        JPanel panel1 = new JPanel(new GridLayout(10, 10));
        panel1.setBackground(Color.BLUE);


        char c = 'A';
        for (int i = 0; i < 10; i++) {
         for (int j = 0; j < 10; j++) {
         JButton button = new JButton((c + " " +j));
         panel1.add(button);
         button.addActionListener (new ActionListener()
         {
             @Override
             public void actionPerformed(ActionEvent e){

            }});
         GridCellP1 [i][j] = button;
         }

         c ++;
         }

        this.add(panel1)

1 个答案:

答案 0 :(得分:1)

首先声明您的Center_Panel,使其参数Cell[][] ...

public class Center_Panel extends JPanel {

public Center_Panel(Cell[][] cells) {

然后,当你构造Center_Panel时,将值传递给它......

    Cell [][] GridCellP1 = new Cell [10][10];
    //...
    Center_Panel Center = new Center_Panel(GridCellP1);

您还会发现,在构建完UI后,如果在框架上调用setVisible(true),则问题会更少......

您可能还希望阅读Model–view–controller,因为这可能有助于您做出更好的设计;)