2016-05-22 9 views
-1

Ich habe für einige Zeit verschiedene Methoden erforscht, um eine Aufgabe nach einer bestimmten Zeit (z. B. Quartz, ScheduledThreadPool, java.util.timer) zu planen und ich habe Probleme zu verstehen, wie man es benutzt .Ich versuche, java.util.timer zu verwenden, um eine Aufgabe regelmäßig zu planen; Ich bin mir nicht sicher, wie

Hier ist nur ein Beispiel, das ich aus meiner Forschung gefunden habe und unten werde ich den Code einfügen, den ich erstelle. --->

import java.util.Timer; 
 
import java.util.TimerTask; 
 

 
public class TaskManager { 
 

 
    private Timer timer = new Timer(); 
 

 
    public static void main(String[] args) { 
 
     TaskManager manager = new TaskManager(); 
 
     manager.startTask(); 
 
    } 
 

 
    public void startTask() { 
 
     timer.schedule(new PeriodicTask(), 0); 
 
    } 
 

 
    private class PeriodicTask extends TimerTask { 
 
     @Override 
 
     public void run() { 
 
      System.out.println(System.currentTimeMillis() + " Running"); 
 

 
      /* replace with the actual task */ 
 
      try { 
 
       Thread.sleep(15 * 1000); 
 
      } catch(InterruptedException e) { 
 
       e.printStackTrace(); 
 
      } 
 
      /* end task processing */ 
 

 
      System.out.println(System.currentTimeMillis() + " Scheduling 10 seconds from now"); 
 
      timer.schedule(new PeriodicTask(), 10 * 1000); 
 
     } 
 
    } 
 
}

Bitte GUI App Methode ignorieren, ich es nur aus Gründen der Übersichtlichkeit eingefügt in. Auch ich verstehe, dass mein Code unorganisiert sein kann, es tut mir leid im Voraus dafür.

Also im Grunde habe ich eine GUI mit drei Frames erstellt; Erstens ist nur der Startrahmen, so dass ignoriert werden kann. Der zweite Rahmen ist derjenige, der im Grunde den Timer verwenden wird. Was ich versuche zu tun ist ein Memory-Spiel zu erstellen, das 12 Zufallszahlen von 1 bis 12 in einem Array von 12 JButtons anzeigt (das habe ich schon) und dann nach einer bestimmten Zeit entfernt oder versteckt (was immer besser ist) die Zahlen und Die Person, die spielt, muss sie in aufsteigender Reihenfolge anklicken. Wenn die Person sie richtig anklickt, bekommt sie 1 Punkt, wenn sie keine Punkte bekommt. Er klickt dann auf die Schaltfläche "Antwort prüfen" und die Nummern werden zurückgesetzt und der Timer startet erneut. Dies wird nur 15 mal passieren.

Und nur für die Klarheit ist die Hilfe, die ich brauche, mit der Implementierung des Timer-Attributs. Danke an alle, die sich die Zeit nehmen, dies zu lesen. Du bist ein Lebensretter!

// The "TryTryTryAgain" class. 
 
import javax.swing.*; 
 
import java.awt.*; 
 
import java.awt.event.*; 
 
import java.applet.*; 
 
import java.net.URL; 
 
import java.util.Arrays; 
 
import java.util.TimerTask; 
 
import java.util.Date; 
 
import java.util.Timer; 
 

 

 
public class JavaMemoryGame_Final { 
 
    static JButton btnStart, buttonArray[] = new JButton[12]; 
 
    static JFrame start, questions, survey; 
 
    static JTextField nameEnter; 
 
    static JLabel scoreOutput, lblTitle, lblPrompt1, lblPrompt2, t_fImage, lblInstruct, lblReadyCheck; 
 
    static JRadioButton reallyBad, bad, good, reallyGood; 
 
    static AudioClip clap, yess, noo; 
 
    static ButtonGroup finalSurvey; 
 
    static DefaultListModel listModel; 
 
    static JList difficulty; 
 
    static int randNumGenerator; 
 
    static int score = 0, arrayImage[] = new int[12]; 
 

 

 
    private Timer timer = new Timer(); 
 

 

 
    public static JButton[] randNum() { 
 

 
    arrayImage[0] = (int)(Math.random() * 12) + 1; 
 
    arrayImage[1] = (int)(Math.random() * 12) + 1; 
 
    while (arrayImage[1] == arrayImage[0]) { 
 
     arrayImage[1] = (int)(Math.random() * 12) + 1; 
 
    } 
 
    arrayImage[2] = (int)(Math.random() * 12) + 1; 
 
    while (arrayImage[2] == arrayImage[1] || arrayImage[2] == arrayImage[0]) { 
 
     arrayImage[2] = (int)(Math.random() * 12) + 1; 
 
    } 
 
    arrayImage[3] = (int)(Math.random() * 12) + 1; 
 
    while (arrayImage[3] == arrayImage[2] || arrayImage[3] == arrayImage[1] || arrayImage[3] == arrayImage[0]) { 
 
     arrayImage[3] = (int)(Math.random() * 12) + 1; 
 
    } 
 
    arrayImage[4] = (int)(Math.random() * 12) + 1; 
 
    while (arrayImage[4] == arrayImage[3] || arrayImage[4] == arrayImage[2] || arrayImage[4] == arrayImage[1] || arrayImage[4] == arrayImage[0]) { 
 
     arrayImage[4] = (int)(Math.random() * 12) + 1; 
 
    } 
 
    arrayImage[5] = (int)(Math.random() * 12) + 1; 
 
    while (arrayImage[5] == arrayImage[4] || arrayImage[5] == arrayImage[3] || arrayImage[5] == arrayImage[2] || arrayImage[5] == arrayImage[1] || arrayImage[5] == arrayImage[0]) { 
 
     arrayImage[5] = (int)(Math.random() * 12) + 1; 
 
    } 
 
    arrayImage[6] = (int)(Math.random() * 12) + 1; 
 
    while (arrayImage[6] == arrayImage[5] || arrayImage[6] == arrayImage[4] || arrayImage[6] == arrayImage[3] || arrayImage[6] == arrayImage[2] || arrayImage[6] == arrayImage[1] || arrayImage[6] == arrayImage[0]) { 
 
     arrayImage[6] = (int)(Math.random() * 12) + 1; 
 
    } 
 
    arrayImage[7] = (int)(Math.random() * 12) + 1; 
 
    while (arrayImage[7] == arrayImage[6] || arrayImage[7] == arrayImage[5] || arrayImage[7] == arrayImage[4] || arrayImage[7] == arrayImage[3] || arrayImage[7] == arrayImage[2] || arrayImage[7] == arrayImage[1] || arrayImage[7] == arrayImage[0]) { 
 
     arrayImage[7] = (int)(Math.random() * 12) + 1; 
 
    } 
 
    arrayImage[8] = (int)(Math.random() * 12) + 1; 
 
    while (arrayImage[8] == arrayImage[7] || arrayImage[8] == arrayImage[6] || arrayImage[8] == arrayImage[5] || arrayImage[8] == arrayImage[4] || arrayImage[8] == arrayImage[3] || arrayImage[8] == arrayImage[2] || arrayImage[8] == arrayImage[1] || arrayImage[8] == arrayImage[0]) { 
 
     arrayImage[8] = (int)(Math.random() * 12) + 1; 
 
    } 
 
    arrayImage[9] = (int)(Math.random() * 12) + 1; 
 
    while (arrayImage[9] == arrayImage[8] || arrayImage[9] == arrayImage[7] || arrayImage[9] == arrayImage[6] || arrayImage[9] == arrayImage[5] || arrayImage[9] == arrayImage[4] || arrayImage[9] == arrayImage[3] || arrayImage[9] == arrayImage[2] || arrayImage[9] == arrayImage[1] || arrayImage[9] == arrayImage[0]) { 
 
     arrayImage[9] = (int)(Math.random() * 12) + 1; 
 
    } 
 
    arrayImage[10] = (int)(Math.random() * 12) + 1; 
 
    while (arrayImage[10] == arrayImage[9] || arrayImage[10] == arrayImage[8] || arrayImage[10] == arrayImage[7] || arrayImage[10] == arrayImage[6] || arrayImage[10] == arrayImage[5] || arrayImage[10] == arrayImage[4] || arrayImage[10] == arrayImage[3] || arrayImage[10] == arrayImage[2] || arrayImage[10] == arrayImage[1] || arrayImage[10] == arrayImage[0]) { 
 
     arrayImage[10] = (int)(Math.random() * 12) + 1; 
 
    } 
 
    arrayImage[11] = (int)(Math.random() * 12) + 1; 
 
    while (arrayImage[11] == arrayImage[10] || arrayImage[11] == arrayImage[9] || arrayImage[11] == arrayImage[8] || arrayImage[11] == arrayImage[7] || arrayImage[11] == arrayImage[6] || arrayImage[11] == arrayImage[5] || arrayImage[11] == arrayImage[4] || arrayImage[11] == arrayImage[3] || arrayImage[11] == arrayImage[2] || arrayImage[11] == arrayImage[1] || arrayImage[11] == arrayImage[0]) { 
 
     arrayImage[11] = (int)(Math.random() * 12) + 1; 
 
    } 
 

 
    for (int x = 0; x <= 11; x++) { 
 
     buttonArray[x] = new JButton("" + arrayImage[x]); 
 
     buttonArray[x].setBackground(Color.orange); 
 
    } 
 
    for (int i = 0; i <= 11; i++) { 
 
     buttonArray[i].setActionCommand("" + arrayImage[i]); 
 

 
    } 
 

 
    return buttonArray; 
 
    } 
 

 

 
    private static void guiApp() { 
 

 
    start = new JFrame("Welcome"); 
 
    start.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
 
    questions = new JFrame("Memry_Game"); 
 
    questions.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
 
    survey = new JFrame("How Was It?"); 
 
    survey.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
 
    btnStart = new JButton("Enter"); 
 

 
    lblTitle = new JLabel("Memory Match Game!"); 
 
    lblInstruct = new JLabel("Welcome to the Memory Match Game!"); 
 
    lblPrompt1 = new JLabel("Please enter your first name:"); 
 
    lblPrompt2 = new JLabel("Choose Difficulty (#of seconds):"); 
 
    nameEnter = new JTextField(""); 
 
    scoreOutput = new JLabel("Score: " + score + "/15"); 
 
    reallyBad = new JRadioButton("Really Bad"); 
 
    bad = new JRadioButton("Bad"); 
 
    good = new JRadioButton("Good"); 
 
    reallyGood = new JRadioButton("Really Good"); 
 
    lblReadyCheck = new JLabel(""); 
 

 
    finalSurvey = new ButtonGroup(); 
 
    finalSurvey.add(reallyBad); 
 
    finalSurvey.add(bad); 
 
    finalSurvey.add(good); 
 
    finalSurvey.add(reallyGood); 
 

 

 

 
    //Declare Audio 
 
    /*URL ebob = JavaMemoryGame_Final.class.getResource (""); 
 
    clap = Applet.newAudioClip (ebob); 
 
    URL bob = JavaMemoryGame_Final.class.getResource ("yes-1.wav"); 
 
    yess = Applet.newAudioClip (bob); 
 
    URL tom = JavaMemoryGame_Final.class.getResource ("no-6.wav"); 
 
    noo = Applet.newAudioClip (tom);*/ 
 

 
    //set up radio buttons 
 
    finalSurvey = new ButtonGroup(); 
 
    finalSurvey.add(reallyBad); 
 
    finalSurvey.add(bad); 
 
    finalSurvey.add(good); 
 
    finalSurvey.add(reallyGood); 
 

 
    //Set Up List Model 
 
    listModel = new DefaultListModel(); 
 
    listModel.addElement("10"); 
 
    listModel.addElement("15"); 
 
    listModel.addElement("30"); 
 

 
    //Set Up List 
 
    difficulty = new JList(listModel); 
 
    difficulty.setVisibleRowCount(1); 
 
    JScrollPane listScroll = new JScrollPane(difficulty); 
 

 

 

 
    for (int x = 0; x <= 11; x++) { 
 
     buttonArray[x] = new JButton(""); 
 
     buttonArray[x].setBackground(Color.orange); 
 
    } 
 

 

 
    ButtonHandler onClick = new ButtonHandler(); 
 
    btnStart.addActionListener(onClick); 
 
    for (int y = 0; y <= 11; y++) { 
 
     buttonArray[y].addActionListener(onClick); 
 
    } 
 

 

 

 
    JPanel mainStart = new JPanel(new BorderLayout()); 
 
    mainStart.setBackground(Color.orange); 
 
    mainStart.setForeground(Color.orange); 
 
    JPanel scoreStuffs = new JPanel(new GridLayout(1, 2)); 
 
    JPanel mainContent = new JPanel(new GridLayout(2, 2)); 
 
    mainContent.setBackground(Color.orange); 
 
    mainStart.setForeground(Color.orange); 
 
    JPanel gameBoard = new JPanel(new GridLayout(2, 6)); 
 
    gameBoard.setBackground(Color.orange); 
 
    JPanel gameContent = new JPanel(new GridLayout(1, 2)); 
 
    JPanel mainGame = new JPanel(new BorderLayout()); 
 
    mainGame.setBackground(Color.orange); 
 
    JPanel buttonScore = new JPanel(new GridLayout(3, 1)); 
 
    buttonScore.setBackground(Color.orange); 
 
    JPanel feedbackPanel = new JPanel(new BorderLayout()); 
 
    feedbackPanel.setForeground(Color.blue); 
 

 

 

 
    //Seperate Panels 
 
    mainContent.add(lblPrompt1); 
 
    mainContent.add(lblPrompt2); 
 
    mainContent.add(nameEnter); 
 
    mainContent.add(listScroll); 
 

 
    //Score Stuff for main Panel 
 
    scoreStuffs.add(scoreOutput); 
 
    scoreStuffs.add(btnStart); 
 

 

 
    //Main Welcome PAnel 
 
    mainStart.add(lblInstruct, BorderLayout.NORTH); 
 
    mainStart.add(mainContent, BorderLayout.CENTER); 
 
    mainStart.add(scoreStuffs, BorderLayout.SOUTH); 
 

 

 
    //GAme Board 
 
    gameContent.add(btnStart); 
 
    gameContent.add(scoreOutput); 
 
    gameBoard.add(buttonArray[0]); 
 
    gameBoard.add(buttonArray[1]); 
 
    gameBoard.add(buttonArray[2]); 
 
    gameBoard.add(buttonArray[3]); 
 
    gameBoard.add(buttonArray[4]); 
 
    gameBoard.add(buttonArray[5]); 
 
    gameBoard.add(buttonArray[6]); 
 
    gameBoard.add(buttonArray[7]); 
 
    gameBoard.add(buttonArray[8]); 
 
    gameBoard.add(buttonArray[9]); 
 
    gameBoard.add(buttonArray[10]); 
 
    gameBoard.add(buttonArray[11]); 
 

 

 
    mainGame.add(gameBoard, BorderLayout.CENTER); 
 
    mainGame.add(gameContent, BorderLayout.PAGE_END); 
 

 

 

 
    Container contentPane = start.getContentPane(); 
 
    contentPane.add(mainStart); 
 
    Container contentPane1 = questions.getContentPane(); 
 
    contentPane1.add(mainGame); 
 
    Container contentPane2 = survey.getContentPane(); 
 
    contentPane2.add(feedbackPanel); 
 
    start.setSize(600, 450); 
 
    start.setVisible(true); 
 
    questions.setSize(500, 250); 
 
    questions.setVisible(true); 
 
    survey.setSize(600, 450); 
 
    survey.setVisible(true); 
 

 

 

 
    } 
 

 

 

 

 
    private static class ButtonHandler implements ActionListener { 
 
