簡體   English   中英

在Java Swing中使用從一個類到另一個類的變量

[英]Use variable from one class to another in Java Swing

我正在創建一個問答游戲,並且StartGamePanel中的變量有一些麻煩。 我有開始游戲面板,游戲結束面板和主菜單面板。 我在開始游戲面板中的得分變量最初為0,但對於每個用戶的正確答案,它又增加了100分。 我的想法是在面板游戲中,如果用戶輸入錯誤的答案告訴他總積分是多少。 但是不幸的是,分數變量為0。在開始游戲面板中,游戲UI正確顯示了分數,邏輯正在工作,並且為每個正確答案添加了100分,但是當我嘗試在面板中使用分數變量時,每個分數都為0時間。 這是我的StartGamePanel:

public class StartGamePanel extends JPanel {
...
private GameData gameData;

public StartGamePanel(Frame frame, GameData gameData) {
    this.frame = frame;
    this.gameData = gameData;
    ...//creating the upper panel and set defaults for the panel

    //label for time
    timeLabel = new JLabel("Time: " + gameData.getTime());
    timeLabel.setFont(font);
    timeLabel.setForeground(Color.BLACK);

    /** updating the timeLabel */
    timer = new Timer(1000, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub
            if (gameData.getStartTime() > 0) {
                //getStartTime -= 1000;
                //time--;
                gameData.updateStartTime(-1000);
                gameData.updateTime(-1);
                if (gameData.getTime() == 0) {
                    frame.swapView("gameover");
                }
                timeLabel.setText("Time: " + gameData.getTime());
                timeLabel.repaint();
            }
        }
    });
    timer.start();

    //getting instance of QuestionRandomizer;       
    QuestionRandomizer qRand = new QuestionRandomizer();


    /*question 1 panel*/
    //------------------
    //------------------
    //------------------
    JPanel card1 = new JPanel(new GridBagLayout());
    card1.setBackground(new Color(0, 128, 43));
    Question q1 = qRand.getRandomQuestion();

    //label for the first question
    JLabel question1Label = new JLabel(q1.getText());
    question1Label.setFont(questionLabelsFont);
    question1Label.setForeground(Color.BLACK);

    //gbc for question1Label
    ...

    card1.add(question1Label, gbc2);

    //Panel holding buttons
    JPanel buttonsPanel = new JPanel(new GridLayout(2, 2));


    //Answer buttons

    JButton answer1 = new JButton(q1.getAnswers()[0].getText()+ "");
    answer1.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub
            if (q1.getAnswers()[0].getIsCorrect() == true) {
            CardLayout cl = (CardLayout) cards.getLayout();
            cl.show(cards, "question2");

            //updating the scores
            gameData.updateScore(100);
            scoresLabel.setText("Scores: " + gameData.getScore());
            scoresLabel.repaint();

            //updating the timer
            timer.stop();
            gameData.setTime(16);
            gameData.setStartTime(16*1000);
            timer.start();
            }       

            //IF THE ANSWER IS INCORRECT GO TO THE GAMEOVER PANEL!!!
            if (q1.getAnswers()[0].getIsCorrect() == false) {
                frame.swapView("gameover");
            }
        }       
    });
    //I have 3 more buttons for the answers in this question card and more questions  cards but the logic is the same for everything.
    public GameData getGameData() {
    return this.gameData;
}

在面板上看一下我的游戲:

public class GameOverPanel extends JPanel {
private StartGamePanel sgp;
private JLabel gameOverLabel;
private GameData gameData;

public GameOverPanel(StartGamePanel sgp) {
    this.sgp = sgp;
    this.gameData = sgp.getGameData(); // i created a method in the start game panel which returns start game panel's gameData object
    //default settings
    this.setLayout(new GridBagLayout());
    this.setBackground(new Color(0, 128, 43));
    this.setBorder(new EmptyBorder(10, 10, 10, 10));


    gameOverLabel = new JLabel("");


    gameOverLabel.setText("<html><h1>You didn't answer correctly!</h1><hr><h2></h2><h3>Your score: " + gameData.getScore() + "</h3></html>");

    gameOverLabel.setForeground(Color.BLACK);

    //constraints for the gameoverlabel
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.CENTER;
    gbc.gridwidth = GridBagConstraints.REMAINDER;

    this.add(gameOverLabel, gbc);

}
}

然后MainFrame類切換面板:

public class Frame extends JFrame {
CardLayout cl = new CardLayout();
GameData gameData = new GameData();
MainMenu menuPanel = new MainMenu(this);
StartGamePanel startPanel = new StartGamePanel(this, gameData);
GameOverPanel gameOverPanel = new GameOverPanel(startPanel);


public Frame() {
    this.setLayout(cl);
    this.setSize(800, 600);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
    this.setResizable(false);
    //this.setEnabled(true);


    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int screenWidth = screenSize.width;
    int screenHeight = screenSize.height;

    this.setLocation((screenWidth - getWidth()) / 2, (screenHeight - getHeight()) / 2);

    this.add(menuPanel, "menu");
    this.add(startPanel, "start");
    this.add(gameOverPanel, "gameover");
    swapView("menu");
}

public void swapView(String view) {
    cl.show(getContentPane(), view);
}
}

您尚未正確建模問題域。 這就是為什么您要面對這個問題。 您應該將questionscoretime等保留在單獨的域類(例如GameData )中,而不是JPanel類中。

在用戶啟動游戲的事件處理程序中,您應該首先創建GameData的實例,然后將該實例作為構造函數參數傳遞給StartGamePanel面板類。 同樣,在用戶結束游戲的事件處理程序中,應使用與傳遞給GameOverPanel並將其傳遞給GameData相同的GameData實例。

編輯

根據您提供的更多信息,除了以上將游戲數據分離為獨立GameData類的建議之外,還需要執行以下操作:

GameOverPanel類中添加一個新的setter方法。

public void setGameData(GameData gd) {
    this.gameData = gd;
}

startGamepanel類中添加一個新的getter方法。

public void getGameData() {
    return gamedata;
}

將主框架類中的swapView方法更新為以下內容:

public void swapView(String view) {
    if("gameover".equals(view)) {
         gameOverPanel.setGameData(startPanel.getGameData());
    }
    cl.show(getContentPane(), view);
    gameOverLabel.setText("<html><h1>You didn't answer correctly!</h1><hr><h2></h2><h3>Your score: " + gameData.getScore() + "</h3></html>");

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM