I'm having an issue with my GUI when I try to change the color of a button after 2 seconds when its has been clicked. What I want to do is to click on a white square button, then a color comes up, after 2 seconds I want it to return to it's original color (white). How can achieve this?
My code on click:
cards[index].setBackground(cards[index].getTrueColor());
try
{
Thread.sleep(2000);
cards[cardPos.get(0)].setBackground(Color.white);
}
catch(Exception e) {}
So this goes back to color white, but in an instance, doesn't wait to seconds.
Really appreciate a little help here.
Thanks!
This calls for a Timer instead of Thread.sleep. You'll want to set the timer with a delay of 2 seconds, and then have it reset the color of your button. For example, in Swing:
// onButtonClick
final Card card = cards[index];
card.setBackground(card.getTrueColor());
new Timer(2000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Change color back
card.setBackground(Color.WHITE);
}
}).start();
How to Use Swing Timers
You can use the AsynkTask class in Android. You can use the onPreExecute method to execute the initial task, and then you can wait and change the button color after 2 sec, this can be done in doInBackground method and you can publish the results to UI by calling publish progress method, and finally you can use the onPostExecute method.
http://developer.android.com/reference/android/os/AsyncTask.html
Related
I want to make a ProgressBar move gradually using a Jbutton. To achieve this I am using a for loop and the method Thread.sleep. The problem is that insted of moving a tiny bit every second (the progress bar) after pressing the button, the program waits until the loop finishes and then does instantly move the progress up. When I take the loop outside of the button listener it works as I want but I really need it to work when pressing the button. Here is the code:
progressBar.setOrientation(SwingConstants.VERTICAL);
progressBar.setMinimum(0);
progressBar.setMaximum(100);
progressBar.setValue(50);
panel1.setLayout(null);
panel1.add(progressBar);
progressBar.setBounds(40,6,100,100);
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int counter = 5;
for (int i = 0; i < 5; i++) {
progressBar.setValue(progressBar.getValue() + counter);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
}
});
If anyone can help me I will be very grateful!
Your code runs on the Event Dispatcher Thread (EDT). That thread is responsible for handling events, but also for repainting. Because it's just one thread, the repainting only occurs after your method ends.
There are some ways to solve this. In your case, a javax.swing.Timer would probably be easiest. Instead of running the loop in a single method, the button click starts a timer that runs every second. When it's done the timer can cancel itself. A slightly more difficult alternative is to use a SwingWorker. You could publish data in the doInBackGround method, and override process to perform the updates to the progress bar.
For more information, please read Concurrency in Swing.
I am new to java, I think this might be simple but I couldn't find the answer to my question anywere, maybe because I didn't phrase it right.
I have this simple pseudo code, if I run it, it will seem as if nothing happens , I want the user to be able to see(icon2) for a few seconds, before it is changed back to icon.
I tried Thread.sleep but it didn't work, it worked on whatever else is inside (if) like a simple (print) but doesn't work on the interface. I think because it is in a the different thread, because I used Netbeans to create a frame class.
ImageIcon icon = new ImageIcon("somepath");
jLabel.setIcon(icon); //i give my label some icon
jLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
ImageIcon icon2 = new ImageIcon("some_otherpath");
jLabel1.setIcon(icon2); // The user clicks on the label so the icon changes
if(condition){ //if some condition is true i want the icon to change back
jLabel1.setIcon(icon); // if condition is not true, the label keeps icon2
// but i want the user to be able to see the change.
}
}
});
Thank you in advance.
Try using Java ScheduledExecutorService:
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
Runnable task = new Runnable() {
public void run() {
//Your 'if' condition here
}
};
int delay = 3; //delay 3 seconds, or whatever
scheduler.schedule(task, delay, TimeUnit.SECONDS);
scheduler.shutdown();
...
This program simply waits 3 seconds before executing your if condition. While it delays, your users will see icon2. This code chunk should be placed after this line jLabel1.setIcon(icon2);
I have this loop
while (true) {
game.update();
view.repaint();
Thread.sleep(DELAY);
}
In the game.update various components of the game have their position changed and those updates are reflected when the repaint() method is called on the view. The view extends JComponent and loops through the game objects and calls their print methods.
What I want to do is have a boolean called nextLevel in the game and if it's true Flash text on the screen for the player to notify them that they're going onto the next level. Maybe flash 4-5 times. Then continue the game.
Is this possible? I have been playing around with Thead.Sleep() but this only seems to pause the displaying and in the background the game is still going on.
Any ideas on how to do this?
Maybe you want to avoid threading by using a Timer object.
an example like that could be
int flashTimer = 0;
if(nextLevel) {
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
//flash something method here
flashTimer++;
}
});
timer.start();
}
and then check your flashTimer if it reaches the number you want then just stop the timer by timer.stop();
Just an idea which seems to me a bit simpler. the 1000 value is milliseconds which is passed and executes the code inside the actionPerformed method every 1 sec.
Hope it helped
I am using freeTTS to speak out some text, in the background i want a animated gif to keep playing
When i try this: as soon as the voice starts speaking, the image in background gets hanged even if i keep it in some other JFrame... and after the speech is completed it starts moving. I want it to run properly without pauses.
I am placing a animated gif in a label by importing it to my application and changing the icon to that image in label' properties.
Edit
Here is my code:
private void RandomjBActionPerformed(java.awt.event.ActionEvent evt) {
Voice voice;
voice = voiceManager.getVoice(VOICENAME);
voice.allocate();
voice.speak("Daksh");
}
I am actually using a lot of setVisible, setText, declaration of integers, calculating on them but i have removed them to simplify the code for you to understand. Still it gives the same problem if executed.
The button 'RandomjB' is clicked from another button by the following code:
final Timer timer = new Timer(zad, new ActionListener() {
int tick = 0;
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Success" + ++tick);
RandomjB.doClick();
final int col = Integer.parseInt(t3.getText());;
if (tick >= col) {
((Timer) e.getSource()).stop();
for(int g=0; g<col; g++){
jButton2.setVisible(true); // Check Button -> Visible
}
}
}
});
timer.setInitialDelay(0);
System.out.format("About to schedule task.%n");
timer.start();
System.out.format("Task scheduled.%n");
It is hard to tell without the code, I however assume that you loop the speech synthesis within the one and only Swing-Thread and therefore block all kind of window updates as long as the speech loop is in progress.
As stated by Shaun Wild: you need to use a second Thread for the speech loop.
You may want to do some research on Threads and Concurrency
These allow two things to operate simultaneously, this is just my assumption.
Assuming that you instantiate some kind of class for the FreeTTS you may want to do something like this
FreeTTSClass tts;
new Thread(new Runnable(){
public void run(){
tts = new FreeTTSClass();
}
}).start();
I have java method that executes a very long model. It takes about 20 minutes. When I press the button, the button remains pressed until the model is finished. I need to create a button that when is pressed, it stop the model execution
So far I have 2 buttons: Stop and Start. My problem is that when I press the start button, all the buttons from the GUI are freeze and they cannot be pressed until the model finishes
How can I create a stop button?
Thank you,
Ionut
You should use a SwingWorker. They are specifically designed for performing long running tasks off of the EDT while still being able to update the GUI with progress reports.
It is best to start a Thread once the button is clicked. You could make a stop button that stops the thread if it has not finished yet. For this you will have to keep track of the Thread though (for example in a static variable).
A quick guide to threading: http://www.tutorialspoint.com/java/java_multithreading.htm
Please take a look at this as well: How to properly stop the Thread in Java?.
If you are executing a 20 minute task in response to a button click you should probably be doing it in a background thread.
You have to use multi-threading. A basic example-
public class ThreadTest {
private int getSum(int x, int y){
return x + y;
}
public static void main(String args[]) {
ThreadTest tTest = new ThreadTest();
System.out.println(tTest.getSum(2, 5));
// Start the thread
new LongProcess().start();
// Since the thread sleeps for two seconds
// You will see 5 + 5 = 10 before Done! gets printed out
System.out.println(tTest.getSum(5, 5));
}
}
class LongProcess extends Thread {
public LongProcess(){
System.out.println("Thread started..");
}
public void run() {
try{
Thread.sleep(2000);
System.out.println("Done!");
} catch(InterruptedException iEx){
System.out.println(iEx.toString());
}
}
}