Possible not to use timer - java

Hi everyone i would like to ask if is it possible not to use timer in Java netbeans to display on my JLabel all value of my variable "counter" using while loop. Here is my sample code.
int counter = 0;
while (counter < 10) {
lblDisplay.setText("Completed " + Integer.toString(counter));
try {
Thread.sleep(1000);
lblDisplay.setText("Completed " + Integer.toString(counter));
} catch (InterruptedException ex) {
Logger.getLogger(Increment.class.getName()).log(Level.SEVERE, null, ex);
}
counter++;
}
in using of system.out.println it was displayed but in my Label was not.

Yes it's possible to avoid using a Swing Timer to achieve this, but if you did this then:
You'd have to make sure that the loop and the Thread.sleep(...) were run in a background thread off of the Swing event thread. If you don't do this, you will freeze the event thread and thus freeze your GUI and render it useless.
And then you'd have to make sure that when you only make Swing calls from the background thread, you take pains to queue those calls onto the Swing event dispatch thread. If you don't do this, you will run the risk of causing occasional very hard to debug threading errors.
Because of the extra work involved and the risk of getting it wrong, you'll find that it is much simpler and safer to just use a Swing Timer. For instance your posted code looks like it's at grave risk of putting the entire GUI/application to sleep since it has both a while loop and a Thread.sleep(...) called without concern for threading.
For example, without a Timer, your code could look something like (caveat: code not compiled nor tested):
new Thread(new Runnable() {
public void run() {
int counter = 0;
while (counter < 10) {
lblDisplay.setText("Completed " + Integer.toString(counter));
try {
Thread.sleep(1000);
final int finalCounter = counter;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
lblDisplay.setText("Completed " + finalCounter);
}
});
} catch (InterruptedException ex) {
Logger.getLogger(Increment.class.getName()).log(Level.SEVERE, null, ex);
}
counter++;
}
}
}).start();
That's a bit more complicated than I like, while the Swing Timer could look like:
int delay = 1000;
new Timer(delay, new ActionListener() {
private int count = 0;
#Override
public void actionPerformed(ActionEvent e) {
if (count < 10) {
lblDisplay.setText("Completed " + counter);
} else {
((Timer) e.getSource()).stop(); // stop the Timer
}
counter++;
}
}).start();
Which is simpler and safer than the previous.

Related

CountDownLatch leads to disappearance of content in JFrame (JButtons, etc.) and comes back only when mouse overed