    public void actionPerformed(ActionEvent e) { 
 
     String textFieldValue = nameEnter.getText(); 
 
     int index = difficulty.getSelectedIndex(); 
 
     int selected = difficulty.getSelectedValue().toInt(); 
 
     int check = 0; 
 

 
     while (check == 0) { 
 
     if (e.getSource() == ("Enter") && textFieldValue.length() != 0 && index > 0) { 
 
      lblPrompt1.setText("Thank You!"); 
 
      lblPrompt2.setText("Thank You!"); 
 
      btnStart.setText("Start?"); 
 
      check = check + 1; 
 
     } else if (e.getSource() == ("Enter") && textFieldValue.length() == 0) { 
 
      lblPrompt1.setText("Enter first name before continuing!"); 
 
      btnStart.setText("Check"); 
 
     } 
 
     } 
 

 
     if (e.getSource() == ("Start?")) { 
 
     start.setVisible(false); 
 
     questions.setVisible(true); 
 

 
     } 
 

 

 

 

 

 
    } 
 
    } 
 

 

 
    public void startTask() { 
 
    timer.schedule(new PeriodicTask(), 0); 
 
    } 
 

 

 

 
    private class PeriodicTask extends TimerTask {@ 
 
    Override 
 
    public void run() { 
 
     System.out.println(System.currentTimeMillis() + " Running"); 
 

 
     /* replace with the actual task */ 
 
     try { 
 
     Thread.sleep(15 * 1000); 
 
     } catch (InterruptedException e) { 
 
     e.printStackTrace(); 
 
     } 
 
     /* end task processing */ 
 

 
     System.out.println(System.currentTimeMillis() + " Scheduling 10 seconds from now"); 
 
     timer.schedule(new PeriodicTask(), 10 * 1000); 
 
    } 
 
    } 
 

 

 

 
    public static void main(String[] args) { 
 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 
 
      public void run() { 
 
      guiApp(); 
 
      } 
 
     } 
 

 

 
    ); 
 

 

 
    } // main method 
 
} // TryTryTryAgain class

