Java 如何从另一个类调用在另一个类中创建的类实例的方法?

Java 如何从另一个类调用在另一个类中创建的类实例的方法?,java,swing,class,methods,Java,Swing,Class,Methods,我试图在JavaSwingGUI中为我的突破游戏创建一些动画游戏文本 预期行为:每次砖块击中其点时,都会猛击屏幕,暂停0.25秒,然后消失为零 我所做的:在名为AlertText的类中的方法中使用计时器。当在类GameLogic中点击砖块时,将创建一个新的AlertText,其计时器开始运行。现在在游戏课上我有绘画课 问题:那么我如何调用在GameLogic中创建的AlertText的特定实例来使用setter和getter方法在Game类中的paint中设置我的g.drawString。我觉得

我试图在JavaSwingGUI中为我的突破游戏创建一些动画游戏文本

预期行为:每次砖块击中其点时,都会猛击屏幕,暂停0.25秒,然后消失为零

我所做的:在名为
AlertText
的类中的方法中使用计时器。当在类
GameLogic
中点击砖块时,将创建一个新的
AlertText
,其计时器开始运行。现在在游戏课上我有绘画课

问题:那么我如何调用在
GameLogic
中创建的
AlertText
的特定实例来使用setter和getter方法在
Game
类中的paint中设置我的
g.drawString
。我觉得这应该是一种常见的技术?有名字吗

我让它为一种砖块样式使用全局变量,所以我知道动画可以工作,但我需要100多个全局变量来完成每种砖块


游戏课

public class Game extends JPanel   
 {
 public static final int HEIGHT = 720;
 public static final int WIDTH = 600;
 public Color color;

private GameLogic gl = new GameLogic();
private KeyboardController  controller;
public Paddle player = new Paddle(110, HEIGHT-30, 100, 10, 10, color.black, controller);
public Ball gameBall = new Ball(300, 300, 15,  color.black);
private boolean PaddleUpdateComplete = false;

private List<AlertText> activeAlerts = new ArrayList<AlertText>();
Game game = new Game();



public void spawnNewAlert(Brick b){
    AlertText alert = new AlertText();
    alert.setxPos(b.getXPosition());
    alert.setyPos(b.getYPosition());
    alert.setText(b.getPoints()+"");
    alert.setColor(b.getColor());
    activeAlerts.add(alert);
    alert.fireText();
}    

@Override
public void paint(Graphics g)
{
     g.clearRect(0, 0, WIDTH, HEIGHT);
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, WIDTH, HEIGHT);


    g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, (int)AlertText.staticAlertSize));
    g.setColor(new Color(AlertText.staticRed, AlertText.staticGreen, AlertText.staticBlue));
    g.drawString(AlertText.staticAlertOne, AlertText.staticAlertXPos, AlertText.staticAlertYPos);

    player.draw((Graphics2D)g);
    gameBall.draw((Graphics2D)g);
    gl.drawBricks(g);
    // Draw GameObjects and anything else here
    g.setFont(scoreFont);
    g.drawString("Score: " + player.getScore(), 10, 25);
    g.drawString("LIVES: " + player.getLives(), 150, 25);
    if(gl.gameOver(player) &&
            gameBall.getYPosition() >= HEIGHT){
        g.setColor(Color.black);
        g.setFont(endFont);
        g.drawString("Game Over!  Score: " + player.getScore(), (WIDTH/2) - 85, (HEIGHT/2));
    }
    if(gl.empty()){
        g.setColor(Color.black);
        g.setFont(endFont);
        g.drawString("You won!  Score: " + player.getScore(), (WIDTH/2) - 85, (HEIGHT/2));
        timer.stop();
    }
    if(PowerUps.isMegaPaddle){
    g.setColor(Color.orange);
    g.setFont(TimeFont);
    g.drawString(PowerUps.megaPaddlecount+"", 300, 500);
    }
    if(PowerUps.isMegaBall){
     g.setColor(Color.red);
     g.setFont(TimeFont);
     g.drawString(PowerUps.megaBallcount+"", 250, 400);   
    }
    if(!game.activeAlerts.isEmpty()){

        for(AlertText alert: game.activeAlerts){
        g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, alert.getTextSize()));
        g.setColor(alert.getColor());
        g.drawString(alert.getText(), alert.getxPos(), alert.getxPos());
        if(alert.count<=0){
         game.activeAlerts.remove(alert);
        }
     }

    } 
}

public void updateGameState()
{
    gameBall.move();
    player.move(controller);
    gl.checkCollisions(gameBall, player, timer, WIDTH, HEIGHT, game);
    gl.removeBrick();
    // Move GameObjects and check for collisions here
    if(Paddle.paddleHits==1 && !PaddleUpdateComplete){
        gameBall.setXVelocity(10);
        gameBall.setYVelocity(gameBall.getYVelocity()-6);
        PaddleUpdateComplete = true;
    }


}

public final void setupGame()
{
    gameBall.setXVelocity(0);
    gameBall.setYVelocity(-10);
    player.setLives(5);
    gl.makeBricks();
    // Instantiate instance variables here




}

// Constructor method should not be modified
public Game()
{
    // Set the size of the Panel to the correct size
    this.setPreferredSize(new Dimension(WIDTH, HEIGHT));

    // Set the background color of the Panel to black
    this.setBackground(Color.BLACK);

    // Instantiate a KeyboardController and listen for input with it
    controller = new KeyboardController(); 
    this.addKeyListener(controller);

    // Call the setupGame method to initialize instance variables
    this.setupGame();

    // Get focus in the window
    this.setFocusable(true);
    this.requestFocusInWindow();
}

