Tim,
as a rule of thumb you should never call getGraphics() on a component - when
you need a graphics object, it is given to you by the system like in
paint(Graphics). Your getting the screen flicker, because you are just
clearing the background in your paint() but painting the units from another
thread.
Since Swing is double buffered, you don't have to do any specials, just
override paintComponent().
As an improvement I would suggest using the observer-pattern, e.g.:
class UnitMap extends java.util.Observable implements Runnable {
private Unit[] units;
private int turn;
public UnitMap() {
/* initialize units ... */
new Thread(this).start();
}
public Unit getUnit(int i) {
return units[i];
}
public int getNumberOfUnits() {
return units.length;
}
public void run() {
while (true) {
turn++;
System.out.println("turn: " + turn);
/* process units */
for (int i = 0; i < units.length; i++){
Unit unit = unitArray[i];
unit.moveUnit();
}
notifyListeners("change");
/* sleep until next turn */
try {
Thread.sleep(SLEEP);
} catch (InterruptedException e) {
}
}
}
}
class UnitMapPanel extends JPanel implements java.util.Observer {
private UnitMap map;
public UnitMapPanel(UnitMap map) {
this.map = map;
map.addObserver(this);
}
public void update(Observable observable, Object arg) {
if (observable == map && "change".equals(arg)) {
repaint();
}
}
public void paintComponent(Graphics graphics) {
/* clear background */
Rectangle clipBounds = graphics.getClipBounds();
graphics.setColor(getBackground());
graphics.fillRect(clipBounds.x, clipBounds.y,
clipBounds.width, clipBounds.height);
/* paint units */
for (int i = 0; i < map.getNumberOfUnits(); i++){
Unit unit = map.getUnit(i);
unit.drawUnit(graphics);
}
}
}
/* somewhere, probably in main thread */
UnitMap map = new UnitMap();
UnitMapPanel panel = new UnitMapPanel(map);
frame.add(panel, BorderLayout.CENTER);
That would be my solution
Sven
===========================================================================
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff JAVA2D-INTEREST". For general help, send email to
[EMAIL PROTECTED] and include in the body of the message "help".