Java Swing计时器不清楚

时间:2014-04-15 00:41:46

标签: java swing timer sleep

我在使用Java swing的Timer函数时遇到了一些问题。我对Java编程很新,所以非常感谢任何帮助。我在本网站上查看了许多其他计时器问题,但没有人回答我的问题。我制作了一个GUI,可以让你玩石头剪刀,你可以选择点击三个按钮。我希望我的程序在您单击按钮后休眠约1秒钟,并在显示消息后再次休眠。在我意识到Thread.sleep()不能用于我的GUI之后,我试图实现一个计时器。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*; 
import javax.swing.border.Border;
import java.io.*;

public class rps { 
//ROCK PAPER SCISSORS
static JLabel middle = new JLabel();
static JLabel them = new JLabel();
static JLabel yourWins = new JLabel();
static JLabel theirWins = new JLabel();
static JPanel yourPanel = new JPanel();
static JPanel middlePanel = new JPanel();
static JLabel blank1 = new JLabel();
static JLabel blank2 = new JLabel();
static JButton rock = new JButton("Rock");
static JButton paper = new JButton("Paper");
static JButton scissors = new JButton("Scissors");
static int yw = 0;
static int tw = 0;
static ButtonHandler listener = new ButtonHandler();

public static void main(String[] args) { 

    //Create the frame
    JFrame frame = new JFrame("Rock Paper Scissors");
    frame.setSize(500, 500); //Setting the size of the frame

    middle.setFont(new Font("Serif", Font.PLAIN, 30)); 
    middle.setHorizontalAlignment(SwingConstants.CENTER);
    them.setFont(new Font("Serif", Font.PLAIN, 15));
    them.setHorizontalAlignment(SwingConstants.CENTER);
    yourWins.setHorizontalAlignment(SwingConstants.CENTER);
    theirWins.setHorizontalAlignment(SwingConstants.CENTER);

    //Creating panels
    JPanel bigPanel = new JPanel();

    Border border = BorderFactory.createLineBorder(Color.BLACK, 1); 
    Border wlb = BorderFactory.createLineBorder(Color.RED, 1); 
    them.setBorder(border);
    yourPanel.setBorder(border);
    bigPanel.setBorder(border);
    yourWins.setBorder(wlb);
    theirWins.setBorder(wlb);
    middlePanel.setBorder(border);

    //Creating grid layouts 
    GridLayout yourGrid = new GridLayout(1,3,10,10); 
    GridLayout theirGrid = new GridLayout(1,1); //One row, one column
    GridLayout middleGrid = new GridLayout(5,1);
    GridLayout bigGrid = new GridLayout(3,1);//Two rows, one column

    //Setting the layouts of each panel to the grid layouts created above
    yourPanel.setLayout(yourGrid); //Adding layout to buttons panel
    them.setLayout(theirGrid); //Adding layout to label panel
    middlePanel.setLayout(middleGrid); 
    bigPanel.setLayout(bigGrid);

    //Adding r/p/s to your grid.
    yourPanel.add(rock);
    yourPanel.add(paper);
    yourPanel.add(scissors);

    //Adding w/l rations to middlegrid.
    middlePanel.add(theirWins);
    middlePanel.add(blank1);
    middlePanel.add(middle);
    middlePanel.add(blank2);
    middlePanel.add(yourWins);

    //Attaching the listener to all the buttons
    rock.addActionListener(listener);
    paper.addActionListener(listener);
    scissors.addActionListener(listener);

    bigPanel.add(them);
    bigPanel.add(middlePanel);
    bigPanel.add(yourPanel); 

    //Shows the score at 0-0.
    yourWins.setText("Your wins: " + yw);
    theirWins.setText("Their wins: " + tw);

    frame.getContentPane().add(bigPanel); //panel to frame 
    frame.setVisible(true); // Shows frame on screen
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

//Class represents what do when a button is pressed
private static class ButtonHandler implements ActionListener { 
    public void actionPerformed (ActionEvent e) {
        Timer timer = new Timer(1000, this);

        String tc = random();
        them.setText("They chose: " + tc + "!");
        if (e.getSource() == rock) {
            whoWins("rock", tc);
        } else if (e.getSource() == paper) {
            whoWins("paper", tc);
        } else if (e.getSource() == scissors) {
            whoWins("scissors", tc);
        }
        yourWins.setText("Your wins: " + yw);
        theirWins.setText("Their wins: " + tw);

        timer.setRepeats(false);
        timer.start();
    }
} 

public static String random() {
    int random = (int) (Math.random() * 3);
    if (random == 0) {
        return "Rock";
    } else if (random == 1) {
        return "Paper";
    } else if (random == 2) {
        return "Scissors";
    }
    return "";
}

public static void whoWins(String yc, String tc) {
    if (yc.equals("rock")) {
        if (tc.equals("Rock")) {
            middle.setText("It's a tie!");            
        } else if (tc.equals("Paper")) {
            middle.setText("You lose!");
            tw++;
        } else if (tc.equals("Scissors")) {
            middle.setText("You win!");
            yw++;
        }
    } else if (yc.equals("paper")) {
        if (tc.equals("Rock")) {
            middle.setText("You win!");
            yw++;
        } else if (tc.equals("Paper")) {
            middle.setText("It's a tie!");
        } else if (tc.equals("Scissors")) {
            middle.setText("You lose!");
            tw++;
        }
    } else if (yc.equals("scissors")) {
        if (tc.equals("Rock")) {
            middle.setText("You lose!");
            tw++;
        } else if (tc.equals("Paper")) {
            middle.setText("You win!");
            yw++;
        } else if (tc.equals("Scissors")) {
            middle.setText("It's a tie!");
        }
    }
}
}

实际发生的是从按下按钮到显示消息时没有延迟,因为显然我没有正确使用定时器。我希望计时器只运行一次,运行后代码将执行。但是,当我单击一个按钮时,虽然setRepeats为false,但计时器将在重复时运行。因此,我想要显示的消息,而不是被延迟,即时显示,然后继续循环并继续显示消息(消息是随机的),直到我关闭程序。如果我再次单击该按钮,它将使计时器的速度加倍,并且消息显示速度快两倍,依此类推。

them.setText("They chose: " + tc + "!");

这是重复显示的消息,变量tc每次都在变化。计时器似乎只是在每个计时器间隔(1s)显示此消息。

非常感谢任何帮助。

编辑:

所以我添加了这一部分:

private static class ButtonHandler implements ActionListener { 
    public void actionPerformed (ActionEvent e) {
        // I'd be disabling the buttons here to prevent
        // the user from trying to trigger another 
        // update...

        // This is an instance field which is used by your
        // listener

        Timer timer = new Timer(1000, listenert);
        timer.setRepeats(false);
        timer.start();
    }
}
private static class timer implements ActionListener {
    public void actionPerformed (ActionEvent e) {
        String tc = random(); //A method that chooses a random word.
        them.setText("They chose: " + tc + "!"); 
        if (e.getSource() == rock) {
            whoWins("rock", tc); //whoWins is a method that will display a message.
        } else if (e.getSource() == paper) {
            whoWins("paper", tc);
        } else if (e.getSource() == scissors) {
            whoWins("scissors", tc);
        }
        yourWins.setText("Your wins: " + yw);
        theirWins.setText("Their wins: " + tw);

        // Start another Timer here that waits 1 second
        // and re-enables the other buttons...
    }
}

所以我认为现在发生的是当我点击一个按钮时,buttonhandler监听器启动定时器,该定时器附加到定时器监听器(名为listenert),它将运行定时器类的actionPerformed中的代码。但是睡眠功能仍无法正常工作

编辑2.5:

