I need to make an image bounce on the screen. I am trying to do this by shifting the image up 5 units, then taking a one second break, then shifting another 5 units up, etc. I am trying to shift up 5 times and then shifting down 5 times, with a one second break between each shift. I need help making the timer for one second so it acts like a break between each shift. I need to write the time() method.
public void moveIt(KeyEvent evt) throws InterruptedException {
switch (evt.getKeyCode()) {
case KeyEvent.VK_DOWN:
myY += 0;
break;
case KeyEvent.VK_UP:
for (int i = 1; i <= 10; i++) {
if (i <= 5) {
bounceUp();
} else {
bounceDown();
}
time();
}
break;
case KeyEvent.VK_LEFT:
myX -= 5;
break;
case KeyEvent.VK_RIGHT:
myX += 5;
break;
}
repaint();
}
Timer timer = new Timer();
public void bounceUp() throws InterruptedException {
myY -= 10;
}
public void bounceDown() throws InterruptedException {
myY += 10;
}
public void time() {
}
Try this:
try{
Thread.sleep(1000);
}catch(InterruptedException e) {
}
TimerTask task = new TimerTask()
{
#Override
public void run()
{
time();//executed each second
}
}
timer.schedule(TimerTask task,1000,1000)
That should help
Welcome to SO!
Try using the schedule in Timer, like this:
Timer timer = new Timer();
timer.schedule(new YourClass(), 0, 1000);
Also, here's a great answer on the same issue:
https://stackoverflow.com/a/12908477/10713658
Related
I'm trying to make an action "stretch" over a certain period of time, being 1 second.
public static int i = 0;
public static void click() {
Robot robot;
try {
robot = new Robot();
for (i = i; i < cps; i++) {
robot.mousePress(InputEvent.BUTTON1_MASK);
Random rn = new Random();
int range = cps - 10 + 1;
int randomNum = rn.nextInt(range) + 10;
robot.delay(randomNum);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
i++;
}
if (i == cps) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i = 0;
}
} catch (AWTException e) {
e.printStackTrace();
}
}
As you can see, this is the code for a "simple" auto clicker.
It runs within this timer.
public static void getClick() {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
while (enabled) {
click();
}
}
}, 1, 1);
}
Is it in any way possible to make this action "stretch" it's action to 1 second. I really don't want it to click 12 times (Example), and then pause for 1 second. It'd be way nicer if these 12 clicks were "stretched" over that 1 second.
Is it possible anyone can help me?
You could just let it sleeps for 1000ms/cps. If the user set cps=10 then 10 Thread.sleep(1000/cps)would let it click ten times in one sec. With cps=0.5 it would click once in two seconds.
(with a little discrepancy, because your code needs time to execute). And you should not create your random object in your loop.
Random rn = new Random();
while(true) {
robot.mousePress(InputEvent.BUTTON1_MASK);
int range = cps - 10 + 1;
int randomNum = rn.nextInt(range) + 10;
robot.delay(randomNum);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
i++;
try {
Thread.sleep(1000/cps);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Ok so I have created a game and it works perfectly, except I don't want the player to win after just one defeat I want him to have to kill 10 enemies well I created my spawnmore method and I know the problem I just don't know how to fix it, in my if statement I have it saying if(dead < 10) then do my stuff, when I only want it to do it once every time dead increments one if you get what I mean here's my method thanks
public void spawnMore(){
int delay = 1000;
Timer time = new Timer(delay, new ActionListener(){
public void actionPerformed(ActionEvent e){
if(WizardCells[BadGuy.getx()][BadGuy.gety()].getIcon() != null){
return;
}
if(WizardCells[BadGuy.getx()][BadGuy.gety()].getIcon() == null){
dead += 1;
}
if(dead < 10){
int where = (int)(10 + Math.random() *9);
BadGuy.spawnEnemy(where, where);
move();
}
}
});
time.start();
}
If I understand you correctly, you could just move the if statement inside the previous if statement:
public void spawnMore(){
int delay = 1000;
Timer time = new Timer(delay, new ActionListener(){
public void actionPerformed(ActionEvent e){
if(WizardCells[BadGuy.getx()][BadGuy.gety()].getIcon() != null){
return;
}
if(WizardCells[BadGuy.getx()][BadGuy.gety()].getIcon() == null){
dead += 1;
if(dead < 10){
int where = (int)(10 + Math.random() *9);
BadGuy.spawnEnemy(where, where);
move();
}
}
}
});
time.start();
}
I have the following CountDownTimer that helps me to set a button visible every 490 ms 30 seconds long.
Is it possible to say that the first 10 seconds the "tick" should be for example 1000ms, the next 10 seconds 700 ms and the last 10 seconds 490ms ?
new CountDownTimer(30000, 490) {
#Override
public void onTick(long millisUntilFinished) {
for(int i = 0; i< arr.size(); i++){
Button aga = arr.get(i);
if(aga.getVisibility() == View.VISIBLE){
aga.setVisibility(View.GONE);
}
}
int zufall = (int) (Math.random()*23);
setNextButton(arr.get(zufall));
}
Hope this will helpful.
public void countDown(long time) {
if (time == 490) {
return;
}
new CountDownTimer(10000, time) {
public void onTick(long millisUntilFinished) {
// Do whatever you want
}
public void onFinish() {
countDown(nextTime); // nextTime can be 700, 100, ... It's up to you. (Your rule). :">
}
}.start();
}
Aside from launching new timers at those intervals to handle the new requirement, your best bet would just be to find a common divisor and set that as your interval, then use a switch with modulus to act at your desired times.
Timer mTimer; // Global
public void countDownTimerCaller()
{
static int count = 0;
int time;
switch(count)
{
case 0:
time = 1000;
break;
case 1:
time = 700;
break;
case 2:
time = 490;
break;
default:
mTimer.cancel(); // stop timer
return;
}
new CountDownTimer(10000, time) {
#Override
public void onTick(long millisUntilFinished) {
for(int i = 0; i< arr.size(); i++){
Button aga = arr.get(i);
if(aga.getVisibility() == View.VISIBLE){
aga.setVisibility(View.GONE);
}
}
int zufall = (int) (Math.random()*23);
setNextButton(arr.get(zufall));
}
}
count++;
}
mTimer = new Timer().schedule(countDownTimerCaller, 10000); // call from where ever you created CountDownTimer instance
I am working on an app that counts the number of questions marks in a few paragraphs of text.
After the scanning is done (which takes no time at all) I would love to have the total presented after the number goes from 0 to TOTAL. So, for 10: 0,1,2,3,4,5,6,7,8,9 10 and then STOP.
I have tried a couple of different techniques:
TextView sentScore = (TextView) findViewById(R.id.sentScore);
long freezeTime = SystemClock.uptimeMillis();
for (int i = 0; i < sent; i++) {
if ((SystemClock.uptimeMillis() - freezeTime) > 500) {
sentScore.setText(sent.toString());
}
}
Also I tried this:
for (int i = 0; i < sent; i++) {
// try {
Thread.sleep(500);
} catch (InterruptedException ie) {
sentScore.setText(i.toString());
}
}
I am sure these are both completely amateur attempts. Any help would be much-appreciated.
Thanks,
Richard
I've used a more conventional Android-style animation for this:
ValueAnimator animator = new ValueAnimator();
animator.setObjectValues(0, count);
animator.addUpdateListener(new AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
view.setText(String.valueOf(animation.getAnimatedValue()));
}
});
animator.setEvaluator(new TypeEvaluator<Integer>() {
public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
return Math.round(startValue + (endValue - startValue) * fraction);
}
});
animator.setDuration(1000);
animator.start();
You can play with the 0 and count values to make the counter go from any number to any number, and play with the 1000 to set the duration of the entire animation.
Note that this supports Android API level 11 and above, but you can use the awesome nineoldandroids project to make it backward compatible easily.
Try this:
private int counter = 0;
private int total = 30; // the total number
//...
//when you want to start the counting start the thread bellow.
new Thread(new Runnable() {
public void run() {
while (counter < total) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t.post(new Runnable() {
public void run() {
t.setText("" + counter);
}
});
counter++;
}
}
}).start();
The question is very old, but I am posting this so that it would help someone else.
I have used these 2 amazing libraries.
Try them
https://github.com/MasayukiSuda/CountAnimationTextView
Or
2. https://github.com/robinhood/ticker
Hope this helps :) Happy Coding!!!
Use TextSitcher
for the best effects. It will transform the text softly.
When coming to the change of the text use the below Code.
> int number = 0;
> Timer obj = new Timer();
> TimerTask tt = new TimerTask() {
> #Override public void run() {
> // TODO Auto-generated method stub
> textView.setText(number++);
> if(number < score)
> obj.schedule(tt, 200); } };
> obj.schedule(tt, 200);
Use a worker thread to do the waiting and update your UI thread.
You could use an AsyncTask, though it might be an overkill for this job. If you use this, In the doInBackground() loop over the number of sleep periods and after every sleep period, update the count in the UIthread.
There you go! Slukain just gave you the working code :P
Maybe try changing the for loop to something like:
int count = 0;
while (count != sent) {
if ((SystemClock.uptimeMillis() - freezeTime) > 500) {
count++;
sentScore.setText("" + count);
freezeTime = SystemClock.uptimeMillis();
}
}
Hi I want to run code over a time period. For example i would like my code to do something like this.
for(every 5 minutes until i say to stop)
automatically read in new value for x
automatically read in new value for y
if (x==y)
//do something
if (x!=y)
//do something else
Timer is what you need.
Naive version. You might consider Timer or the quartz scheduler instead.
while (!done) {
try {
Thread.sleep(5 * 60 * 1000);
x = readX();
y = readY();
if (x == y) {
} else {
}
} catch(InterruptedException ie) {
}
}
System.currentTimeMillis(); Returns you the system time in milliseconds, you can use that.
but first, you need some sort of loop.
This is an alternative to Timer 's
public static final int SECONDS = 1000;
public static final int MINUTES = 60 * SECONDS;
boolean quit = false; //Used to quit when you want to..
long startTime = System.currentTimeMillis();
while (!quit) {
if (System.currentTimeMillis() >= (startTime + (long)5*MINUTES)) {
//automatically read in new value for x
//automatically read in new value for y
if (x==y) {
//do something
} else {
//do something else
}
startTime = System.currentTimeMillis(); //reset the timer for the next 5 minutes
}
}
How about:
Runnable runnable = new Runnable() {
public void run() {
// do your processing here
}
};
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnable, 0, 5, TimeUnit.MINUTES);
Call service.shutdown() when you want to stop.