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

问题描述 投票:0回答:1

我是Java的新手,正如您在Java swing中看到的那样,该程序由一个jframe和一个jpanel组成。当您单击按钮时,其颜色变为红色,并自动按下按钮1,其颜色变为蓝色。但是问题是我想要这些动作之间的延迟,而当我使用Thread.sleep(1000)时,这会导致按下按钮和更改其颜色之间的延迟,而我不希望那样。当我按下按钮2时(例如),它的颜色立即改变,并且在按下1秒钟的按钮1之后该怎么办?

jframe:

 import java.awt.Color;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 import javax.swing.JButton;

  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                   

}

java swing colors jbutton sleep
1个回答
0
投票

在这种情况下,请使用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

© www.soinside.com 2019 - 2024. All rights reserved.