| 1 | package com.googlecode.lanterna.gui2; |
| 2 | |
| 3 | /** |
| 4 | * This {@link TextGUIThread} implementation is assuming the GUI event thread will be the same as the thread that |
| 5 | * creates the {@link TextGUI} objects. This means on the thread you create the GUI on, when you are done you pass over |
| 6 | * control to lanterna and let it manage the GUI for you. When the GUI is done, you'll get back control again over the |
| 7 | * thread. This is different from {@code SeparateTextGUIThread} which spawns a new thread that manages the GUI and |
| 8 | * leaves the current thread for you to handle.<p> |
| 9 | * Here are two examples of how to use {@code SameTextGUIThread}: |
| 10 | * <pre> |
| 11 | * {@code |
| 12 | * MultiWindowTextGUI textGUI = new MultiWindowTextGUI(new SameTextGUIThread.Factory(), screen); |
| 13 | * // ... add components ... |
| 14 | * while(weWantToContinueRunningTheGUI) { |
| 15 | * if(!textGUI.getGUIThread().processEventsAndUpdate()) { |
| 16 | * Thread.sleep(1); |
| 17 | * } |
| 18 | * } |
| 19 | * // ... tear down ... |
| 20 | * } |
| 21 | * </pre> |
| 22 | * In the example above, we use very precise control over events processing and when to update the GUI. In the example |
| 23 | * below we pass some of that control over to Lanterna, since the thread won't resume until the window is closed. |
| 24 | * <pre> |
| 25 | * {@code |
| 26 | * MultiWindowTextGUI textGUI = new MultiWindowTextGUI(new SameTextGUIThread.Factory(), screen); |
| 27 | * Window window = new MyWindow(); |
| 28 | * textGUI.addWindowAndWait(window); // This call will run the event/update loop and won't return until "window" is closed |
| 29 | * // ... tear down ... |
| 30 | * } |
| 31 | * </pre> |
| 32 | * @see SeparateTextGUIThread |
| 33 | * @see TextGUIThread |
| 34 | */ |
| 35 | public class SameTextGUIThread extends AbstractTextGUIThread { |
| 36 | |
| 37 | private final Thread guiThread; |
| 38 | |
| 39 | private SameTextGUIThread(TextGUI textGUI) { |
| 40 | super(textGUI); |
| 41 | guiThread = Thread.currentThread(); |
| 42 | } |
| 43 | |
| 44 | @Override |
| 45 | public Thread getThread() { |
| 46 | return guiThread; |
| 47 | } |
| 48 | |
| 49 | @Override |
| 50 | public void invokeAndWait(Runnable runnable) throws IllegalStateException, InterruptedException { |
| 51 | if(guiThread == null || guiThread == Thread.currentThread()) { |
| 52 | runnable.run(); |
| 53 | } |
| 54 | super.invokeAndWait(runnable); |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * Default factory class for {@code SameTextGUIThread}, you need to pass this to the {@code TextGUI} constructor if |
| 59 | * you want it to use this class |
| 60 | */ |
| 61 | public static class Factory implements TextGUIThreadFactory { |
| 62 | @Override |
| 63 | public TextGUIThread createTextGUIThread(TextGUI textGUI) { |
| 64 | return new SameTextGUIThread(textGUI); |
| 65 | } |
| 66 | } |
| 67 | } |