Antwort

0

Verwendung java.awt.event.ActionListener.

import java.awt.event.*; 
Timer t = new Timer(10, //will run every 10 ms 
        new Listener()); 
t.start(); 

private class Listener implements ActionListener { 
    @Override 
    public void actionPerformed(ActionEvent e){ 
     //Code here will execute every (10) ms. 
    } 
} 
+0

Wie würde ich die Listener-Klasse verwenden, um das Layout des Rahmens zu ändern, wenn es von der Button-Handler-Methode aufgerufen wurde. Zum Beispiel wurde auf eine Schaltfläche geklickt, der Button-Handler wurde benachrichtigt, und jetzt möchte ich der Listener-Klasse mitteilen, dass sie ihren Code einmal ausführen soll. Wie würde ich darauf verweisen? – Toni

+0

Inside actionPerformed(), rufen Sie eine andere Methode an anderer Stelle in Ihrem Programm auf. Dann, wenn die Taste gedrückt wird, rufen Sie dieselbe Methode in Ihrem Handler auf. – RobotKarel314

0

Ich glaube, dass es einige Verwirrung gibt. Die Timer-Klasse erstellt einen neuen Thread und führt Tasks in diesem Thread so aus, dass sie entweder zu einem bestimmten Zeitpunkt in der Zukunft ausgeführt werden oder um den Task wiederholt in einem bestimmten Intervall auszuführen. Der folgende Code beschreibt eine Swing-Klasse, die einen roten Punkt im Abstand von zwei Sekunden verschiebt. Die Thread.sleep-Methode bewirkt, dass der Thread, in dem sie enthalten ist, einen bestimmten Zeitraum wartet. (Der Schlaf kann durch verschiedene Ereignisse unterbrochen werden.) Ihr erster Gebrauch eines Timers ist wirklich ein Dummy, da die Null, die für die Verzögerung verwendet wird, bedeutet, dass der Task ohne Verzögerung ausgeführt wird.

