You can customize the look of your simulation in several ways. One option is to change the node icons, which is covered by another tutorial. Here, we explain how to draw extra lines and shapes (i.e. drawings), and how to change the background image.
You can draw lines and shapes through the interface io.jbotsim.ui.painting.BackgroundPainter
,
which consists of a single method to be implemented, namely paintBackground()
.
JBotSim will call this method automatically when the UI needs to be refreshed. Two arguments are given:
UIComponent
, which encapsulates the actual object used for drawing
(in the default viewer, a Graphics2D
).Topology
object, from which you can retrieve information about the ongoing simulation.The following example consists of drawing a grid in the background:
import io.jbotsim.core.Topology;
import io.jbotsim.ui.painting.UIComponent;
import io.jbotsim.ui.painting.BackgroundPainter;
import java.awt.*;
public class MyBackgroundPainter implements BackgroundPainter {
@Override
public void paintBackground(UIComponent c, Topology tp) {
Graphics2D g = (Graphics2D) c.getComponent();
g.setColor(Color.GRAY);
for (int i = 0; i < tp.getWidth(); i++){
for (int j = 0; j < tp.getHeight(); j++){
g.drawLine(i*50, 0, i*50, tp.getHeight());
g.drawLine(0, j*50, tp.getWidth(), j*50);
}
}
}
}
In the case of Graphics2D
objects, a full range of methods are available, which allows you to draw lines and various shapes (circle, rectangles, ellipses, etc.)
Once your painter is defined, you can register it in the
JTopology
object, which is the main UI component within the JViewer. For example, in the main()
method, you may proceed as follows:
public static void main(String[] args) {
Topology tp = new Topology();
JViewer jv = new JViewer(tp);
jv.getJTopology().addBackgroundPainter(new MyBackgroundPainter());
tp.start();
}
Note that several painters can be registered. In this case, JBotsim will call them in the same order as they were registered. The usual components like nodes, links, etc. will be drawn on top of these.
Changing the background image can be done in exactly the same way as above, by exploiting the features of the
Graphics2D
object (or an equivalent object in other platforms).
The corresponding lines are as follows:
// Setting a background image
Toolkit tk = Toolkit.getDefaultToolkit();
Image image = tk.getImage(getClass().getResource("/forest.jpg"));
g.drawImage(image, 0, 0, null);
To all intents and purposes, the forest picture is available here.