Java执行开关延迟

时间:2018-04-22 02:59:27

标签: java

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

在下面的代码中有2个按钮,右键每次点击1个图块,而Act按钮每次点击多个图块。

我的Act按钮有问题。我希望它当时去一块瓷砖,然后休息1秒,再去另一块瓷砖。我将switch语句与Thread.sleep()一起使用,但它没有使用1个tile并休息,而是将休息时间合并到睡眠时间结束后立即转到最后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 个答案:

答案 0 :(得分:0)

同样,您的代码正在做什么

  1. 以不灵活的方式对交换机遍历进行硬编码
  2. 在Swing事件线程上调用Thread.sleep,该线程将阻止此线程并使程序无法运行,冻结,直到所有休眠完成。
  3. 相反,您将需要使用Swing Timer来通过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());
        }
    }