I am working on Deal or No Deal with a user interface. The first problem I ran into was how to wait for a button action to continue, and I used Count Down Latches and it worked perfectly. But whenever, I click a button, everything in my JFrame disappears and comes back when you mouse over, it all of a sudden reappears when I press another buttton (This never happened before I used Count Down Latches, and this also happens with Semaphores, etc.) I'll try to keep my code as relevant as possible.
public CountDownLatch cdl = new CountDownLatch(1);
pickFirst();
try {
cdl.await();
} catch (Exception E) {
}
while (banker.findCasesLeft() > 2) {
banker = new Banker(Main.f.values);
for (i = casesToPick; i >= 1; i--) {
cdl = new CountDownLatch(1);
pickCase();
picked = false;
try {
cdl.await();
} catch (Exception E) {
}
}
^^^ That was my class that deals with picking cases Below is class with actionlisteners
public void actionPerformed(ActionEvent ae) {
if (!Main.me.pickedFirst) {
Main.me.pickedCase = caseNo;
Main.f.log += "You picked to keep case " + caseNo + ".\n";
setText(caseNo + "\np");
Main.f.changeLog();
Main.me.pickedFirst = true;
Main.me.cdl.countDown();
} else {
int value = Main.me.values[caseNo-1];
Main.me.values[caseNo] = 0;
Main.f.values[getIndex(value)].setSelected(true);
Main.f.log += "You picked to get rid of case " + caseNo + ". It contained $" + value + ".\n";
Main.f.changeLog();
Main.me.picked = true;
Main.me.cdl.countDown();
}
setEnabled(false);
}
Note that the await() method of CountDownLatch "Causes the current thread to wait until the latch has counted down to zero." If that thread is the event dispatch thread, GUI updates will be blocked until the wait condition changes. In general, CountDownLatch is meant to allow separate threads to rendezvous; it should't be used to within the event dispatch thread. This complete example, which coordinates multiple SwingWorker instances, may help clarify the usage.

Java Synchronizing objects, wait and notify

I have a program that rolls dice, and uses a new thread to loop through in order to update the image and repaint. Here is my code:
public int roll()
{
new Thread(
new Runnable() {
public void run() {
synchronized(o) {
o.notify();
for (int i = 0; i < 10; i++) {
image = randomImage();
repaint();
try {
Thread.sleep(100);
}
catch(InterruptedException ex) {
System.out.println("InterruptedException caught");
}
}
}
}
}
).start();
synchronized(o) {
try {
o.wait();
}
catch(InterruptedException ex) {
System.out.println("InterruptedException caught");
}
}
return rolled;
}
In my other class, I have:
int rolled = dicePanel.roll();
label.setText("Rolled a + rolled");
The problem is that with the current code with synchronization, the dice images do not animate, but do return the correct int rolled. Without the synchronized code, the images will animate but the roll method will return a 0 as the int because it does not let the other thread finish.
Is there any way to have the image code loop through and repaint each time, but wait until the thread has finished to return the int rolled?
This looks like an overly complicated solution. You should certainly perform your dice rolling / image updating in thread other than the EDT, but you needn't split that task into two separate threads.
Just have one thread that fiddles with your dice images then when it's finished doing that, it can set the chosen dice value in your label (and presumably in your image too).
Put the o.notify(); to the end of the run() method. Btw. using notifyAll() should be preferred. Or you may find useful the Future object pattern. Here is an article about it http://www.vogella.com/articles/JavaConcurrency/article.html
Or if you are developing Swing application look to SwingWorker. However, SwingWorker is probably overkill for this task.
Wait&notify is quite low level api and there are many good abstraction in Java to work with concurrency.

Java Applet, game loop runs fine the first time, and then when reset, updates at half the speed

so for the game I'm creating I realized I mist have done something wrong with my gameLoop because the first time I play through my game it runs great, but the second time or anything after that, it slows down by about half. Even if I minimize the game (Because that stops the gameLoop, and then bringing it up again starts it back up) here is the gameLoop code:
public void gameLoop(){
new Thread(){
public void run() {
while(gameRunning){
try {
Thread.sleep(1000/60);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (tutorial){
updateBullet();
updatePlayer();
repaint();
} else {
updateEnemies();
updateBullet();
createEnemies();
updateParticles();
updatePlayer();
repaint();
}
}
repaint();
}
}.start();
}
I start it for the first time in the init() just with
gameLoop();
And then I also have:
public void stop(){
bg.stop();
gameRunning = false;
}
public void start(){
bg.start();
gameRunning = true;
gameLoop();
}
And finally the playerUpdate also stops the loop with (The Thread inside of player is to allow for some effects to finish after the player dies):
public void updatePlayer(){
if (player.isMovingLeft){
player.x-=3;
}
if (player.isMovingRight){
player.x+=3;
}
for (int j=0; j < enemies.size(); j++){
if (player.isAlive){
if (enemies.get(j).x+19 > player.x && enemies.get(j).x < player.x+40 && enemies.get(j).y > player.y && enemies.get(j).y < player.y+40) {
enemies.remove(j);
j--;
explode.setFramePosition(0);
explode.start();
for (int k = 0; k <21; k++){
addParticle(player.x+20,player.y+20,2);
}
new Thread(){
public void run() {
try {
Thread.sleep(2000);
gameRunning = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
player.isAlive = false;
break;
}
}
}
}
And then it is restarted with in the keyPressed event:
if (!gameRunning){
if (arg0.getKeyCode() == KeyEvent.VK_ENTER){
enemies.clear();
bullets.clear();
particles.clear();
score = 0;
player.x = 200;
player.isMovingLeft = false;
player.isMovingRight = false;
player.isAlive = (true);
gameRunning = true;
gameLoop();
}
}
So why is it that whenever the loop is stopped and started again, it runs at half the speed? Thanks!
It looks like you're starting a new thread for each gameloop; this means each time the gameloop runs, you've got another thread for the Java VM to handle. This is extremely inefficient, as eventually you'll have 1000 threads running, causing HUGE lag. Is there any way you could rewrite your code without threading there?
Also, what is this supposed to do?
try {
Thread.sleep(1000/60);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Why would you do 1000/60? A: Why not just use 16? B: It seems like you meant something else here, not sure what though
Also, what is the bg variable your reference in your start() and stop() methods?
It looks like you are trying to stop the thread by using the gameRunning boolean. If this is not volatile, then the game loop may not notice changes from the GUI thread that sets it to false and will run forever. Even if it is volatile, you have a race condition if start is called again before the game thread notices the stop command.
You should instead store a reference the the created thread and interrupt it in your stop method.
Also are all your update methods thread safe with respect to the paint method. updatePlayer doesn't look thread safe, and you don't know when paint will be called so it could happen at the same time as your update method. Even if the paint method doesn't write to the shared data, it could still see inconsistent data due to lack of a memory barrier.
I'd suggest doing all the updates in the GUI thread unless it is very slow and you need the multithreading. Look at using a Timer from Swing to to initiate your update logic.

Repaint() not being called in Thread

I have a jFrame that is implementing a poker game. I have a thread so that the computer opponents take time with their moves. I've tried to implement it so that the Thread waits when a human turn comes up. Before I even put a human player in, though, the frame doesn't call repaint(). I've used the debugger in Netbeans to check this: it does get to the line where the frame calls repaint(), but for some reason it doesn't actually do it. Here's the code:
public void run() {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < players.size(); j++) {
Card card = deck.draw();
players.get(i).addToHand(card);
output.append("Player " + players.get(i).getName() + " got a " + card + ".\n");
System.out.println("Player " + players.get(i).getName() + " got a " + card + ".\n");
}
}
while (true) {
if (!players.isEmpty() && players.get(0) instanceof HumanPlayer)
humansTurn = true;
if (humansTurn) {
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
}
}
} else if (humanMoveMade) {
playMove(humanMove, players.remove(0));
humanMoveMade = false;
}else {
//unrelated code, then:
debug.update();
repaint();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
}
}
}
Basically it's supposed to get to that else whenever the human player isn't making his or her move, and it does get to that repaint, but it never goes through for some reason. The window appears, but none of the components.
EDIT: I should also mention that the debug.update() method call before the repaint() is supposed to update information on another frame, but nothing is showing up in that window either...
I need to have this ready soon, so I really need some help with this. What is going on?
Ugh...sorry, false alarm. I had forgotten to check when this frame gets created. Turns out I had accidentally called the run() method instead of running the thread the way it normally is (I had tried to implement something different beforehand). After going back to making a new thread and calling start(), it works now.

Java Swing how can I make this counter work?

Everytime my counter reaches 4 I want it to play a beep sound and go back to '1' and again count up to 4 play the beep sound and so on.
I probably shouldn't place this in a label, because the counter doesnt run at all!
I don't get any errors but the label says; counter is 4 and doesnt count or anything.
Can you help me make this counter work properly? I also used printline but that
gave some errors too.
My code for the counter is this:
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label1.setVisible(true);
int counter = 1;
while(counter < 5 )
{
label1.setText("counter is " + counter);
counter = counter + 1 ;
}
counter = 1;
tk.beep();
}
});
Spawn a new thread to count, wait, and update the GUI.
You're doing all of this work in the Event Dispatch Thread, which is the only thread which updates the GUI. So when you set the text of the label, it doesn't get updated on the screen until the method returns and the Event Dispatch Thread handles the repaint operation.
You need to spawn a new thread to do this, rather than just running it in a loop which executes immediately. Just have the actionPerformed method spawn a new Thread which handles this instead. Loop, count, and update in this thread, waiting with Thread.sleep between updates. To update the label text, create a new Runnable that will update the label to the next value and put it on the Event Dispatch Thread with SwingUtilities.invokeLater. Keep this thread running in the background until you need it. I would recommend checking a shutdown status boolean every loop through, and quitting when it's set to false. This way, you can shut down the thread cleanly at any time. Or, if you want it to countdown and beep only once, you can have the thread just end after one iteration of counting.
There are lots of questions on Stack Overflow that detail each of these steps, so I won't repeat this information here.
How does the event dispatch thread work?
How to create the thread which does the counting
After changing the value you need to repaint. Also, I assume you actually want to count the seconds in which case you need to use a Timer to kick off the action of changing the label and possibly playing a sound.
If I understand correctly what you want , the below code should accomplish your goal.
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label1.setVisible(true);
Runnable runnable = new Runnable() {
int counter =1 ;
public void run() {
while(true) {
while (counter<5) {
SwingUtilties.invokeLater(new Runnable() {
public void run() {
label1.setText("counter is " + counter);
}
});
counter = counter + 1 ;
try {
Thread.sleep(1000);
}catch(InterruptedException ex) {
System.err.println(ex.toString());
}
}
counter = 1;
tk.beep();
}
}
};
new Thread(runnable).start();
});
Maybe this is does what you intened, every 4th button press it resets and beeps
loginButton.addActionListener(new java.awt.event.ActionListener() {
int counter = 1;
public void actionPerformed(ActionEvent arg0) {
label1.setVisible(true);
if (counter < 5) {
label1.setText("counter is " + counter);
label1.repaint();
++counter;
} else {
counter = 1;
tk.beep();
}
}
});
Your loop stops after the first 4 and never called again. since the text is changing to fast, you can only see the last result
int counter = 0;
while (//when do you want it to stop?)
{
// print what you want (using (counter % 4) + 1)
if ((counter % 4) == 0)
{
tk.beep();
}
}

Categories

Resources