如何重新安排/重拍计时器?

时间:2015-09-19 04:48:53

标签: java timer schedule timertask

我尝试过Timer和TimerTask,但他们没有工作。它只是at com.dankrushen.mojangservicechecker.MojangServiceChecker.<init>(MojangServiceChecker.java:107),这显然意味着第107行出现错误。该行是激活计时器的行。我不知道为什么它会给出错误,但这里的代码是没有时间的,有没有可能的方法可以在其中添加计时器?只是为了让你知道我是一个平庸的编码员,但这是我尝试的第一个gui。

package com.dankrushen.mojangservicechecker;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.TimerTask;

import javax.swing.JSlider;
import javax.swing.JLabel;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;

public class MojangServiceChecker extends TimerTask {

    private JFrame frmMinecraftServiceChecker;

    /**
     * Launch the application.
     */
    int refreshInt;
    String timeSetting;
    String settings;
    double timesOpened = 0;
    JLabel status = new JLabel();
    static ClassExecutingTask executingTask = new ClassExecutingTask();
    public String refreshStatus() {
        RefreshStatus cbeta = new RefreshStatus();
        String returned = cbeta.refreshStatus();  //?
        return returned;
    }
    public int readSettings(){
        int Number;
        File file = new File("MSC-Settings.txt");
        if(!file.exists()){
            System.out.print("\nCreating file...");
            try {
                file.createNewFile();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            if(!file.exists()){
                System.out.print("\nFailed to create file.");
            }
            else{
                System.out.print("\nCreated file successfully!");
                System.out.print("\nTrying to write to file...\n");
                try {
                    PrintWriter out;
                    out = new PrintWriter("MSC-Settings.txt");
                    out.println("10");
                    out.close();
                } catch (FileNotFoundException e2) {
                    e2.printStackTrace();
                    System.out.print("\nGiving up writing to file.");
                }
            }
        }
        try(BufferedReader br = new BufferedReader(new FileReader("MSC-Settings.txt"))) {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            String everything = sb.toString();
            everything = everything.replace("\uFEFF", "");
            double everything2 = Double.parseDouble(everything);
            Number = (int) everything2;
            return Number;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 10;
    }

    public static void main(String[] args) {
        executingTask.start();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MojangServiceChecker window = new MojangServiceChecker();
                    window.frmMinecraftServiceChecker.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public MojangServiceChecker() {
        initialize();
    }
    private void screen2() throws FileNotFoundException, IOException {
        frmMinecraftServiceChecker = new JFrame();
        frmMinecraftServiceChecker.setTitle("Settings");
        frmMinecraftServiceChecker.setResizable(false);
        frmMinecraftServiceChecker.setBounds(100, 100, 450, 300);
        frmMinecraftServiceChecker.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frmMinecraftServiceChecker.getContentPane().setLayout(null);
        frmMinecraftServiceChecker.setVisible (true);

        final JLabel lblNewLabel = new JLabel("Current Setting: " + "10" + " Seconds");
        lblNewLabel.setBounds(14, 42, 173, 14);
        frmMinecraftServiceChecker.getContentPane().add(lblNewLabel);

        final JSlider slider = new JSlider();
        slider.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent arg0) {
                refreshInt = slider.getValue();
                if (refreshInt < 2){
                    timeSetting = " Second";
                }
                else timeSetting = " Seconds";
                lblNewLabel.setText("Current Setting: " + refreshInt + timeSetting);
            }
        });
        slider.setValue(readSettings());
        slider.setMinimum(1);
        slider.setMaximum(120);
        slider.setBounds(10, 11, 241, 20);
        frmMinecraftServiceChecker.getContentPane().add(slider);

        JLabel lblRefreshInterval = new JLabel("Refresh Interval in Seconds");
        lblRefreshInterval.setBounds(261, 11, 173, 20);
        frmMinecraftServiceChecker.getContentPane().add(lblRefreshInterval);

        JButton btnClose = new JButton("Cancel");
        btnClose.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                frmMinecraftServiceChecker.setVisible (false);
                initialize();
            }
        });
        btnClose.setBounds(180, 238, 89, 23);
        frmMinecraftServiceChecker.getContentPane().add(btnClose);
        frmMinecraftServiceChecker.setVisible (true);

        JButton btnApply = new JButton("Apply");
        btnApply.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {
                    PrintWriter out;
                    System.out.print("\nWriting to settings file.");
                    out = new PrintWriter("MSC-Settings.txt");
                    out.println(refreshInt);
                    out.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    System.out.print("\nCreating file...");
                    File file = new File("MSC-Settings.txt");
                    try {
                        file.createNewFile();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    if(!file.exists()){
                        System.out.print("\nFailed to create file.");
                    }
                    else{
                        System.out.print("\nCreated file successfully!");
                        System.out.print("\nTrying to write to file again...");
                        try {
                            PrintWriter out;
                            out = new PrintWriter("MSC-Settings.txt");
                            out.println(refreshInt);
                            out.close();
                        } catch (FileNotFoundException e2) {
                            e2.printStackTrace();
                            System.out.print("\nGiving up writing to file.");
                        }
                    }
                }
                frmMinecraftServiceChecker.setVisible (false);
                executingTask.start();
                initialize();
            }
        });
        btnApply.setBounds(268, 238, 89, 23);
        frmMinecraftServiceChecker.getContentPane().add(btnApply);

        JButton btnReset = new JButton("Reset");
        btnReset.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                slider.setValue(10);
            }
        });
        btnReset.setBounds(92, 238, 89, 23);
        frmMinecraftServiceChecker.getContentPane().add(btnReset);
    }
    /**
     * Initialize the contents of the frame.
     */
    public void setNames(String namestring){
    }
    private void initialize() {
        frmMinecraftServiceChecker = new JFrame();
        frmMinecraftServiceChecker.setTitle("Minecraft Service Checker");
        frmMinecraftServiceChecker.setResizable(false);
        frmMinecraftServiceChecker.setBounds(100, 100, 450, 300);
        frmMinecraftServiceChecker.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmMinecraftServiceChecker.getContentPane().setLayout(null);
        frmMinecraftServiceChecker.setVisible (true);
        if(timesOpened < 3){
            frmMinecraftServiceChecker.setVisible (false);
            timesOpened = timesOpened+1;
        }
        else frmMinecraftServiceChecker.setVisible (true);
        JButton btnNewButton = new JButton("Settings");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                frmMinecraftServiceChecker.setVisible (false);
                try {
                    screen2();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        btnNewButton.setBounds(180, 238, 89, 23);
        frmMinecraftServiceChecker.getContentPane().add(btnNewButton);
        status.setText(refreshStatus());
        status.setBounds(10, 11, 424, 144);
        frmMinecraftServiceChecker.getContentPane().add(status);

        JButton temp = new JButton("Temp");
        temp.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                frmMinecraftServiceChecker.setVisible (false);
            }
        });
        temp.setBounds(10, 238, 70, 23);
        frmMinecraftServiceChecker.getContentPane().add(temp);
    }
    public void run() {
        status.setText(refreshStatus());
    }
}

