Advertisement
Guest User

Untitled

a guest
Apr 7th, 2020
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.00 KB | None | 0 0
  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.util.Timer;
  4. import java.util.*;
  5.  
  6. class React {
  7.     private static Date startTime;
  8.  
  9.     public static void start() {
  10.         startTime = new Date();
  11.     }
  12.  
  13.     public static Long end() {
  14.         return (new Date()).getTime() - startTime.getTime();
  15.     }
  16. }
  17.  
  18. class MyJFrame extends JFrame {
  19.     private static Timer timer = new Timer();
  20.  
  21.     public MyJFrame(String title) {
  22.         super(title);
  23.         setSize(new Dimension(300, 150));
  24.         setVisible(true);
  25.         setLocationRelativeTo(null);
  26.         setResizable(false);
  27.         setLayout(GridBagLayout());
  28.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  29.         getContentPane().setBackground(Color.WHITE);
  30.  
  31.         JButton reactBtn = new JButton("Start");
  32.         reactBtn.setFocusable(false);
  33.         reactBtn.addActionListener(event => {
  34.             if (reactBtn.getText().equalsIgnoreCase("start")) {
  35.                 reactBtn.setText("React");
  36.                 reactBtn.setEnabled(false);
  37.  
  38.                 Random rand = new Random();
  39.                 scheduleTask(() -> {
  40.                     getContentPane().setBackground(Color.BLUE);
  41.                     React.start();
  42.                     reactBtn.setEnabled(true);
  43.                 }, rand.nextInt(11500));
  44.  
  45.             } else {
  46.                 JOptionPane.showMessageDialog(null, "WINNER: " + React.end() + " milliseconds", "RESULT", JOptionPane.INFORMATION_MESSAGE);
  47.                 getContentPane().setBackground(Color.WHITE);
  48.                 reactBtn.setText("Start");
  49.             }
  50.         };
  51.  
  52.         add(reactBtn, new GridBagConstraints());
  53.     }
  54.  
  55.     private void scheduleTask(final Runnable runnable, long delay) {
  56.         timer.schedule(new TimerTask() {
  57.             @Override
  58.             public void run() {
  59.                 runnable.run();
  60.             }
  61.         }, delay);
  62.     }
  63.  
  64. }
  65.  
  66. public class Debug {
  67.     public static void main(String[] args) {
  68.         new MyJFrame("React Play");
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement