在Java Swing中停止计时器

时间:2014-09-11 07:57:17

标签: java swing timer actionlistener mouselistener

我刚开始使用Swing并使用Timer。我写的程序基本上上下移动一个矩形到屏幕上的特定点,我使用计时器让它运行缓慢而平稳。但是当我试图阻止它时我遇到了问题。以下是代码:

提升类改变矩形的位置:

 public void moveUp(int destination){
        speed++;
        if(speed>5){
            speed = 5;
        }
        System.out.println("Speed is: "+speed);
        yPos -= speed;
        if(yPos < destination){
            yPos = destination;
            isStop = true;
        }
        setPos(xPos, yPos);
    }

获得TimerMouseListener的课程:

this.addMouseListener(new MouseListener() {

        @Override
        public void mouseReleased(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mousePressed(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON1) {
                Timer timer = new Timer(100, new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        liftArray.get(0).moveUp(rowDisctance / 2);
                        repaint();
                    }
                });
                timer.start();
            }

        }

2 个答案:

答案 0 :(得分:3)

如果我确实理解你正在寻找这样的东西,你需要两个定时器来控制上下机制,timer1一个向下移动,timer2向上移动,反之亦然。你需要停止timer1然后在timer1里面你需要启动timer2,这里是下面的代码和动画。

enter image description here

添加字段

  Point rv;

在构造函数

中将初始位置设置为对话框(矩形)
 rv= rectangle.this.getLocation();

您的按钮操作已执行

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
     timer1.setInitialDelay(0);
     timer1.start();
     jTextArea1.append("Timer 1 Started Moving Down\n");
} 

复制粘贴这两个timer1和timer2就像java中的方法一样

    private Timer timer1 = new Timer(10, new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        rv.y++;



        if (rv.y == 500) {
            timer1.stop();
            jTextArea1.append("Timer 1 Stopped\n");
            jTextArea1.append("Timer 2 Started Moving Up\n");
            timer2.setInitialDelay(0);
            timer2.start();

        }

        rectangle.this.setLocation(rv.x , rv.y);
        rectangle.this.repaint();

    }
});



 private Timer timer2 = new Timer(5, new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
       rv.y--;

        if (rv.y == 200 ) {
            timer2.stop();
            jTextArea1.append("Timer 2 Stopped\n");
        }
          rectangle.this.setLocation(rv.x , rv.y);
         rectangle.this.repaint();
    }
});

答案 1 :(得分:0)

为了想象如何处理这个问题,我编写了一个小例子:

enter image description here

启动时,将创建两个矩形。当您在绘图区域上单击鼠标左键时,它们开始移动。

目的地线到达时,动作将停止。

逻辑取决于Rectangle类中的状态。当计时器事件处理程序运行时,检查每个矩形的状态,如果到达的所有矩形都具有isStopped状态,则计时器停止;

        public void mousePressed(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON1) {
                timer = new Timer(100, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        /** 
                         * Variable isStopped is used to track, if any 
                         * rectangle didn't reach the destination yet
                         */
                        boolean isStopped = true;

                        for(int i = 0; i < count; i++){
                            rectangles[i].moveUp(destination);
                            if (!rectangles[i].isStopped()) {
                                isStopped = false;
                            }
                        }
                        drawPanel.repaint();

                        /** 
                         * With all rectangles having arrived at destination, 
                         * the timer can be stopped
                         */
                        if (isStopped) {
                            timer.stop();
                        }
                    }
                });
                timer.start();
            }
        }

从Rectangle类中摘录 - 在这里你看,isStopped状态是如何处理的 - 内部是私有的isStop变量 - 可以使用isStopped getter检索。

/** 
 * Moves the rectangle up until destination is reached
 * speed is the amount of a single movement.
 */
public void moveUp(int destination) {
    if (speed < 5) {
        speed++;
    }

    y -= speed;

    if (y < destination) {
        y = destination;
        isStop = true;
    }
}

public boolean isStopped() {
    return isStop;
}

以下是整个计划:

主程序MovingRectangle ,创建绘图区域并提供控件:

