繁体   English   中英

如何将我的jButtons链接到同一包中其他类中的方法

[英]How can i link my jButtons to methods in other class in the same package

实际上,我正在用Java开发游戏,当用户单击包含所有游戏组件的同一程序包下的“窗口”类中创建的jButton(新游戏)时,我想开始新游戏。 现在,我想在我的buttonActionPerformed()方法中访问在Framework类中定义的方法'newGame()',但不调用framework的构造函数。

       private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)    {                                         
   Framework f = new Framework();
    f.newGame();         
}   

我正在使用此代码,但是由于我使用过,它显示了很多错误

          this.setContentPane(new Framework());       

在Window类的构造函数中。这是我的框架类的一部分

public class Framework extends Canvas {
public Framework ()
{
    super();

    gameState = GameState.VISUALIZING;

    //We start game in new thread.
    Thread gameThread = new Thread() {
        @Override
        public void run(){
            GameLoop();
        }
    };
    gameThread.start();
    }
     private void GameLoop()
     {
           long visualizingTime = 0, lastVisualizingTime = System.nanoTime();

    // This variables are used for calculating the time that defines for how long we should put threat to sleep to meet the GAME_FPS.
    long beginTime, timeTaken, timeLeft;

    while(true)
    {
        beginTime = System.nanoTime();

        switch (gameState)
        {
            case PLAYING:
                gameTime += System.nanoTime() - lastTime;

                game.UpdateGame(gameTime, mousePosition());

                lastTime = System.nanoTime();
            break;
            case GAMEOVER:
                //...
            break;
            case MAIN_MENU:
                //...
            break;
            case OPTIONS:
                //...
            break;
            case GAME_CONTENT_LOADING:
                //...
            break;
            case STARTING:
                // Sets variables and objects.
                Initialize();
                // Load files - images, sounds, ...
                LoadContent();

                // When all things that are called above finished, we change game status to main menu.
                gameState = GameState.MAIN_MENU;
            break;
            case VISUALIZING:
                        if(this.getWidth() > 1 && visualizingTime > secInNanosec)
                {
                    frameWidth = this.getWidth();
                    frameHeight = this.getHeight();

                    // When we get size of frame we change status.
                    gameState = GameState.STARTING;
                }
                else
                {
                    visualizingTime += System.nanoTime() - lastVisualizingTime;
                    lastVisualizingTime = System.nanoTime();
                }
            break;
        }

        // Repaint the screen.
        repaint();               // goes to paint component in canvas

        timeTaken = System.nanoTime() - beginTime;
        timeLeft = (GAME_UPDATE_PERIOD - timeTaken) / milisecInNanosec; 
        if (timeLeft < 10) 
            timeLeft = 10; //set a minimum
        try {
             Thread.sleep(timeLeft);
        } catch (InterruptedException ex) { }
    }
      }
     public void newGame()
      {
      // We set gameTime to zero and lastTime to current time for later calculations.
       if(true)
        {
          BufferedImage blankCursorImg = 
                       new BufferedImage(16, 16,BufferedImage.TYPE_INT_ARGB);
        Cursor blankCursor =       
               Toolkit.getDefaultToolkit().createCustomCursor(blankCursorImg, new Point(0, 0), null);
        this.setCursor(blankCursor);
    }
    gameTime = 0;
    lastTime = System.nanoTime();

    game = new Game();
  } 
}

这是WindowForm.java,其中包含main()和jButtons包opterbattle;

 import javax.swing.JFrame;

  public class WindowForm extends javax.swing.JFrame {
  public WindowForm() {
     this.setTitle("Helicopter battle");
     if(true) // Full screen mode
    {  
        this.setUndecorated(true);
         this.setExtendedState(this.MAXIMIZED_BOTH);
    }
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Creates the instance of the Framework.java that extends the Canvas.java and puts it on the frame.
    this.setContentPane(new Framework());
     initComponents();
     jButton1.setBounds(630,490,100,30);
     jButton2.setBounds(630,540,100,30);
      } 
     private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    System.exit(0);
}                                        

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:

    Framework f = new Framework();
    f.newGame();
      jButton1.setVisible(false);
    jButton2.setVisible(false);
}                          
  public static void main(String args[]) {
  java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new WindowForm().setVisible(true);
        }
    });
}
  public javax.swing.JButton jButton1;
  public javax.swing.JButton jButton2;
  // End of variables declaration                   
 }

请帮忙,谢谢。

如果我正确理解,您想调用newGame()方法而不从Framework类创建新对象

我认为您可以通过在构造函数之前在WindowForm类中声明一个最终变量来实现此目标,如下所示

private final Framework myFramework = new Framework();

然后将其传递给setContentPane方法

setContentPane(myFramework); 

并在jButton1ActionPerformed方法内使用相同的对象

myFramework.newGame();

-

另一种解决方案是使用Singleton设计模式从Framework类创建静态实例,并在需要时调用Framework.getInstance()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM