我刚开始使用 Swing 并使用 Timer
。我编写的程序基本上是将一个矩形上下移动到屏幕上的特定点,我使用计时器让它缓慢而平稳地运行。但是我在试图阻止它时遇到了问题。这是下面的代码:
提升类改变矩形的y位置:
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);
}
以及获得 Timer
和 MouseListener
的类:
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();
}
}
最佳答案
如果我没有正确理解你,你正在寻找这样的东西,你需要两个定时器来控制上下机制,timer1 一个向下移动,timer2 向上移动,反之亦然。你需要停止 timer1 然后在 timer1 里面你需要启动 timer2 ,下面是代码和动画。
添加您的字段
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");
}
在java中复制粘贴这两个timer1和timer2 like方法
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();
}
});
关于java - 在 Java Swing 中停止定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25782118/