然后是第二节课:

package com.dankrushen.mojangservicechecker;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class RefreshStatus{

    String ResponseName;
    String v1;
    String v2;
    String v3;
    String v4;
    String v5;
    String v6;
    String v7;
    String v8;
    String v9;
    public String[] mojangStatus(){
        try {
            v1 = getStatus("\"minecraft.net\"");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            v2 = getStatus("\"session.minecraft.net\"");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            v3 = getStatus("\"account.mojang.com\"");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            v4 = getStatus("\"auth.mojang.com\"");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            v5 = getStatus("\"skins.minecraft.net\"");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            v6 = getStatus("\"authserver.mojang.com\"");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            v7 = getStatus("\"sessionserver.mojang.com\"");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            v8 = getStatus("\"api.mojang.com\"");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            v9 = getStatus("\"textures.minecraft.net\"");
        } catch (IOException e) {
            e.printStackTrace();
        }
        String[] all = new String[(9)];
        all[(0)] = v1;
        all[(1)] = v2;
        all[(2)] = v3;
        all[(3)] = v4;
        all[(4)] = v5;
        all[(5)] = v6;
        all[(6)] = v7;
        all[(7)] = v8;
        all[(8)] = v9;
        return all;
    }
    public String getStatus(String LookupName) throws IOException {
        URL url = new URL("http://status.mojang.com/check");
        BufferedReader in = new BufferedReader(
                new InputStreamReader(
                        url.openStream()));
        ResponseName = in.readLine();
        String FinalCheck = LookupName + ":\"green\"";
        if(ResponseName.contains(FinalCheck)) {
            return "<font color = \"008000\">This service is healthy.</font>";
        }
        FinalCheck = LookupName + ":\"yellow\"";
        if(ResponseName.contains(FinalCheck)) {
            return "<font color = \"FFD700\">This service is shaky.</font>";
        }
        FinalCheck = LookupName + ":\"red\"";
        if(ResponseName.contains(FinalCheck)) {
            return "<font color = \"FF0000\">This service is offline.</font>";
        }
        in.close();
        return "Unknown/No Response.";
    }

    public String refreshStatus(){
        String[] list = mojangStatus();
        String display = "<html>minecraft.net: " + list[(0)] + "<br/>session.minecraft.net: " + list[(1)] + "<br/>account.mojang.com: " + list[(2)] + "<br/>auth.mojang.com: " + list[(3)] + "<br/>skins.minecraft.net: " + list[(4)] + "<br/>authserver.mojang.com: " + list[(5)] + "<br/>sessionserver.mojang.com: " + list[(6)] + "<br/>api.mojang.com: " + list[(7)] + "<br/>textures.minecraft.net: " + list[(8)] + "</html>";
        System.out.print("\n" + display);
        return display;
    }
}

