简体   繁体   English

Java Swing 无法获取变量的值

[英]Java Swing Can't Get Value Of Variable

Im trying to make a game with two diffrent frames.我试图用两个不同的帧制作游戏。 (I know its not effective) Anyways my problem is i can't get the value of my variable that i changed under actionListener function. (我知道它无效)无论如何我的问题是我无法获得我在 actionListener function 下更改的变量的值。

public void Pick_Char() {
    
    frame2 = new JFrame();
    frame2.setBounds(100, 100, 925, 805);
    frame2.setLocationRelativeTo(null);
    frame2.setResizable(false);
    frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    
    JPanel panel = new JPanel();
    
    btnNewButton = new JButton("Gözlüklü Şirin");
    btnNewButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
                        
            Main window = null;
            try {
                 
                window = new Main();
            } catch (IOException e1) {
                
                e1.printStackTrace();
            }

            flag1=true;
            window.frame2.setVisible(false);
            frame2.dispose();
            window.frame.setVisible(true);
            
            
            
        }
    });

public Main() throws IOException {
    Pick_Char();
        initialize();
        if(flag1 == true)
             GamePlay();
      
       
}

the variable i talk about is flag1.我谈论的变量是flag1。 I declared that variable globally.我在全局范围内声明了该变量。 What im trying to do is when i press the button, it will close that frame and open other frame (which is already working) and give me the flag1 value.我想要做的是当我按下按钮时,它会关闭该框架并打开其他框架(它已经在工作)并给我 flag1 值。 I don't get any mistakes, but i can't get value of flag1.我没有得到任何错误,但我无法获得 flag1 的值。 GamePlay function doesn't work. GamePlay function 不工作。 Please help me请帮我

Introduction介绍

I put together an example Swing GUI to show how a multi-player game can be created where each player has their own JPanel .我整理了一个示例 Swing GUI 来展示如何在每个玩家都有自己的JPanel的情况下创建多人游戏。 A timer JPanel appears in between showing the player JPanels so you have time to switch seats.在显示播放器JPanels之间会出现一个计时器JPanel ,因此您有时间切换座位。

Here's Player 1's JPanel .这是玩家 1 的JPanel

玩家 1 JPanel

Here's the timer JPanel , counting down.这是计时器JPanel ,正在倒计时。

定时器 JPanel

Here's Player 2's JPanel .这是 Player 2 的JPanel

播放器 2 JPanel

I didn't just change the JLabel text.我不仅更改了JLabel文本。 You're seeing two player JPanels in one JFrame .您在一个JFrame中看到两个玩家JPanels

Explanation解释

When I create a Swing GUI, I use the model / view / controller (MVC) pattern.当我创建 Swing GUI 时,我使用model / view / controller (MVC) 模式。 This pattern allows me to separate my concerns and focus on one part of the Swing application at a time.这种模式使我能够分离我的关注点,并一次专注于 Swing 应用程序的一部分。

The MVC pattern using Java Swing works like this:使用 Java Swing 的 MVC 模式是这样工作的:

  1. The view reads information from the model.该视图从 model 读取信息。
  2. The view does not update the model.该视图不会更新 model。
  3. The controller updates the model and repaints / revalidates the view. controller 更新 model 并重新绘制/重新验证视图。

Usually, a Swing application has multiple controller classes, one for each action.通常,一个 Swing 应用程序有多个 controller 类,每个操作一个。 This example has one ActionListener since all we're doing is switching player JPanels .这个例子有一个ActionListener因为我们所做的只是切换播放器JPanels

Model Model

This application has two model classes, Player and GameState .此应用程序有两个 model 类, PlayerGameState For now, the Player class holds a player name.目前, Player class 拥有玩家姓名。 All other game information about a player, like score, goes in this class.有关玩家的所有其他游戏信息,例如得分,都在此 class 中。

The GameState class holds information about the game state. GameState class 保存有关游戏 state 的信息。 The List of Player instances tells us the number of players and the int playerTurn tells us whose turn it is. Player实例List告诉我们玩家的数量,而int playerTurn告诉我们轮到谁了。

View看法

This Swing GUI consists of a single JFrame , with a main JPanel using a CardLayout .这个 Swing GUI 由一个JFrame组成,主JPanel使用CardLayout Each player has their own JPanel .每个玩家都有自己的JPanel The JButton at the bottom of the player JPanel switches you to the next player.播放器JPanel底部的JButton将您切换到下一个播放器。

Each player JPanel contains whatever information from the GameState class that a player needs to see to play the game.每个玩家JPanel都包含来自GameState class 的玩家玩游戏需要看到的任何信息。 There can be other JButtons on the player JPanel that alter the state of the player.播放器JPanel上可能还有其他JButtons可以改变播放器的 state。 When the player finishes his turn, he clicks on the next turn JButton to pass the game to the next player.当玩家完成他的回合时,他点击下一个回合JButton将游戏传递给下一个玩家。

Controller Controller