Ihre PeriodicTask-Klasse druckt eine Nachricht, wartet fünfzehn Sekunden, druckt eine Nachricht, plant eine Wiederholung der Aufgabe 10 Sekunden später und beendet dann.

package bradleyross.swing; 
import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.FlowLayout; 
import java.awt.event.ActionListener; 
import java.awt.event.ActionEvent; 
import java.awt.event.KeyListener; 
import java.lang.reflect.InvocationTargetException; 
import java.awt.event.KeyEvent; 
import java.awt.Graphics; 
import javax.swing.BorderFactory; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.JButton; 
import javax.swing.SwingUtilities; 
import java.util.Random; 
import java.util.Timer; 
import java.util.TimerTask; 
/** 
* This Swing demo creates a JPanel component and randomly 
* moves a red dot within the panel when triggered by a 
* timer. 
* 
* @author Bradley Ross 
* 
*/ 
public class SwingTimer implements Runnable{ 
    protected JFrame mainFrame; 
    protected FlowLayout layout; 
    protected MyPanel panel; 
    protected int xPos = 0; 
    protected int yPos = 0; 
    protected Random random = new Random(); 
    protected Timer timer = new Timer(); 
    public void run() { 
     buildFrame(); 
    } 
    /** 
    * Action listener for this application. 
    * @author Bradley Ross 
    * 
    */ 
    protected class Listener1 implements ActionListener { 

