Ok, So I have a JFrame and, a JLabel. All of which likes to load simultaneously. But, I want it so the JFrame loads first and, then the JLabel loads an updates itself. I’m thinking I have to do this with threads?
You could also have a system like this.
public class Loader {
public static HashMap<String, JLabel> components = new HashMap<String, JLabel>();
public static JFrame frame;
public static void setJFrame(JFrame _frame){
frame = _frame;
}
public static void addJLabel(String title, JLabel label){
components.put(title, label);
}
public static int tick = 0;
public static void load(){
if(tick == 0){
// Load the JFrame
} else {
// Load a JLabel
}
tick++;
}
// Use this to update a label
public static JLabel getLabel(String title){
return components.get(label);
}
}
Again, just a suggestion.
CopyableCougar4
You just want the label to show up after a delay?
...
frame.setVisible(true);
new Thread(new Runnable() {
try {
Thread.sleep(delay);
} catch (Exception e) {}
frame.add(label);
}).start();
If I were to use this method, Which appears to work right now, How would I go about doing thread.join() in this instance?
/Edit: Am I right to assume that the thread stops automatically once everything is completed inside of it?
Are you asking that because you want the main thread to wait for the JLabel to appear? If so, then just do the sleeping in the main thread, no extra thread needed.
The reason I asked was because once the JLabel appears and, reaches it’s last update the game starts. Which has its own thread and, I’m curious if this will create any efficiency problems down the road.
public LoadingGUI(int id) throws IOException {
super(2);
setTitle(".:: " + title + " v" + version + " by: " + author + " :: Loading ::.");
validate();
new Thread(new Runnable() {
public void run() {
// Each of these access a setJLabel method in this class and, Is called statically in each object below
im = new ImageManager(); // Ex: Does setJLabel("Grass Tile"), setJLabel("Water Tile") as defined
map = new Level();
player = new Player(0, 0, im);
loaded = true;
//dispose();
}
}).start();
if (loaded) {
try {
// Starts the game, Which has it's own thread
new Display().DisplayStart();
} catch (IOException ex) {
Logger.getLogger(LoadingGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
}
}
Basically, I’m worried about nested/unnecessary threads. I can start the game in the super class, But how would I tell the main thread to wait or, sleep for the thread in this classes method to finish?
This is precisely the use case of a SwingWorker
Even has update-JLabel-background-thread example. I’d assume you’d put the “start the game” code in done().
EDIT: Though I still don’t see why you actually need it to be asynchronous.