然后是第三节课:

package com.dankrushen.mojangservicechecker;

import java.util.Date;
import java.util.Timer;

public class ClassExecutingTask {

    public int readSettings() {
        MojangServiceChecker cbeta = new MojangServiceChecker();
        int returnint = cbeta.readSettings();  //?
        return returnint;
    }
    long delay = readSettings()*1000; // delay in milliseconds
    MojangServiceChecker task = new MojangServiceChecker();
    Timer timer = new Timer("timer");

    public void start() {
    timer.cancel();
    timer = new Timer("timer");
    delay = readSettings()*1000; // delay in milliseconds
    Date executionDate = new Date(); // no params = now
    timer.scheduleAtFixedRate(task, executionDate, delay);
    }
}

编辑:我已经开始工作,但我无法重新安排计时器。我知道它是因为取消使得它无法重启以及打开4个窗口而不是1,我不知道为什么会发生这种情况,但我还添加了一个新的计时器。我也知道有一个更新的东西,而不是使用Timer,但我无论如何使用它都无论如何使用它,无论我看多少东西ScheduledThreadPoolExecutor。但它给了我错误(PS我也更新了类文件!):

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Task already scheduled or cancelled
    at java.util.Timer.sched(Unknown Source)
    at java.util.Timer.schedule(Unknown Source)
    at com.dankrushen.mojangservicechecker.ClassExecutingTask.start(ClassExecutingTask.java:22)
    at com.dankrushen.mojangservicechecker.MojangServiceChecker$4.actionPerformed(MojangServiceChecker.java:191)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$300(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

2 个答案:

答案 0 :(得分:0)

您说Timer无效,但您没有提供代码,因此无法确定导致错误的原因。我将向您展示我的工作Timer的样子。

// Here's an action that will be called every timer event
public class MyTimerAction extends AbstractAction {

    // You may need a target here to access the actual
    // method you wish to invoke.
    // ...

    @Override
    public void actionPerformed(ActionEvent e) {
        // code to be performed
    }
}

// Here's the Timer class 
public class MyTimer extends Timer {

    // The action invoked by the timer.
    private MyTimerAction action;

    public MyTimer(int delay, ActionListener listener) {
        super(delay, listener);
        action = (MyTimerAction)listener;
        //...
    }
}

这应该适用于计时器。您必须进行适当的更改才能适用于您的方案。

答案 1 :(得分:0)

我想要一种非常容易和快速改变间隔的方法,而不是使用计时器,而不一定准确,但只是让它工作。所以我决定只创建一个新线程,并使用sleep并检查每次从配置之间的延迟应该是什么,为了进入配置屏幕,它将只是杀死线程并且每次都创建一个新线程。