Right now, the only ActionListener is the one that switches player JPanels .现在,唯一的ActionListener是切换播放器JPanels的那个。 There's an internal ActionListener controlled by a Swing Timer that allows players to switch seats.有一个由 Swing Timer控制的内部ActionListener ,允许玩家切换座位。 You can adjust the countdown time in the outer ActionListener class.您可以在外部ActionListener class 中调整倒计时时间。 Other JButtons would trigger other ActionListeners .其他JButtons会触发其他ActionListeners

Code代码

Here's the complete runnable example.这是完整的可运行示例。

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class MultiPlayerGame implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new MultiPlayerGame());
    }
    
    private CardLayout cardLayout;
    
    private GameState gameState;
    
    private JLabel timerLabel;
    
    private JPanel mainPanel;
    private JPanel timerPanel;
    
    private PlayerPanel[] playerPanels;
    
    public MultiPlayerGame() {
        this.gameState = new GameState();
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("MultiPlayer Game");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        this.mainPanel = createMainPanel();
        frame.add(mainPanel, BorderLayout.CENTER);
        
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
    
    private JPanel createMainPanel() {
        cardLayout =  new CardLayout();
        JPanel panel = new JPanel(cardLayout);
        
        List<Player> players = gameState.getPlayers();
        playerPanels = new PlayerPanel[players.size()];
        for (int i = 0; i < players.size(); i++) {
            Player player = players.get(i);
            playerPanels[i] = new PlayerPanel(this, gameState, 
                    player);
            panel.add(playerPanels[i].getPanel(), player.getName());
        }
        
        timerPanel = createTimerPanel();
        panel.add(timerPanel, "timer");
        
        return panel;
    }
    
    private JPanel createTimerPanel() {
        JPanel panel = new JPanel(new FlowLayout());
        
        timerLabel = new JLabel(" ");
        timerLabel.setFont(panel.getFont().deriveFont(16f));
        panel.add(timerLabel);
        
        return panel;
    }
    
    public void updateTimerPanel(Player player, int seconds) {
        String text = "" + seconds + " seconds before " + 
                player.getName() + " may play";
        timerLabel.setText(text);
    }
    
    public CardLayout getCardLayout() {
        return cardLayout;
    }

    public JPanel getMainPanel() {
        return mainPanel;
    }

    public JPanel getTimerPanel() {
        return timerPanel;
    }

    public class PlayerPanel {
        
        private final MultiPlayerGame frame;
        
        private final GameState model;
        
        private final JPanel panel;

        public PlayerPanel(MultiPlayerGame frame, GameState model, Player player) {
            this.frame = frame;
            this.model = model;
            this.panel = createPlayerPanel(player);
        }
        
        private JPanel createPlayerPanel(Player player) {
            JPanel panel = new JPanel(new BorderLayout(5, 5));
            panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
            panel.setPreferredSize(new Dimension(300, 200));
            
            JLabel label = new JLabel(player.getName());
            label.setFont(panel.getFont().deriveFont(Font.BOLD, 24f));
            label.setHorizontalAlignment(JLabel.CENTER);
            panel.add(label, BorderLayout.BEFORE_FIRST_LINE);
            
            JButton button = new JButton("Next Player's Turn");
            button.addActionListener(new ButtonListener(frame, model));
            panel.add(button, BorderLayout.AFTER_LAST_LINE);
            
            return panel;
        }

        public JPanel getPanel() {
            return panel;
        }
        
    }
    
    public class ButtonListener implements ActionListener {
        
        private final MultiPlayerGame frame;
        
        private final GameState model;
        
        private Timer timer;

        public ButtonListener(MultiPlayerGame frame, GameState model) {
            this.frame = frame;
            this.model = model;
        }

        @Override
        public void actionPerformed(ActionEvent event) {
            int delayPeriod = 30;
            int turn = model.nextPlayerTurn();
            Player player = model.getPlayers().get(turn);
            CardLayout cardLayout = frame.getCardLayout();
            timer = new Timer(1000, new ActionListener() {
                private int delay = delayPeriod;
                
                @Override
                public void actionPerformed(ActionEvent innerEvent) {
                    --delay;
                    frame.updateTimerPanel(player, delay);
                    if (delay < 0) {
                        cardLayout.show(frame.getMainPanel(), 
                                player.getName());
                        timer.stop();
                    }
                }
            });
            timer.start();
            frame.updateTimerPanel(player, delayPeriod);
            cardLayout.show(frame.getMainPanel(), "timer");
        }
        
    }
    
    public class GameState {
        
        private int playerTurn;
        
        private final List<Player> players;
        
        public GameState() {
            this.players = new ArrayList<>();
            this.players.add(new Player("Player 1"));
            this.players.add(new Player("Player 2"));
            this.playerTurn = 0;
        }
        
        public int nextPlayerTurn() {
            playerTurn = ++playerTurn % players.size();
            return playerTurn;
        }

        public int getPlayerTurn() {
            return playerTurn;
        }

        public List<Player> getPlayers() {
            return players;
        }
        
    }
    
    public class Player {
        
        private final String name;

        public Player(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
        
    }

}

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

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