繁体   English   中英

Java延迟执行开关

[英]Java executing switch with delay

我正在制作迷宫游戏,并且想要实现非常原始的自动播放选项。 绿色方块必须到达迷宫或线条末端的粉红色方块。

在下面的代码中,有2个按钮,“右键”每次单击将变为1个图块,而“操作”按钮每次将变为多个图块。

我对“操作”按钮有疑问。 我希望它一次变一格,然后休息一秒钟,再变一格。 我将switch语句与Thread.sleep()一起使用,但是与其结合使用1个图块并进行休息,它结合了休息时间,并在休眠时间结束后立即转到了最后一个case #图块。

如何逐步进行?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;

public class Line extends JFrame implements ActionListener  {


private JPanel jPBoard;
private JPanel jPControl;

private JButton jBFill[] = new JButton[16];
private JButton jBAct;
private JButton jBRight;

private Border empty;

private int fillCounter;
private int position;


public static void main(String[] args) {


    Line frame = new Line();
    frame.setSize(700, 100); 
    frame.createGUI(); 
    frame.setVisible(true);
}

private void createGUI()
{
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Container window = getContentPane();
    window.setLayout(new BorderLayout() );


    jPBoard = new JPanel(); 
    jPBoard.setPreferredSize(new Dimension(700, 60));               
    jPBoard.setBackground(Color.GRAY);
    window.add(jPBoard, BorderLayout.CENTER);                           
    jPBoard.setLayout(new GridLayout(1, 16));

    empty = BorderFactory.createEmptyBorder();

    for (fillCounter = 1; fillCounter < 16; fillCounter++) {            



        jBFill[fillCounter] = new JButton(""+fillCounter);          
        jBFill[fillCounter].setBorder(empty); 
        position = 1;
        jPBoard.add(jBFill[fillCounter]);

        jBFill[fillCounter].setBackground(Color.YELLOW);


        if (fillCounter == 15) 
        {               
            jBFill[fillCounter].setBackground(Color.PINK);
        }

        if (position == fillCounter) 
        {               
            jBFill[fillCounter].setBackground(Color.GREEN);
        }


        jPControl = new JPanel();
        jPControl.setLayout(new GridLayout(1,2) );
        jPControl.setPreferredSize(new Dimension(700, 40));
        jPControl.setBackground(Color.RED);
        window.add(jPControl, BorderLayout.SOUTH);


        jBRight = new JButton("Right");
        jPControl.add(jBRight);
        jBRight.addActionListener(this);

        jBAct = new JButton("Act");
        jPControl.add(jBAct);
        jBAct.addActionListener(this);
    }
}

@Override
public void actionPerformed(ActionEvent grid) {

    Object source = grid.getSource();
    if (source == jBRight){

          jBFill[position+1].setBackground(Color.GREEN);
          jBFill[position].setBackground(Color.YELLOW);
          position=position+1;

      }

    if (source == jBAct) {

        switch (position) {
        case 1: jBRight.doClick();
        try {                       
            Thread.sleep(100);
            } 
        catch (InterruptedException e) {
            e.printStackTrace();};


        case 2:  jBRight.doClick();
        try {                       
            Thread.sleep(100);
            } 
        catch (InterruptedException e) {
            e.printStackTrace();};


        case 3:  jBRight.doClick();
        try {                       
            Thread.sleep(100);
            } 
        catch (InterruptedException e) {
            e.printStackTrace();};

        case 4: jBRight.doClick();
        try {                       
            Thread.sleep(100);
            } 
        catch (InterruptedException e) {
            e.printStackTrace();};


        case 5:  jBRight.doClick();
        try {                       
            Thread.sleep(100);
            } 
        catch (InterruptedException e) {
            e.printStackTrace();};


        case 6:  jBRight.doClick();
        try {                       
            Thread.sleep(100);
            } 
        catch (InterruptedException e) {
            e.printStackTrace();};  

        case 7: jBRight.doClick();
        try {                       
            Thread.sleep(100);
            } 
        catch (InterruptedException e) {
            e.printStackTrace();};


        case 8:  jBRight.doClick();
        try {                       
            Thread.sleep(100);
            } 
        catch (InterruptedException e) {
            e.printStackTrace();};


        case 9:  jBRight.doClick();
        try {                       
            Thread.sleep(100);
            } 
        catch (InterruptedException e) {
            e.printStackTrace();};  

        default: break;
    }
    }
}
}   

同样,您的代码正在做的是

  1. 以一种不灵活的方式对开关的遍历进行硬编码
  2. 在Swing事件线程上调用Thread.sleep ,这将阻止该线程并使您的程序冻结,冻结,直到完成所有睡眠为止。

取而代之的是,您将希望使用Swing计时器通过List<JButton>进行“伪”循环,该List<JButton>是一个ArrayList,按希望遍历按钮的顺序保存按钮。

例如,编译并运行此命令以查看我的意思:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;

@SuppressWarnings("serial")
public class Line2 extends JPanel {
    private static final int BTN_COUNT = 256;
    private static final Dimension BTN_SZ = new Dimension(40, 40);
    private List<JButton> buttonList = new ArrayList<>();
    private JButton actButton;
    private int index = 0;

    public Line2() {
        JPanel buttonPanel = new JPanel(new GridLayout(16, 0));
        for (int i = 0; i < BTN_COUNT; i++) {
            JButton btn = new JButton("" + (i + 1));
            btn.setBorder(BorderFactory.createEmptyBorder());
            btn.setPreferredSize(BTN_SZ);
            buttonPanel.add(btn);
            buttonList.add(btn);
        }
        JButton actionButton = new JButton("Act");
        actionButton.addActionListener(e -> doAction());
        resetColors();
        buttonList.get(0).setBackground(Color.GREEN);

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

    public void resetColors() {
        for (int i = 0; i < buttonList.size(); i++) {
            Color color = Color.YELLOW;
            if (i == BTN_COUNT - 1) {
                color = Color.PINK;
            }
            buttonList.get(i).setBackground(color);
        }
    }

    private void doAction() {
        int timerDelay = 100;
        index = 0;
        new Timer(timerDelay, e -> {
            resetColors();
            if (index == BTN_COUNT) {
                ((Timer) e.getSource()).stop();
            } else {
                // buttonList.get(index).doClick();
                buttonList.get(index).setBackground(Color.GREEN);
                index++;
            }
        }).start(); 
    }

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

        JFrame frame = new JFrame("Line 2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

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

暂无
暂无

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

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