Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

swing - Creating a Java Timer and a TimerTask?

I'm new to Java and I'm trying to set a simple timer, I'm familiar with set_interval, because of experience with JavaScript and ActionScript,

I'm not so familiar with classes yet so I get confused easily, I understand that I need to set a new Timer, and then set a TimerTask, but I don't get how exactly to do it even though I'm looking at the documentation right now..

So I created an Applet, and that's my init method:

public void init() {
    TimerTask myTask;
    Timer myTimer;
    myTimer.schedule(myTask,5000);
}

How do I actually set the task code? I wanted it to do something like

g.drawString("Display some text with changing variables here",10,10);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As told by many a wonderful Stackoverflow users, the right idea in here is to use the javax.swing.TImer. Here is one small code snippet for your help. Do ask any question, that is beyond your grasp, I will try to provide information likewise.

import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;

public class DrawStringWithTimer
{
    private final int WIDTH = 400;
    private final int HEIGHT = 300;
    private Timer timer;
    private int x;
    private int y;
    private int counter;
    private Random random;
    private String[] messages = {
                                    "Bingo, I am ON",
                                    "Can you believe this !!",
                                    "What else you thinking about ?",
                                    "Ahha, seems like you are confused now !!",
                                    "Lets Roll and Conquer :-)"
                                };
    private CustomPanel contentPane;

    private ActionListener timerAction = new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent ae)
        {
            if (counter == 5)
                counter = 0;
            /*
             * Creating random numbers where 
             * x will be equal to zero or 
             * less than WIDTH and y will be
             * equal to zero or less than HEIGHT.
             * And we getting the value of the
             * messages Array with counter variable
             * and passing this to setValues function,
             * so that it can trigger a repaint()
             * request, since the state of the 
             * object has changed now.
             */ 
            x = random.nextInt(WIDTH);
            y = random.nextInt(HEIGHT);
            contentPane.setValues(x, y, messages[counter]);
            counter++;
        }
    };

    public DrawStringWithTimer()
    {
        counter = 0;
        x = y = 10;
        random = new Random();
    }

    private void displayGUI()
    {
        JFrame frame = new JFrame("Drawing String Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        contentPane = new CustomPanel(WIDTH, HEIGHT);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
        /*
         * javax.swing.Timer is what you need
         * when dealing with Timer related
         * task when using Swing.
         * For more info visit the link
         * as specified by @trashgod, in the
         * comments.
         * Two arguments to the constructor
         * specify as the delay and the 
         * ActionListener associated with 
         * this Timer Object.
         */
        timer = new Timer(2000, timerAction);
        timer.start();
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new DrawStringWithTimer().displayGUI();
            }
        });
    }
}

class CustomPanel extends JPanel
{
    private final int GAP = 10;
    private int width;
    private int height;
    private int x;
    private int y;
    private String message = "";

    public CustomPanel(int w, int h)
    {
        width = w;
        height = h;

        setOpaque(true);
        setBackground(Color.WHITE);
        setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
    }

    public void setValues(int x, int y, String msg)
    {
        this.x = x;
        this.y = y;
        message = msg;

        /*
         * As the state of the variables will change,
         * repaint() will call the paintComponent()
         * method indirectly by Swing itself. 
         */
        repaint();
    }

    @Override
    public Dimension getPreferredSize()
    {
        return (new Dimension(width, height));
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        /*
         * Below line is used to draw the JPanel
         * in the usual Java way first.
         */
        super.paintComponent(g);
        /*
         * This line is used to draw the dynamic
         * String at the given location.
         */
        g.drawString(message, x, y);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...