为什么这个 java 程序不能正常工作?

Why this java program not working properly?

我是 java 的新手,正如您在 java 中看到的这个程序一样,swing 由一个 jframe 和一个 jpanel 组成。当您单击一个按钮时,它的颜色变为红色,并且自动按下按钮 1 并且它的颜色变为蓝色。

但问题是我希望这些操作之间有延迟,当我使用 Thread.sleep(1000) 时,它会导致按下按钮和更改其颜色之间的延迟,我不希望这样。

当我按下按钮 2 时(例如)它的颜色立即改变并且在按下按钮 1 1 秒后我能做什么?

jframe:

public class NewJFrame extends javax.swing.JFrame {

    private String player = "Player 1";
    private JButton[] btn = new JButton[4];

    public NewJFrame() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        newJPanel1 = new NewJPanel();
        newJPanel2 = new NewJPanel();
        btn1 = new javax.swing.JButton();
        btn2 = new javax.swing.JButton();
        btn3 = new javax.swing.JButton();

        javax.swing.GroupLayout newJPanel1Layout = new javax.swing.GroupLayout(newJPanel1);
        newJPanel1.setLayout(newJPanel1Layout);
        newJPanel1Layout.setHorizontalGroup(
                newJPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 100, Short.MAX_VALUE)
        );
        newJPanel1Layout.setVerticalGroup(
                newJPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 100, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        newJPanel2.setBackground(new java.awt.Color(255, 255, 255));
        newJPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        btn1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAction(evt);
            }
        });

        btn2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAction(evt);
            }
        });

        btn3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAction(evt);
            }
        });

        javax.swing.GroupLayout newJPanel2Layout = new javax.swing.GroupLayout(newJPanel2);
        newJPanel2.setLayout(newJPanel2Layout);
        newJPanel2Layout.setHorizontalGroup(
                newJPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(newJPanel2Layout.createSequentialGroup()
                                .addGap(35, 35, 35)
                                .addComponent(btn1)
                                .addGap(74, 74, 74)
                                .addComponent(btn2)
                                .addGap(66, 66, 66)
                                .addComponent(btn3)
                                .addContainerGap(104, Short.MAX_VALUE))
        );
        newJPanel2Layout.setVerticalGroup(
                newJPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(newJPanel2Layout.createSequentialGroup()
                                .addGap(31, 31, 31)
                                .addGroup(newJPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(btn1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(btn2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(btn3, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addContainerGap(222, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(newJPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addContainerGap())
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(newJPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void btnAction(java.awt.event.ActionEvent evt) {
        JButton btn = (JButton) evt.getSource();
        if (player.equals("Player 1")) {
            player = "Player 2";
            btn.setBackground(Color.RED);
        } else {
            player = "Player 1";
            btn.setBackground(Color.BLUE);
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        player2Action();

    }

    private void player2Action() {
        if (player.equals("Player 2")) {
            btn1.doClick();
        }

    }

    public static void main(String args[]) {

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

// Variables declaration - do not modify                     
    private javax.swing.JButton btn1;
    private javax.swing.JButton btn2;
    private javax.swing.JButton btn3;
    private NewJPanel newJPanel1;
    private NewJPanel newJPanel2;
// End of variables declaration                   
}

jpanel:

public class NewJPanel extends javax.swing.JPanel {

    public NewJPanel() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>                        

    // Variables declaration - do not modify                     
    // End of variables declaration                   
}

在这种情况下,使用 Timer 代替 Thread。查看来自 Andrew Thompson 的评论了解更多详情。

要修复您的代码,只需删除 Thread.sleep 的 try-catch 块及其旁边的 player2Action() 方法。然后添加以下代码使其工作:

ActionListener player2ActionListener = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        player2Action();
    }
};
Timer timer = new Timer(1000, player2ActionListener);
timer.setRepeats(false);
timer.start();

并且不要忘记导入 javax.swing.Timer