Skip to content

Commit 58dc3a8

Browse files
Ruediger.LundeRuediger.Lunde
authored andcommitted
Little fix to make logging thread save.
1 parent e25beb3 commit 58dc3a8

File tree

2 files changed

+26
-8
lines changed

2 files changed

+26
-8
lines changed

src/aima/gui/applications/search/map/RoutePlanningAgentAppDemo.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,8 +206,7 @@ protected AdaptableHeuristicFunction createHeuristic(int heuIdx) {
206206
@Override
207207
protected void startAgent() {
208208
if (destinations.size() != 1) {
209-
frame
210-
.logMessage("Error: This agent requires exact one destination.");
209+
frame.logMessage("Error: This agent requires exact one destination.");
211210
return;
212211
}
213212
frame.logMessage("<route-planning-simulation-protocol>");

src/aima/gui/framework/AgentAppFrame.java

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import javax.swing.JSplitPane;
1717
import javax.swing.JTextArea;
1818
import javax.swing.JToolBar;
19+
import javax.swing.SwingUtilities;
1920

2021
/**
2122
* <p>
@@ -165,14 +166,32 @@ public void modelChanged() {
165166
e.printStackTrace();
166167
}
167168
}
168-
169+
169170
/** Prints a log message on the text area. */
170171
public void logMessage(String message) {
171-
int start = textArea.getDocument().getLength();
172-
textArea.append(message + "\n");
173-
int end = textArea.getDocument().getLength();
174-
textArea.setSelectionStart(start);
175-
textArea.setSelectionEnd(end);
172+
MessageLogger ml = new MessageLogger();
173+
ml.message = message;
174+
if (SwingUtilities.isEventDispatchThread()) {
175+
ml.run();
176+
} else {
177+
try {
178+
SwingUtilities.invokeAndWait(ml);
179+
} catch (Exception e) {
180+
e.printStackTrace();
181+
}
182+
}
183+
}
184+
185+
/** Helper class which makes logging thread save. */
186+
private class MessageLogger implements Runnable {
187+
String message;
188+
public void run() {
189+
int start = textArea.getDocument().getLength();
190+
textArea.append(message + "\n");
191+
int end = textArea.getDocument().getLength();
192+
textArea.setSelectionStart(start);
193+
textArea.setSelectionEnd(end);
194+
}
176195
}
177196

178197
/** Assembles the inner structure of the frame. */

0 commit comments

Comments
 (0)