java不要无限循环,Java,无限循环的替代?

I am making a program that shows cellular growth through an array. I have gotten it so when I press the start button, the array updates every 10 seconds in a while(true){} loop. The problem with that is I want to be able to stop the loop by pressing the pause button, but while in the loop, it wont let me use any of the controls. I need something other than a infinite loop in orer to refresh the frames.

I am a bit of a newbie, but I am in a java class at the moment. so I have some grasp of the language.

解决方案

What you need is use a Timer which changes the state of your component ( in this case the cellular growth ) and then call JComponent.repaint()

This timer can be cancelled to make the pause and then to restart it, you just create a new one:

So you could define the following two methods:

private Timer timer;

...

public void startPaiting() {

timer = new Timer();

timer.schedule( new TimerTask(){

public void run(){

changeState();

repaint();

}

},0, 10000 ); // 10 s.

}

public void pause(){

timer.cancel();

}

And then in your "Pause/Resume" button invoke this "pause/startPaiting" methods:

if( e.getActionCommand().equals("Pause")){

growPanel.pause();

setText("Resume");

} else {

growPanel.startPaiting();

setText("Pause");

}

Here's the complete source code to see it running:

import javax.swing.*;

import java.awt.Graphics;

import java.awt.Point;

import java.awt.event.*;

import java.util.Timer;

import java.util.TimerTask;

public class Grow {

public static void main( String [] args ) {

JFrame frame = new JFrame();

final GrowPanel growPanel = new GrowPanel();

frame.add( growPanel );

frame.add( new JPanel(){{

add( new JButton("Pause"){{

addActionListener( new ActionListener(){

public void actionPerformed( ActionEvent e ){

if( e.getActionCommand().equals("Pause")){

growPanel.pause();

setText("Resume");

} else {

growPanel.startPaiting();

setText("Pause");

}

}

});

}});}}, java.awt.BorderLayout.SOUTH );

frame.setSize( 400, 300 );

frame.setVisible( true );

}

}

class GrowPanel extends JComponent {

private int x;

private int y;

private Timer timer;

GrowPanel() {

x = 10;

y = 10;

startPaiting();

}

public void startPaiting() {

timer = new Timer();

timer.schedule( new TimerTask(){

public void run(){

changeState();

repaint();

}

},0, 100 ); // or 10000 which is 10 s.

}

public void pause(){

timer.cancel();

}

public void paintComponent( Graphics g ){

g.fillOval( x, y, 10, 10 );

}

private void changeState(){

x+=10;

if( x >= 400 ) {

y+=10;

x = 0;

}

if( y >= 300 ){

y = 10;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值