     public void actionPerformed(ActionEvent e) { 
      System.out.println("Action " + e.getActionCommand()); 
     } 

    } 
    /** 
    * Key listener for this application. 
    * @author Bradley Ross 
    * 
    */ 
    protected class Listener2 implements KeyListener { 
     /** 
     * Action when key event is detected. 
     * @param e key event 
     */ 
     public void keyTyped(KeyEvent e) { 
      System.out.println("Keystroke received " + e.getKeyChar()); 
     } 
     public void keyPressed(KeyEvent e) { ; } 
     public void keyReleased(KeyEvent e) { ; } 

    } 
    /** 
    * This subclass of JPanel repaints the 
    * the dot using {@link SwingTimer#xPos} and 
    * {@link SwingTimer#yPos}. 
    * 
    * @author Bradley Ross 
    * 
    */ 
    @SuppressWarnings("serial") 
    public class MyPanel extends JPanel { 
     public void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      g.fillOval(xPos, yPos, 5, 5); 
     } 
    } 
    /** 
    * Executed each time the timer triggers an event. 
    * 
    * <p>It randomly repositions the dot within the 
    * panel.</p> 
    * @author Bradley Ross 
    * 
    */ 
    public class Motion extends TimerTask { 
     public void run() { 
      xPos = random.nextInt(300); 
      yPos = random.nextInt(300); 
      panel.repaint(); 
     } 
    } 
    public void buildFrame() { 
     xPos = random.nextInt(300); 
     yPos = random.nextInt(300); 
     KeyListener listener2 = new Listener2(); 
     ActionListener listener1 = new Listener1(); 
     mainFrame = new JFrame(); 
     layout = new FlowLayout(FlowLayout.LEADING); 
     mainFrame.setLayout(layout); 
     mainFrame.addKeyListener(listener2); 
     JButton first = new JButton("First"); 
     first.setActionCommand("first"); 
     first.addActionListener(listener1); 
     first.addKeyListener(listener2); 
     first.setFocusable(false); 
     mainFrame.add(first); 
     mainFrame.setFocusable(true); 
     panel = new MyPanel(); 
     panel.setBorder(BorderFactory.createLineBorder(Color.black)); 
     panel.setPreferredSize(new Dimension(300,300)); 
     panel.setForeground(Color.red); 
     panel.addKeyListener(listener2); 
     panel.repaint(); 
     timer.scheduleAtFixedRate(new Motion(), 0 , 2000); 
     mainFrame.add(panel); 
     mainFrame.setSize(500, 500); 
     mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     mainFrame.setVisible(true); 
    } 
    /** 
    * Main driver. 
    * @param args not used in this example 
    */ 
    public static void main(String[] args) { 
     try { 
      SwingUtilities.invokeAndWait(new SwingTimer()); 
     } catch (InvocationTargetException e) { 
      e.printStackTrace(); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 
}