 private static class ButtonHandler implements ActionListener { 
    public void actionPerformed (ActionEvent e) {
        final JButton button = (JButton)e.getSource();
        Timer timer = new Timer(1000, new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        String tc = random();
                        them.setText("They chose: " + tc + "!");
                        if (button == rock) {
                            whoWins("rock", tc);
                        } else if (button == paper) {
                            whoWins("paper", tc);
                        } else if (button == scissors) {
                            whoWins("scissors", tc);
                        }
                        yourWins.setText("Your wins: " + yw);
                        theirWins.setText("Their wins: " + tw);
                    }
                });
        timer.setRepeats(false);
        timer.start();     

    }
} 

这就是我到目前为止,我只需要在之后添加其他睡眠     them.setText(“他们选择:”+ tc +“!”); 如果有的话,我会在哪里放一个timer.restart()? timer.start()在方法的最后,我不太明白。

2 个答案:

答案 0 :(得分:3)

因此,当计时器"勾选"时,您向[{1}}提供的ActionListener会收到通知,因此您Timer ButtonHandler应该更像...

actionPerformed

您的public void actionPerformed (ActionEvent e) { // I'd be disabling the buttons here to prevent // the user from trying to trigger another // update... // This is an instance field which is used by your // listener choice = e.getSource(); Timer timer = new Timer(1000, listener); timer.setRepeats(false); timer.start(); } 应该更像

listener

例如......

您可以考虑查看How to use Swing Timers了解更多详情

<强>更新

从一个简单的例子开始......     公共类TestPane扩展了JPanel {

public void actionPerformed (ActionEvent e) {
    String tc = random(); //A method that chooses a random word.
    them.setText("They chose: " + tc + "!"); 
    if (choice == rock) {
        whoWins("rock", tc); //whoWins is a method that will display a message.
    } else if (choice == paper) {
        whoWins("paper", tc);
    } else if (choice == scissors) {
        whoWins("scissors", tc);
    }
    yourWins.setText("Your wins: " + yw);
    theirWins.setText("Their wins: " + tw);

    // Start another Timer here that waits 1 second
    // and re-enables the other buttons...
}

这只是每隔半秒调用 private JLabel label; private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); public TestPane() { setLayout(new GridBagLayout()); label = new JLabel(); add(label); tick(); Timer timer = new Timer(500, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { tick(); } }); timer.start(); } protected void tick() { label.setText(sdf.format(new Date())); } } 方法来更新tick上的时间...

答案 1 :(得分:0)

首先导入以下内容;

import java.awt.event.ActionEvent ;

import java.awt.event.ActionListener ;

import javax.swing.Timer ; 

然后在表格的末尾初始化计时器,如下所示; public static void main(String args []){

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

});

}    
    private Timer timer ;

然后在初始化定时器后添加一个公共类,如下所示;

公共类进度实现ActionListener {     public void actionPerformed(ActionEvent evt){

int n = 0 ;
if (n<100){
    n++ ;
    System.out.println(n) ;
}else{
    timer.stop() ;
}
}
}

执行此操作后,转到j框架&gt;右键单击并选择&gt;事件&gt;窗口&gt;窗口打开并键入以下内容;

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
        timer = new Timer(100,new progress()) ;

并且在您完成所有操作之后,将一个按钮命名为任何内容,并在其空白处键入以下内容,如下所示;

 timer.start();

这就是它的代码,然后回复我......