如何在单击按钮时重新启动JFrame?

Exo*_*fic 3 java swing

我正在制作JFrame纸牌游戏.我想JFramerestartBtn点击时重新启动.谁能帮我?

PlayGame课程将推出frame1

public class PlayGame {

  public static void main(String[] args) {
        GameFrame frame1 = new GameFrame();

        // Set Icon
        Image icon = Toolkit.getDefaultToolkit().getImage("image/poker_icon.gif");
        frame1.setIconImage(icon);

        frame1.setVisible(true);
        frame1.setSize(600, 700);
        frame1.setTitle("Card Game");

        // Set to exit on close
        frame1.setDefaultCloseOperation(GameFrame.EXIT_ON_CLOSE);
  }
}
Run Code Online (Sandbox Code Playgroud)

这是GameFrame类用于JFrame构造函数.

public class GameFrame extends JFrame implements ActionListener {

  public JLabel restartLbl;  
  public JButton restartBtn

  public GameFrame() {

    restartLbl = new JLabel(restart);
    restartBtn = new JButton();

    restartBtn..addActionListener(this);
  }


  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == restartBtn) {
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

rth*_*sen 6

你必须编写帧的重启代码.考虑一开始的游戏状态以及所有组件的状态.一般来说,你在setup某个地方和start某个阶段都有一个观点.如果你可以设置它们就可以很容易地使用setupstartas restart.

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == restartBtn) {
        restart();
    }
  }

public void restart(){
    stop(); // if necessary
    setup(); // set everything to initial state
    start(); // start game
}

public void stop(){
    // stop any timers, threads, operations etc.
}

public void setup(){
    // set to initial state.
    // something like recreate the deck, 
    // clear hands and table, shuffle, and deal.
}

public void start(){
    // code to initiate the game.
}
Run Code Online (Sandbox Code Playgroud)

因此,最好的方法是将您的游戏视为几个阶段,而其他行动restart应该是其他阶段的组合.在不了解您的实际游戏代码(或计划)的情况下,很难具体回答这个问题.但我希望有所帮助.:)

编辑

这是一种更好的生成/洗牌的方法.

   public class GenRandom {

   int []  cards = new int [GameFrame.NUMBER_OF_CARDS];

   public void generateCards() {
      for (int i = 0; i < cards.length; i++) { // for each index of the array...
         int card; // declare card
         do {
            card = (int) (Math.random() * 51) + 1; // random between 1 and 52
         } while (contains(card)); // regenerate random card if array already contains.
         cards[i] = card; // card is unique, so assign value to array index
      }
   }

   private boolean contains(int t){
      for(int i = 0; i < GameFrame.NUMBER_OF_CARDS; i++){ // for each index...
         if(cards[i] == t){
            return true; // if the generated card is already in the array..
         }
      }
      return false; // otherwise reached end, so return false.
   }

   public int [] getAllCards() {
      return cards;
   }
}
Run Code Online (Sandbox Code Playgroud)