// Start method should not be modified
public void start()
{
    // Set up a new Timer to repeat every 20 milliseconds (50 FPS)
    timer = new Timer(20, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) 
        {
            repaint();
            updateGameState();
        }
    });

    timer.setRepeats(true);
    timer.start();
}

Timer timer; 
}
公共类游戏扩展JPanel
{
公共静态最终内部高度=720;
公共静态最终整数宽度=600;
公共色彩;
私有GameLogic gl=新GameLogic();
专用键盘控制器;
公共桨叶播放器=新的桨叶(110,高度-30,100,10,10,彩色。黑色,控制器);
公共球gameBall=新球(300、300、15,颜色.黑色);
私有布尔值pableUpdateComplete=false;
私有列表activeAlerts=new ArrayList();
游戏=新游戏();
公共警报(砖b){
AlertText alert=新的AlertText();
alert.setxPos(b.getXPosition());
alert.setyPos(b.getYPosition());
alert.setText(b.getPoints()+);
alert.setColor(b.getColor());
activeAlerts.add(警报);
alert.fireText();
}    
@凌驾
公共空间涂料(图g)
{
g、 clearRect(0,0,宽度,高度);
g、 setColor(Color.WHITE);
g、 fillRect(0,0,宽度,高度);
g、 setFont(新字体(Font.SANS_SERIF,Font.BOLD,(int)AlertText.staticAlertSize));
g、 setColor(新颜色(AlertText.staticRed、AlertText.staticGreen、AlertText.staticBlue));
g、 抽绳(AlertText.staticAlertOne、AlertText.staticAlertXPos、AlertText.staticAlertYPos);
球员。抽签((图2d)g);
gameBall.draw((图2d)g);
gl.拉丝砖(g);
//在这里绘制游戏对象和其他任何东西
g、 setFont(scoreFont);
g、 抽绳(“分数:+player.getScore(),10,25);
g、 抽绳(“生活:+player.getlifes(),150,25);
如果(总图gameOver)(玩家)&&
gameBall.getYPosition()>=高度){
g、 设置颜色(颜色为黑色);
g、 setFont(endFont);
g、 抽绳(“游戏结束!得分:+player.getScore(),(宽度/2)-85,(高度/2));
}
if(gl.empty()){
g、 设置颜色(颜色为黑色);
g、 setFont(endFont);
g、 抽绳(“你赢了!得分:+player.getScore(),(宽度/2)-85,(高度/2));
timer.stop();
}
if(通电。IsmegaPaile){
g、 setColor(颜色为橙色);
g、 setFont(TimeFont);
g、 抽绳(通电.兆瓦数+“”,300,500);
}
if(通电。isMegaBall){
g、 setColor(Color.red);
g、 setFont(TimeFont);
g、 抽绳(加电.兆球数+“”,250,400);
}
如果(!game.activeAlerts.isEmpty()){
用于(AlertText alert:game.activeAlerts){
g、 setFont(新字体(Font.SANS_SERIF、Font.BOLD、alert.getTextSize());
g、 setColor(alert.getColor());
g、 抽绳(alert.getText(),alert.getxPos(),alert.getxPos());
如果(警报计数47){
textSize+=10;
xPos-=2;
计数--;
}
否则,如果(计数>42){
计数--;
}
否则{
yPos-=1;
xPos+=1;
textSize-=1;
计数--;
if(count=(WIDTH-ball.getDiameter())| | ball.getXPosition()(player.getYPosition()+player.getHeight()+10)){
重置球(球、球员、时间、宽度、高度);
}

如果(ball.getYPosition()据我所知,您希望通过另一个对象触发一个对象中的方法,而这两个对象都被包装在第三个,更高级别的对象中,对吗

我将在游戏对象中创建AlertText和GameLogic对象,然后将AlertText的引用传递给GameLogic,从而使GameLogic能够触发AletText的fireText()方法。您必须从spawnNewAlert方法中删除AlertText的实例化(事实上,您只需要一个AlertText实例),并在每次运行后稍微修改fireText方法以重置

在GameLogic中:

AlertText alert;

public GameLogic(AlertText alert //other parameters) {
  this.alert = alert;
  //other stuff you do here
}
在游戏中,让我们说:

GameLogic gameLogic;
AlertText alertText;

public Game() {
  alertText = new AlertText();
  gameLogic = new GameLogic(alertText);
}

public void paint(Graphics g) {
  gameLogic.spawnNewAlert(brick);
}

您可能希望在
游戏
类中创建一个警报列表,在该列表中进行渲染,并且您希望能够在
游戏逻辑
类中添加警报列表,在该列表中处理所有游戏

有很多方法可以做到这一点。假设您在
GameLogic
中引用了
Game
类,然后将
spawnNewAlert()
的代码移动到
Game
中。然后
GameLogic
中的代码可以调用
Game.spawnNewAlert(b)
然后将其留给
游戏
类管理

您需要在
游戏
类中添加一些内容:

  • 新成员字段
    private List activeAlerts=new ArrayList();
  • 在fireText()之前的
    spawnNewAlert()
    中,将警报添加到
    activeAlerts
  • paint()
    中,循环执行
    activeAlerts
    并绘制每个警报,删除任何不再有效的警报(请注意删除方式,使用
    迭代器或将删除推迟到迭代后进行,以防出现
    ConcurrentModificationException

  • 你能展示一些相关的代码吗?Swing还是Android?不可能两者都是。这是个好主意,我也是
    AlertText alert;
    
    public GameLogic(AlertText alert //other parameters) {
      this.alert = alert;
      //other stuff you do here
    }
    
    GameLogic gameLogic;
    AlertText alertText;
    
    public Game() {
      alertText = new AlertText();
      gameLogic = new GameLogic(alertText);
    }
    
    public void paint(Graphics g) {
      gameLogic.spawnNewAlert(brick);
    }