package question;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class MovingRectangle extends JPanel {
    /**
     * The serial version uid.
     */
    private static final long serialVersionUID = 1L;

    private Rectangle[] rectangles = new Rectangle[10];
    private int count;
    private int destination;

    private JPanel controlPanel;
    private DrawingPanel drawPanel;
    private JButton stop;

    private Timer timer;

    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("Rectangles");
                frame.setContentPane(new MovingRectangle());
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    public MovingRectangle(){
        /** Imaginary horizontal line - the destination */
        destination = 200;

        /** Create the control panel for the left side containing the buttons */
        controlPanel = new JPanel();
        controlPanel.setPreferredSize(new Dimension(120, 400));

        /** Create the button */
        stop = new JButton("Stop");
        stop.addActionListener(new ButtonListener());
        controlPanel.add(stop);

        /** Create a hint how to start the movement. */
        JTextArea textHint = new JTextArea(5, 10);
        textHint.setEditable(true);
        textHint.setText("Please click on the drawing area to start the movement");
        textHint.setLineWrap(true);
        textHint.setWrapStyleWord(true);
        controlPanel.add(textHint);

        /** Add control panel to the main panel */
        add(controlPanel);

        /** Create the drawing area for the right side */
        drawPanel = new DrawingPanel();

        /** Add the drawing panel to the main panel */
        add(drawPanel);

        /** With a left mouse button click the timer can be started */
        drawPanel.addMouseListener(new MouseListener() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1) {
                    timer = new Timer(100, new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            /** 
                             * Variable isStopped is used to track, if any 
                             * rectangle didn't reach the destination yet
                             */
                            boolean isStopped = true;

                            for(int i = 0; i < count; i++){
                                rectangles[i].moveUp(destination);
                                if (!rectangles[i].isStopped()) {
                                    isStopped = false;
                                }
                            }
                            drawPanel.repaint();

                            /** 
                             * With all rectangles having arrived at destination, 
                             * the timer can be stopped
                             */
                            if (isStopped) {
                                timer.stop();
                            }
                        }
                    });
                    timer.start();
                }
            }

            @Override
            public void mouseReleased(MouseEvent arg0) {
            }

            @Override
            public void mouseClicked(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });

        /** Add two rectangles to the drawing area */
        addRectangle(100, 30, 0, 370, new Color(255, 0, 0));
        addRectangle(120, 50, 200, 350, new Color(0, 0, 255));
    }

    private void addRectangle(final int widthParam, final int heightParam, final int xBegin, final int yBegin, final Color color) {
        /** Add a new rectangle, if array not filled yet */
        if (count < rectangles.length) {
            rectangles[count] = new Rectangle(widthParam, heightParam, xBegin, yBegin, color);
            count++;
            drawPanel.repaint();
        }
    }

    /** This inner class is used to handle the button event. */
    private class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e){
            if (e.getSource() == stop){
                timer.stop();
            }
        }
    }

    /** This inner class provides the drawing panel */
    private class DrawingPanel extends JPanel{
       /** The serial version uid. */
        private static final long serialVersionUID = 1L;

        public DrawingPanel() {
            this.setPreferredSize(new Dimension(400, 400));
            setBackground(new Color(200, 220, 255));
        }

        public void paintComponent(Graphics g){
            super.paintComponent(g);

            /** Draw destination line */
            g.setColor(new Color(150, 150, 150));
            g.drawLine(0, destination, 400, destination);

            /** Draw rectangles */
            for(int i = 0; i < count; i++){
                rectangles[i].display(g);
            }
        }
    }
}

移动形状的矩形类

package question;

import java.awt.Color;
import java.awt.Graphics;

public class Rectangle {
    private int x, y, width, height;
    private Color color;
    private boolean isStop = false;
    private int speed = 0;

    public Rectangle(final int widthParam, final int heightParam, final int xBegin, final int yBegin, final Color colorParam) {
        width = widthParam;
        height = heightParam;
        this.x = xBegin;
        this.y = yBegin;
        this.color = colorParam; 
    }

    public void display(Graphics g){
        g.setColor(this.color);
        g.fillRect(this.x, this.y, this.width, this.height);
    }  

    /** 
     * Moves the rectangle up until destination is reached
     * speed is the amount of a single movement.
     */
    public void moveUp(int destination) {
        if (speed < 5) {
            speed++;
        }

        y -= speed;

        if (y < destination) {
            y = destination;
            isStop = true;
        }
    }

    public boolean isStopped() {
        return isStop;
    }
}