while循环在Swing应用程序中不可用吗?

时间:2016-09-30 00:05:28

标签: java arrays swing

基本上我有一个游戏板,我想让第一步移动到一个没有边缘的正方形上是非法的。该框架是一个5x5游戏板,根据轮到它的方式在点击时交替显示颜色。

我的问题:当我启动程序时,它并没有告诉我,我在中间按下的按钮是非法动作。任何人都可以解释为什么代码不起作用?

以下是一些示例代码:

package fgame;

import java.awt.Color;
import javax.swing.JOptionPane; 

public class FooFrame extends javax.swing.JFrame {

private Color whoseTurn = Color.BLACK;
private Color playerOneTurn = Color.BLACK;
private Color playerTwoTurn = Color.ORANGE;
private String playerOne = "You";
private String playerTwo;
private int PlayerOneCount = 21;
private int PlayerTwoCount = 21;


public FooFrame() {
    initComponents();
    setSize(800,800);
    setLocationRelativeTo(null);
    humanOrAI();
    movesLeft();
    endGame();


}

private void humanOrAI()
{
    Object[] options = {"Other Human","Computer (EASY)","Computer (HARD)"};

    Object input = (Object) JOptionPane.showInputDialog(null, 
            "Who is your opponent?",
            "CHOOSE YOUR FATE!",JOptionPane.QUESTION_MESSAGE,
            null,options,
            options[0]);  
    if (input == options[0]){
        playerTwo = (String.valueOf(options[0]));
    }
    else if (input == options[1]){
        playerTwo = (String.valueOf(options[1]));   
    }
    else {
        playerTwo = (String.valueOf(options[2]));
    }        
}

private void determineWhoseTurn()
{
    if (whoseTurn.equals(playerOneTurn))
    {
        whoseTurn = Color.orange;
    }
    else
    {
        whoseTurn = Color.BLACK;
    }
}

public void movesLeft()
{

    if (whoseTurn.equals(playerOneTurn))
    {
        jLabel1.setText(" " + playerOne + " have " + PlayerOneCount+ " pieces left    "
                + "         "+ playerTwo+ " has " + PlayerTwoCount+ " pieces left");
        PlayerOneCount--;
    }

    else
    {
        jLabel1.setText(" " + playerOne + " have " + PlayerOneCount+ " pieces left    "
                + "         "+ playerTwo+ " has " + PlayerTwoCount+ " pieces left");
        PlayerTwoCount--;
    }  
}

//How do I count the amount of black and orange squares?
public void endGame()
{
    int black = 0;
    int orange = 0;

    if (whoseTurn.equals(playerOneTurn))
    {
        black++;
    }
    else
    {
        orange++;
    }

    if (PlayerTwoCount <= 0 || PlayerOneCount <= 0)
    {
        JOptionPane.showMessageDialog(rootPane, "Game Over!" + " black: "+ black
        + "orange: "+ orange);
    }
}

public void validStartingPoint()
{
   Object illStartPoint[] = {B2,B3,B4,C2,C3,C4,D2,D3,D4};

   while (PlayerOneCount == 21 || PlayerTwoCount == 21)
       if (whoseTurn.equals(illStartPoint[0-8]))
       {
           JOptionPane.showMessageDialog(rootPane, "Not a valid move! Start "
                   + "from an edge square!");
       } else
       {
           break;
       }
}

我的问题与方法validStartingPoint()有关。但是我也有一个关于endGame()的问题,它被放在上面的评论中。我的所有JBUTTONS都要求所有方法

另外,我知道这可能与while循环无关。我不是世界上最好的编码员。

1 个答案:

答案 0 :(得分:3)

不可能给你特别的帮助,因为你写的问题不完整,但要回答你的直接问题:while循环当然适用于Swing应用程序,

但是,您不应该像在线性控制台应用程序中那样使用它们。理解Swing GUI,就像大多数GUI不是线性程序,其中一位代码必然跟随另一个,但它们是事件驱动程序,其中代码通常仅在事件后调用 - 例如按下按钮或鼠标按下。

所以你不想使用while循环来等待或轮询用户输入,而是想要使用“状态”机器类型设计并监听事件,状态是底层模型的状态对于你的程序,这里是你的游戏逻辑。

如果您需要更详细的帮助,请充实您的问题,包括创建并发布minimal example program供我们使用。

如果这些人是JButton,那么是的,while循环是错误的

Object illStartPoint[] = { B2, B3, B4, C2, C3, C4, D2, D3, D4 };

相反,按钮的ActionListener中应该有一个if语句,如果按下按钮是合法的,则按下按钮。这将取决于您所在程序的哪个部分,因此必须是if测试中的布尔语句的一部分,以确定它是否合法。例如,如果你阻止某人按下第一个按钮上的按钮,一些布尔人会这样做。

但话虽如此,我实际上会以不同的方式做事。我会停用任何不应该被按下的按钮,然后在应该按下它们时激活它们。这可以通过调用setEnabled(boolean enabled)并为该按钮传入true或false来完成,具体取决于程序所处的状态。

例如,运行此代码以查看我的意思:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;

public class TestButtons1 extends JPanel {
    private static final int BUTTON_COUNT = 10;
    // private boolean onlyEvenButtonsActve = true;
    private List<JButton> allButtons = new ArrayList<>();

    public TestButtons1() {
        JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
        for (int i = 0; i < BUTTON_COUNT; i++) {
            JButton button = new JButton("Button " + i);
            // add ActionListener
            button.addActionListener(e -> {
                System.out.println("Button pressed: " + e.getActionCommand());
            });

            buttonPanel.add(button);  // add to jpanel 
            allButtons.add(button); // add to array list for all buttons
        }

        JToggleButton activateOnlyEvensTglBtn = new JToggleButton("Activate Only Even Buttons");
        activateOnlyEvensTglBtn.addItemListener(e -> {
            for (int i = 0; i < allButtons.size(); i++) {
                boolean b = i % 2 == 0  || e.getStateChange() == ItemEvent.DESELECTED;
                allButtons.get(i).setEnabled(b);
            }
        });
        JPanel bottomPanel = new JPanel();
        bottomPanel.add(activateOnlyEvensTglBtn);

        setLayout(new BorderLayout());
        add(buttonPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

    private static void createAndShowGui() {
        TestButtons1 mainPanel = new TestButtons1();

        JFrame frame = new JFrame("TestButtons1");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}