从另一个访问一个类

时间:2013-05-02 21:56:06

标签: java object

我有一个定义的类,它发布了一个允许访问私有对象的方法:

    public class HexBoard {

[...]

        public HexBoard(int Width, int Height, boolean Wrap) {
            SetSize(Width, Height); // inherently calls Reset()
            SetWrap(Wrap);
        } // HexBoard constructor


        public Polygon GetHexagon(int CellIndex) {

            Polygon p = new Polygon();
            for (int i = 0; i < 6; i++) {
                p.addPoint((int) (HexCentres.X(CellIndex) + HexPoints.X(i)), (int) (HexCentres.Y(CellIndex) + HexPoints.Y(i)));
            }

            return p;
        } // GetHexagon

        public int Cells() { return CellCount; }

    } // HexBoard

您可以看到该方法创建了一个多边形并将其返回。这个效果很好。现在,我有另一个类,它发布一个扩展的JPanel,以绘制一个由大量六边形组成的基于六边形的游戏场。

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

public class PCinterface extends JPanel {

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        int CellCount = HexBoard.Cells();
        for (int i = 0; i < HexBoard.Cells(); i++) {
            g.drawPolygon(HexBoard.GetHexagon(i));
        }
    } // paintBoard

} // PCinterface

问题是PC接口对HexBoard一无所知,因此无法访问HexBoard.Cells()或HexBoard.GetHexagon()。

执行以下操作时

public class Test {

    public static void main(String args[]) {

        BreadBoard Board = new BreadBoard(12,12,false);

        Board.SetCellRadius(25);

        JFrame frame = new JFrame();
        frame.setTitle("BreadBoard");
        frame.setSize(600, 600);
        frame.addWindowListener(new WindowAdapter() {
           public void windowClosing(WindowEvent e) {
              System.exit(0);
           }
        });
        Container contentPane = frame.getContentPane();
        contentPane.add(new PCinterface());
        frame.setVisible(true);
*/
    } // main

} // Test

我希望它会打开一个窗口并绘制一些六边形,但我可以看到使用HexBoard在main中创建的基于六边形的板在PC接口的上下文中不存在。

我可以看到我可以很容易地在主要包含PCInterface,这将解决问题:我正在尝试为多个平台开发,并希望这是分离平台相关类的适当方式。

如何在PCInterface类中使用BreadBoard中保存的数据?

2 个答案:

答案 0 :(得分:1)

您需要一个HexBoard实例。您可以在PC接口上添加一个

public class PCinterface extends JPanel {

    public HexBoard hexBoard

    public PCinterface(HexBoard board)
    {
        this.hexBoard = board;
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        int CellCount = this.hexBoard.Cells();
        for (int i = 0; i < this.hexBoard.Cells(); i++) {
            g.drawPolygon(this.hexBoard.GetHexagon(i));
        }
    } // paintBoard

} // PCinterface

假设Board的类型,BreadBoard扩展HexBoard,您可以将其传递给构造函数,如下所示

contentPane.add(new PCinterface(Board));

答案 1 :(得分:0)

正如@HunterMcMillen评论的那样,您需要实例化HexBoard才能使用方法Cells()

...
HexBoard hexBoard = new HexBoard(width, height, wrap);
int cellCount = hexBoard.Cells();
...
相关问题