Java Swing 无法获取变量的值 [英] Java Swing Can't Get Value Of Variable

查看:35
本文介绍了Java Swing 无法获取变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用两个不同的框架制作游戏.(我知道它无效)无论如何我的问题是我无法获得我在 actionListener 函数下更改的变量的值.

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.

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();
      
       
}

我所说的变量是flag1.我在全局声明了该变量.我想要做的是当我按下按钮时,它会关闭该框架并打开其他框架(已经在工作)并给我 flag1 值.我没有犯任何错误,但我无法获得 flag1 的值.游戏功能不起作用.请帮帮我

the variable i talk about is 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. I don't get any mistakes, but i can't get value of flag1. GamePlay function doesn't work. Please help me

推荐答案

简介

我整理了一个示例 Swing GUI 来展示如何创建多人游戏,其中每个玩家都有自己的 JPanel.一个计时器 JPanel 出现在显示播放器 JPanels 之间,因此您有时间换座位.

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. A timer JPanel appears in between showing the player JPanels so you have time to switch seats.

这是玩家 1 的 JPanel.

这是计时器 JPanel,倒计时.

Here's the timer JPanel, counting down.

这是玩家 2 的 JPanel.

我不只是更改了 JLabel 文本.您会在一个 JFrame 中看到两个播放器 JPanels.

I didn't just change the JLabel text. You're seeing two player JPanels in one JFrame.

当我创建 Swing GUI 时,我使用 模型/视图/控制器 (MVC) 模式.这种模式允许我将关注点分开,一次专注于 Swing 应用程序的一个部分.

When I create a Swing GUI, I use the model / view / controller (MVC) pattern. This pattern allows me to separate my concerns and focus on one part of the Swing application at a time.

使用 Java Swing 的 MVC 模式是这样工作的:

The MVC pattern using Java Swing works like this:

  1. 视图从模型中读取信息.
  2. 视图不会更新模型.
  3. 控制器更新模型并重新绘制/重新验证视图.

通常,一个 Swing 应用程序有多个控制器类,每个操作一个.这个例子有一个 ActionListener,因为我们所做的只是切换播放器 JPanels.

Usually, a Swing application has multiple controller classes, one for each action. This example has one ActionListener since all we're doing is switching player JPanels.

这个应用程序有两个模型类,PlayerGameState.现在,Player 类包含一个玩家名称.玩家的所有其他游戏信息(例如得分)都归入此类.

This application has two model classes, Player and GameState. For now, the Player class holds a player name. All other game information about a player, like score, goes in this class.

GameState 类保存有关游戏状态的信息.Player 实例的 List 告诉我们玩家的数量,int playerTurn 告诉我们轮到谁了.

The GameState class holds information about the game state. The List of Player instances tells us the number of players and the int playerTurn tells us whose turn it is.

这个 Swing GUI 由一个 JFrame 和一个使用 CardLayout 的主要 JPanel 组成.每个玩家都有自己的JPanel.播放器底部的 JButton JPanel 将您切换到下一个播放器.

This Swing GUI consists of a single JFrame, with a main JPanel using a CardLayout. Each player has their own JPanel. The JButton at the bottom of the player JPanel switches you to the next player.

每个玩家 JPanel 包含来自 GameState 类的任何信息,玩家在玩游戏时需要看到这些信息.播放器 JPanel 上可以有其他 JButtons 来改变播放器的状态.当玩家完成他的回合时,他点击下一回合 JButton 将游戏传递给下一个玩家.

Each player JPanel contains whatever information from the GameState class that a player needs to see to play the game. There can be other JButtons on the player JPanel that alter the state of the player. When the player finishes his turn, he clicks on the next turn JButton to pass the game to the next player.

现在,唯一的 ActionListener 是切换播放器 JPanels 的那个.有一个由 Swing Timer 控制的内部 ActionListener 允许玩家切换座位.您可以在外部 ActionListener 类中调整倒计时时间.其他 JButtons 会触发其他 ActionListeners.

Right now, the only ActionListener is the one that switches player JPanels. There's an internal ActionListener controlled by a Swing Timer that allows players to switch seats. You can adjust the countdown time in the outer ActionListener class. Other JButtons would trigger other ActionListeners.

这是完整的可运行示例.

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;
        }
        
    }

}

这篇关于Java Swing 无法获取变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