Connecting a Java GUI to an ASTRA Agent
The astra-gui library provides a small bridge between an ASTRA agent and a Java user interface. The GUI can post events to the agent, and the agent can send data back to the GUI. Add this dependency to your project’s <dependencies> section:
<dependency>
<groupId>com.astralanguage</groupId>
<artifactId>astra-gui</artifactId>
<version>2.6.1</version>
</dependency>
Start the GUI from the agent
Declare the GuiModule and launch a class that implements AstraGui:
package example;
agent Counter {
module astra.gui.GuiModule gui;
module Console console;
initial !start();
plan +!start() {
gui.launch("example.CounterWindow");
}
plan $gui.event("increment", list Args) {
console.println("GUI requested an increment: " + Args);
}
}
launch(...) creates the GUI by class name and passes it an AstraEventListener. The GUI can use that listener to post events to the agent. A $gui.event(type, args) plan handles each posted event.
Implement the Java side
The GUI class implements AstraGui. Its launch method creates and displays the interface; receive handles updates sent from the agent. For example, a button can notify the agent through the listener:
package example;
import java.util.List;
import astra.gui.AstraEventListener;
import astra.gui.AstraGui;
public class CounterWindow implements AstraGui {
private AstraEventListener listener;
@Override
public void launch(AstraEventListener listener) {
this.listener = listener;
// Create and display the window and its controls here.
}
public void incrementButtonClicked() {
listener.addEvent("increment", new Object[0]);
}
@Override
public boolean receive(String type, List<?> args) {
if ("count".equals(type)) {
// Update the interface using args.
}
return true;
}
}
The agent can update the GUI with either a type and list of values or a function term:
gui.updateGui("count", [N]);
gui.updateGui(count(N));
The module converts ASTRA primitive values and lists to Java values before calling receive(...). Keep GUI updates on the GUI toolkit’s required thread (for Swing, the event dispatch thread).
Use an externally created GUI
An application can also create its GUI first and start the ASTRA agent with a reference to that interface through the application’s own Java integration. The same AstraGui and AstraEventListener methods provide the communication channel; the ASTRA agent does not need to create the window itself.