Java GUI如何将创建的对象分配给其他类中的构造函数?

时间:2016-11-29 15:24:15

标签: java user-interface

我正在尝试移动之前在其他类中创建的元素。如何将创建的对象分配给“Player”类中的构造函数,并使GUI中绘制的对象属于每个玩家?以下代码是我的代码的一部分。请看一下并提出一些解决方案。谢谢。

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

class Gui extends JFrame {

    public Gui(){
        setTitle("Test");
        setBackground(Color.white);
        setSize(1000, 1000);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }
    public static void addNewOval(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.red);    g2d.fillOval (865, 865, 30, 30);
    }
    public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawRect(50, 50, 900, 900);
    }
}

class Player{
    Gui a1;
    String name;
    int position;
    // add something?

    Player(String name){
        this.name = name;
        position = 0;
        // add something?
    }
    public void move(){
        position += 1;
        // Can the object in GUI move according to the position?
    }
}

public class Game{
    public static int totalPlayerNumber;
    public static void main(String [] args){
        Gui a1 = new Gui();
        System.out.println("How many players?");
        Scanner scanner = new Scanner(System.in);
        totalPlayerNumber = scanner.nextInt();
        Gui.addNewOval(a1.getGraphics(), totalPlayerNumber);

        for (int i = 1; i <= totalPlayerNumber; i++){
            System.out.println("number " + i + " player's name: ");
            scanner = new Scanner(System.in);
            String temp = scanner.next();
            Player a = new Player(temp);
    }
}

我试图在Player构造函数中添加“a1.addNewOval(a1.getGraphics());”但在main中创建Player对象时显示NullPointerException。有什么建议吗?

0 个答案:

没有答案