Updating GUI gives a flickering effect - java

I currently have a JFrame where on it's content pane I draw images on from a game loop at 60 frames per second. This works fine, but at the right side, I now have more Swing elements on which I want to display some info on when selecting certain parts of the content pane. That part is a static GUI and does not make use of a game loop.
I'm updating it this way:
public class InfoPanel extends JPanel implements Runnable {
private String titelType = "type: ";
private String type;
private JLabel typeLabel;
private ImageIcon icon;
public void update() {
if (this.icon != null)
this.typeLabel.setIcon(this.icon);
if(this.type != null || this.type != "")
this.typeLabel.setText(this.titelType + this.type);
else
this.typeLabel.setText("");
}
public void run() {
try {
Thread.sleep(150);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.update();
}
(this method is only called when the player has actually moved, so it's just called once - not 60 times per second)
I noticed that, when calling this update()-method from the game loop, I get flickering effects. I assume this is because updating the UI takes some time, so I decided to put it in a new thread. This reduced the flickering, but didn't solve it.
Next, I decided to give the new thread low priority as the part of the screen which is redrawed 60 times a second is far more important. This reduced the flickering again, but it still happened. Then, I decided to use Thread.sleep(150); in the new thread before calling the update()-method, which solved the flickering effect on my system completely.
However, when running it on other systems, it still happens. Not as often as before (maybe one time per 20 seconds), but it's still pretty annoying. Apparantly, just updating the UI in another thread doesn't solve the problem.
Any ideas how to completely eleminate the flickering?

Call the update() in SwingUtilities.invokeAndWait() which stops the thread and updates UI in EDT.

Problem is that you are use Thread.sleep(int), that stop and freeze GUI during EventDispatchTread more in the Concurency in Swing, example demonstrating freeze GUI by using Thread.sleep(int), example for Runnable#Thread
If you want to delay whatever in Swing then the best way is implements javax.swing.Timer

Related

How to use a thread to run another JFrame while the main is still running

I have a jframe i want to display while my main frame is running. i want to pause my main code, until the user does the necessary actions on the other frame. I've read a lot of solutions but i need to see it done for my code to understand and grasp it fully. i do not want to use jdialog like I've seen listed as an answer before. My main goal is to understand better threading so that i can use what i learn in different cases.
With the code I've created, when running the thread, only just the frame loads, none of the other features are there on the frame. (the frame is simple it has a label, a list the user selects from, and a button to basically return the chosen list value.) its like the thread is cut off from completing or something.
here is my class calling the screen:
public class myThread implements Runnable {
String result = null;
public void run() {
MessageScreen ms = new MessageScreen();
ms.setVisible(true);
}
public String getResult() {
return result;
}
public void setResult(String AS) {
result = AS;
}
}
in my main code, a method is called that is returning a String[] value, with this method at some point i have the following code calling the new thread to get the value necessary to return in the original main method:
myThread mt = new myThread();
Thread t = new Thread(mt);
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
myreturn = new String[] {"true", mt.getResult()};
without listing the whole code for the second frame, when the user presses the button, and at the end of the listener tied to the button press the i want to close the frame and return a string that was selected from the list:
jf.dispose();
myt.setResult(AdminSelection);
in the frame class, i have the following instance variables declared:
String AdminSelection = null;
myThread myt;
i hope this is enough information for someone to help me out and understand whats gone wrong here.
The function join() waits until the end of the run() method, when you do t.join(), your thread is already or almost ended. This is because in your run() method there is nothing that blocks the thread until the user has clicked the confirm button. And is better like this!
There is no sense to create a thread here, you should use a callback, or more generally in Java, a listener. You can take a look at Creating Custom Listeners.
But, especially if you want to pause your main code, you should use a (modal) JDialog which is made for this! Don't try to block the UI by yourself, you could block the UI thread (handled by Swing/AWT) by mistake. Creating a JDialog is better because everything is already made for this usage on the UI thread.
Also, you must know that create a Thread is really long, use a Thread when you really need it.

contentpane.removeAll does not remove JPanel

I have a JPanel with a start button when that button is pressed it calls through the mainFrame the start() function in the controller
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource().equals(start)) {
System.out.println("hi");
try {
f.c.start();
} catch (KludgeException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
the start() function calls the askQuesions() function which loops over questions creates a question panel for them and stores the answers.
public void start() throws KludgeException{
System.out.println("start");
askQuestions();
ConductInference();
}
public void askQuestions() throws KludgeException {
QuestionsPanel qp = new QuestionsPanel(main);
for(data.containers.Question q : kludge.getQuestions()){
qp.addQuestion(q.getQuestion(), q.getType());
main.setPanel(qp);
synchronized(this){
while(!next){
try {
wait();
kludge.setSystemValue(q.getValueName(), v);
//System.out.println("waitOver");
} catch (InterruptedException e) {}
}
}
next = false;
//System.out.println("next question");
}
System.out.println("questions over;");
}
this is a function in the mainFrame which is a JFrame it set the necessary panel.
public void setPanel(JPanel p){
main.getContentPane().removeAll();
main.getContentPane().add(p);
main.validate();
System.out.println("all removed, added and validated");
}
My problem is this... the program gets stuck on the startPanel when the stat button is pressed it freezes. If i skip the whole startPanel and tell it to go straight to the questions it works fine. but still i dont want it to go straight to the questions. For some reason it switches between the question panels fine but not between the startPanel and questionPanels..
You've got a concurrency issue and are calling long-running code on the Swing event thread, an issue that will prevent this thread from doing its important jobs such as painting the GUI and interacting with the user. The solution is to do the long-running code in a background thread such as provided by a SwingWorker. That and read up on Swing concurrency: Lesson: Concurrency in Swing
OK, I'm now sure that my original recommendation -- to use a background thread -- is wrong, that instead you've over-complicated your code with the while loop, the synchronized block and the wait. Yes these are blocking the event thread, and yes, this is hamstringing your application, making it freeze and become totally unresponsive, but the solution is not to use a background thread but instead you will want to get rid of the while (true) loop, the synchronized block and the wait() call and in their place use event listeners and call back methods. The exact wiring of this will depend on code that we're not yet privy to, but that is the solution to this problem. For instance, the question panel could notify a control class that a question has been answered, to change the state of the model so that it moves on to the next question. The model then changes, and this can notify the view that it must update itself and now display this next question.
Side notes:
you're better off using a CardLayout to swap views then to directly swap them. The tutorial can be found here: CardLayout tutorial.
And regarding: main.setPanel(qp);
You appear to be re-adding the QuestionPanel to the main within the for loop. If so, you only need to and only should add it once.

Is there a way to know if a JPanel is finished loading it's content?

I'm writing an application that adds cards (JPanels) to a CardLayout during runtime. The problem is that some components on the card loads faster than others, making it appear glitchy and not properly rendered before it's displayed.
I want it to be ready when shown for the first time.
I have solved the issue temporary by a loading screen, which makes the thread sleep for 1500 ms. Is there a more exakt way to know if everything on the panel is loaded?
private void showLoadingScreen() {
final Component glassPane = getGlassPane();
setGlassPane(loadingPanel);
loadingPanel.setVisible(true);
Thread thread = new Thread() {
public void run() {
try {;
Thread.sleep(1500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setGlassPane(glassPane);
}
};
thread.start();
}
Do all your file loading and data manipulation in a background thread that is created using a SwingWorker. Then before executing the SwingWorker, add a PropertyChangeListener. When the PropertyChangeEvents newValue is SwingWorker.StateValue.DONE, then you know all background work is done and you can display your GUI.
Please have a look at the Concurrency in Swing tutorial, and for an example, please have a look at this answer to a similar question.

libgdx - doing something in other thread not working

My game has a stats queue, after each game the current game stats goes into the queue.
Whenever the mainmenu starts i want to upload all the game stats to a server, and this take like 1-3 seconds and I want to do this in an other thread.
My code
#Override
public void show() {
Global.key = Global.getKey();
// System.out.println(Stats.getJSONObject(Global.key));
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
Stats.TryUploadGame1();
System.out.println("DONE");
}
});
.....
}
But this also freezes my game.
What should I do?
Your current code is posting a Runnable instance that will be executed by the render thread before the next frame. The Gdx.app.postRunnable API is generally used so background threads can ask for something to happen on the render thread. You want to post a Runnable to execute anywhere but the render thread.
As long as your Stats code doesn't interact with OpenGL context at all (since Android OpenGL APIs assume only a single thread interacts with them), you can just post your Runnable on a new background thread:
new Thread(new Runnable() { ... }).start();
This should unblock your render. (Of course, if your background thread uses a lot of CPU, it can still interfere with the render thread, but if its mostly doing blocking IO or host has spare cores, it shouldn't interfere.)
This could be improved in lots of ways (using a ThreadPool, or using Android-aware background task support), but if your stats update is relatively quick and the thread creation isn't frequent this should work fine.
Okay to do something in a other thread you need to take care of the OpenGL context. Inside of a different thread you cant do anything that does render stuff. You are forced to push such thing into the renderthread in any way. And you need to synchronize everything that can be called from the regular render thread from libgdx. For example you want to call the .act(float delta) from a stage from a different thread you are forced to put the stage indo an synchronized block.
The post runable isn't a thread. It is an runable that get executed at the beginning of the next rendercall. So it will stop the game till it's done but it is inside of the OpenGl context thread. (That's why your game stops)
So here is an example of how to use threading in libgdx. I use this inside of my game. It runs on 210 frames so 210 updatecalls per second. You can change it to as fast as possible or just to 60fps whatever you need:
public class GameLogicThread extends Thread {
private GameScreen m_screen;
private boolean m_runing;
private long m_timeBegin;
private long m_timeDiff;
private long m_sleepTime;
private final static float FRAMERATE = 210f;
public GameLogicThread(GameScreen screen) { //pass the game screen to it.
m_screen = screen;
setName("GameLogic");
}
#Override
public void run() {
m_runing = true;
Logger.log("Started");
while (m_runing) {
m_timeBegin = TimeUtils.millis();
// act of the camera
synchronized (m_screen.figureStage) { //stage with figures
// now figures
if (m_screen.m_status == GameStatus.GAME) {
m_screen.figureStage.act(1f / GameLogicThread.FRAMERATE);
}
}
m_timeDiff = TimeUtils.millis() - m_timeBegin;
m_sleepTime = (long) (1f / GameLogicThread.FRAMERATE * 1000f - m_timeDiff);
if (m_sleepTime > 0) {
try {
Thread.sleep(m_sleepTime);
}
catch (InterruptedException e) {
Logger.error("Couldn't sleep " + e.getStackTrace());
}
} else {
Logger.error("we are to slow! " + m_sleepTime); //meight create it dynamic so if you are to slow decrease the framerate till you are not to slow anymore
}
}
}
/**
* Stops the thread save<br>
*/
public void stopThread() {
m_runing = false;
boolean retry = true;
while (retry) {
try {
this.join();
retry = false;
}
catch (Exception e) {
Logger.error(e.getMessage());
}
}
}
}
This does update all my figures. To not cause any troubles with the rendering thread the figurestage is synchronized. (Kind of critical section)
Dont forget that you need to create a new thread every time you stopped it. so for example inside of the show you need todo this:
#Override
public void show() {
super.show();
m_logic = new GameLogicThread(this); //create a new one inside of the GameScreen
m_logic.start(); //start the thread
}
Also dont forget to savestop it inside of the pause stop and so on.
#Override
public void dispose() {
m_logic.stopThread();
}
According to the wiki
To pass data to the rendering thread from another thread we recommend using Application.postRunnable(). This will run the code in the Runnable in the rendering thread in the next frame, before ApplicationListener.render() is called.
So calling that method is just creating a new thread on to run on the render thread.
You may want to use standard java practice on creating threads unless this is frowned upon in libgdx because of android, that I am not sure of.

JSlider knob isn't updating as video progresses

this is my code for updating jslider
try{
name=(String) jList1.getSelectedValue();
CanvasVideoSurface videoSurface = mediaPlayerFactory.newVideoSurface(canvas1);
mediaPlayer.setVideoSurface(videoSurface);
mediaPlayer.setAdjustVideo(true);
mediaPlayer.playMedia(name+".mp4");
mediaPlayer.setVolume(jSlider1.getMinimum());
mediaPlayer.parseMedia();
time = (int)(mediaPlayer.getMediaMeta().getLength()/1000);
jSlider2.setMaximum(time);
while(jSlider2.getValue()<jSlider2.getMaximum())
{
jSlider2.setValue((int) this.mediaPlayer.getTime()/1000);
}
}
catch(Exception e)
{
e.printStackTrace();
}
and for changed state of slider this is the code
private void jSlider2StateChanged(javax.swing.event.ChangeEvent evt)
{
mediaPlayer.setTime((long) this.jSlider2.getValue());
}
but it doesn't change position of nob,infact it keeps playing from start again anda again.i think reason is that setTime() function keeps updating to 0 before jslider can take new value.is there any solution??maybe using threads??
thanks!!
With this code:
while(jSlider2.getValue() < jSlider2.getMaximum())
{
jSlider2.setValue((int) this.mediaPlayer.getTime()/1000);
}
You're calling a long-running loop on the Swing Event Dispatch Thread or EDT, and this will freeze your GUI preventing all painting. Consider running your background process in a SwingWorker's doInBackground method and then updating the GUI via the SwingWorker's publish/process method pair. Also, if you're going to poll the media player, consider putting in a Thread.sleep(/* some number */) inside the polling loop since it doesn't make sense to poll almost continuously.
For more on this, please have a look at Concurrency in Swing.

Categories