create array of agents in jade - java

good morning, i would like to create an array that contain a multiple instances of an agent (many agents that have a same behaviour), so i used netbeans to create firstly an agent management who create the others agents and draw a circle that represent every agent in a frame. this the code for the main agent:
package jade;
/**
*
* #author walid
*/
import jade.core.Agent;
import jade.core.Runtime;
import jade.core.ProfileImpl;
import jade.wrapper.*;
import javax.swing.JFrame;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.logging.Level;
import java.util.logging.Logger;
import jade.Agent1;
public class AgentEnvironement extends Agent{
private JFrame jFrame = null;
private Agent1 []tab;
#Override
protected void setup() {
try {
getJFrame().setVisible(true);
} catch (StaleProxyException ex) {
Logger.getLogger(AgentEnvironement.class.getName()).log(Level.SEVERE, null, ex);
}
}
public JFrame getJFrame() throws StaleProxyException {
if (jFrame == null) {
jFrame = new JFrame();
jFrame.setSize(new java.awt.Dimension(500,350));
Dimension tailleEcran =Toolkit.getDefaultToolkit().getScreenSize();
int largeurEcran = tailleEcran.width;
int hauteurEcran = tailleEcran.height;
jFrame.setLocation((largeurEcran-500)/2,(hauteurEcran-350)/2);
jFrame.setTitle("Environement des agents rumeurs.");
jFrame.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
//jFrame.setContentPane(getJContentPane());
Runtime rt = Runtime.instance();
// Création du profil par défault
ProfileImpl p = new ProfileImpl(false);
AgentContainer container =rt.createMainContainer(p);
// Agent controleur pour permettre la création des agents
AgentController Agent=null;
Agent = container.createNewAgent("Agent1", "jade.Agent1", null);
Agent.start();
}
return jFrame;
}
}
and this the code for the agent class that i would like to create many instance of him
package jade;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
/**
*
* #author walid
*/
public class Agent1 extends Agent {
/**
*/
#Override
public void setup() {
addBehaviour(new comportement());
}
class comportement extends CyclicBehaviour {
public void action() {
System.out.println ("ready");
}
}
public static void main(String[] args) {
}
}
honestly i'm not good in java programming and if someone can help me i will be very pleasure.

Create an array of agents???? I'm not sure what that means but if you want to create multiple agents use a for loop and a counter to increment the name.
for (agentcounter=1;agentcounter++;agentcounter<agentmax)
{
Agent = container.createNewAgent("Agent"+agentcounter, "jade.Agent1", null);
}
this should create multiple agents of type jade.Agent1
eg for agentmax=10
Agent1 (Type jade.Agent1)
Agent2 (Type jade.Agent1)
Agent3 (Type jade.Agent1)
....
Agent10 (Type jade.Agent1)
Notice that in
Agent = container.createNewAgent("Agent"+agentcounter, "jade.AgentClass", null);
The first field is the name of the instance of the agent
The second field is the agent class

You cannot call your agent 'Agent', because is the name of another class, the root class your agents are inheriting from.
AgentController anotherName=null;
anotherName = container.createNewAgent("Agent1", "jade.Agent1", null);
anotherName.start();
That should work fine.
Another comment; Agents don't need and don't have a 'main()' method, because they are created in another fashion, as you have just seen.

Related

Exception in Application constructor - Cannot Start a Class

**I'm unable to create a constructor from "GUIController".. The program runs if i delete this line
"GUIController(){myModel = new TheModel(this)"
but i still need it in other part. Please help!
**
package theclient;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class GUIController extends Application {
TheModel myModel;
GUIController(){
myModel = new TheModel(this);
}
//public void init(){}
public TextArea myTextArea;
public TextField myTextField;
// Button and text field actions
public void myButtonAction() {
sendMsg();
}
public void myTextFieldAction() {
sendMsg();
}
// Append coming message
public void displayMsg(String comingMSG) {
System.out.println("Receive 01");
myTextArea.appendText(comingMSG);
}
public void sendMsg() {
try {
System.out.println("Send 01");
myModel.myChatServer.tellOthers(myTextField.getText());
} catch (RemoteException ex) {
Logger.getLogger(GUIController.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("GUI.fxml"));
Scene scene = new Scene(root, 600, 400);
stage.setScene(scene);
stage.setResizable(false);
stage.show();
}
public static void main(String[] args) throws Exception {
new GUIController();
launch(args);
}
}
The Second class. I'd be thankful if you can suggest any edits to the code. Thanks in advance for your efforts.
package theclient;
import common.ChatServerInt;
import common.ClientInt;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TheModel implements ClientInt {
public GUIController myCtrl;
ChatServerInt myChatServer;
TheModel(GUIController myCtrl) {
this.myCtrl = myCtrl;
}
public ChatServerInt connection() {
if (myChatServer == null) {
try {
Registry reg = LocateRegistry.getRegistry(1111);
myChatServer = (ChatServerInt) reg.lookup("ChatService");
myChatServer.register(this);
myChatServer.tellOthers("I'm here!");
} catch (RemoteException | NotBoundException ex) {
Logger.getLogger(TheModel.class.getName()).log(Level.SEVERE, null, ex);
}
} return myChatServer;
}
#Override
public void receive(String msg) throws RemoteException {
myCtrl.displayMsg(msg);
}
}
Following the Model-view-controller design pattern, the model shouldn't be holding a reference to its controller. If the controller needs to respond to changes in the model's data, then this can be done with properties and listeners. The model holds a property (here, a StringProperty) and the controller listens for changes to the property.
For your code, this means storing the msg in a StringProperty. The controller, after constructing the model, attaches a ChangeListener that calls displayMsg when the model receives a message.
Using a property and listener, TheModel no longer stores a reference to GUIController and does not take a GUIController as a parameter in its constructor.
GUIController would look something like this:
public class GUIController extends Application {
...
TheModel myModel;
...
GUIController(){
myModel = new TheModel();
// Listen for changes in the msg StringProperty and call displayMessage when it changes
myModel.getMsgProperty().addListener(msg -> this.displayMsg(msg));
}
...
Note that the constructor for GUIController no longer needs to pass this to the constructor TheModel. (In general, avoid passing this outside of the constructor. An object is not fully constructed until the constructor returns.)
TheModel would look something like this:
public class TheModel implements ClientInt {
...
private StringProperty msgProperty;
...
// remember to add a getter and setter for msgProperty!
...
#Override
public void receive(String msg) throws RemoteException {
// When a message is received, listeners attached to msgProperty will execute when setValue is called
msgProperty.setValue(msg);
}

Minecraft modding Java exception in mod item class

This is my code, I have errors on line 16 and 17, i don't know where im going wrong, this is in the main ModItems class and i have been using this video as a guide If you need the rest of my class files i have uploaded the current copy of my classes here
The error on both lines is The constructor Item(Item, Item) is undefined
package TheStraying11.QuarkyPower.init;
import TheStraying11.QuarkyPower.Reference;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.item.ItemSoup;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.registry.GameRegistry;
import TheStraying11.QuarkyPower.items.QuarkUp;
import TheStraying11.QuarkyPower.items.QuarkDown;
public class ModItems {
public static Item QuarkUp;
public static Item QuarkDown;
public static void init() {
QuarkUp = new Item(QuarkUp, QuarkUp);
QuarkDown = new Item(QuarkDown, QuarkDown);
}
public static void register() {
registerItem(QuarkUp);
registerItem(QuarkDown);
}
public static void registerRenders() {
}
public static void registerItem(Item item) {
GameRegistry.register(item);
}
public static void registerRender(Item item) {
ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation(new ResourceLocation(Reference.MODID, item.getUnlocalizedName().substring(5)), "inventory"));
}
}
friend helped, changed
QuarkUp = new Item(QuarkUp, QuarkUp);
QuarkDown = new Item(QuarkDown, QuarkDown);
to
quark_Up = new itemQuarkUp();
quark_Down = new itemQuarkDown();
EDIT:
Completely started again as that video just made a mess imo, that i didn't understand, I guess ill get better soon haha, i just wish i could use Python instead

In Java why would I be unable to import a sub-class into another class when I can import the superclass?

I am building a small scale system that has both workers and managers, manager inherits all of the workers properties because he also is a worker but has higher access within the system. I have a system class which has been reduced in size for clarity,
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Scanner;
public class system {
static Depot depot = new Depot("d1");
//static Depot depot2 = new Depot("d2");
//static Depot depot3 = new Depot("d3");
static ArrayList<Depot> depotArray = new ArrayList<Depot>();
public static void systemSetup() {
depotArray.add(depot);
}
public static void main(String[] args) throws ParseException {
StateThreadClass stateThreadClass = new StateThreadClass();
Thread thread = new Thread(stateThreadClass);
thread.start();
systemSetup();
GetDepot();
}
}
Once I get a depot it brings me to my main depot class which holds most calculations.
import java.io.IOException;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.Scanner;
//import Driver.Manager;
public class Depot{
String name;
int LOCount = 0;
int counter = 0;
#SuppressWarnings("deprecation")
Long date3 = 1478217600000L;
Date date1 = new Date(1478217600000L);
Date date2 = new Date(1479217600000L);
Worker worker = new Worker ("tom", "tom", false);
Worker worker = new Worker ("phil2", "phil2", false);
Worker worker = new Worker ("phil", "phil", true);
-----> Manager manager = new Manager("ben", "ben", true);
etc.....
}
I can instantiate the Worker with no problem and use it within the system but when I attempt to instantiate the Manager I get an error saying "Manager cannot be resolved to a type", I am given the option of importing it. When I do I get another error "The import Worker cannot be resolved"
This is my Worker and Manager class minus unnecessary code,
import java.io.IOException;
public class Worker {
private String username;
private String password;
private boolean available;
public Worker(String username, String password, boolean av) {
this.username = username;
this.password = password;
this.available = av;
}
public Boolean CheckPassword(String password) {
return this.password.equals(password);
}
public Boolean CheckUsername(String username) {
return this.username.equals(username);
}
public class Manager extends Worker {
public Manager(String username, String password, boolean av) {
super(username, password,av);
}
}
Any help would be appreciated, I know I shouldn't be using static but I will deal with that another day!
cheers
Ensure that your Manager class is defined in its own file separately. As it's defined as an inner class of Worker, then it's currently not accessible outside of your Worker class.
Once you have that fixed, then you should be able to refer to your Manager class from your Depot class, provided they are in the same package. If they are not, then simply include the import for your Manager class and you'll be able to access your Manager class.
Some info on inner classes: http://www.javaworld.com/article/2077411/core-java/inner-classes.html.

java.lang.NoSuchMethodError when it is clearly there

General Info: I am using the Bukkit/Spigot API in version git-Spigot-1d14d5f-ba32592 (MC: 1.8.3) (Implementing API version 1.8.3-R0.1-SNAPSHOT), IntelliJ IDEA 14.1.3 and compile with its default compiler. The java jdk version is 1.8.0_25.
So when I try to call this class's constructor, it throws the runtime exception from the title.
Inventory menu class
package me.lakan.util.inventory;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.HashMap;
import java.util.Map;
#SuppressWarnings("unused") // Util functionality is not always used
public class InventoryMenu implements Listener {
private InventoryType type;
private String title;
private Map<Integer, MenuOption> options;
// Constructors
public InventoryMenu(InventoryType type, String title, JavaPlugin plugin) {
this.options = new HashMap<Integer, MenuOption>();
this.type = type;
this.title = title;
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
public boolean addOption(int position, MenuOption option) {
boolean res = isPosEmpty(position);
this.options.put(position, option);
return res;
}
public void addOption(String name, int position, ItemStack icon) {
addOption(position, new MenuOption(icon, name));
}
public boolean isPosEmpty(int position) {
return !this.options.containsKey(position);
}
public void openFor(Player p) {
// Create a new inventory
Inventory inv = Bukkit.createInventory(p, this.type, this.title);
// Fill all icons at their positions
for (Map.Entry<Integer, MenuOption> key : this.options.entrySet()) {
inv.setItem(key.getKey(), key.getValue().getIcon());
}
// If the inventory is a player inventory, update the player's
if (inv.getType() == InventoryType.PLAYER) {
p.getInventory().setContents(inv.getContents());
}
// For any openable inventory, just open it up
else {
p.openInventory(inv);
}
}
/**
* Listens for inventory clicks
* If the inventory is a menu:
* - Cancel movement
* - Push event
* - Close inventory if it should
* #param e The actual event
*/
#EventHandler(priority = EventPriority.HIGHEST)
public void onInventoryClick(InventoryClickEvent e) {
// Prevent clicking if this inventory was clicked
if (e.getClickedInventory().getName().equals(this.title)) {
e.setCancelled(true);
// Check for option
if (this.options.containsKey(e.getRawSlot())) {
// Get the option for this slot
MenuOption option = this.options.get(e.getRawSlot());
// Fill out an event and push it
MenuClickEvent event = new MenuClickEvent((Player) e.getWhoClicked(), true, option.getName(), e.getRawSlot());
Bukkit.getServer().getPluginManager().callEvent(event);
// Now close inventory if not cancelled
if (event.willCLose()) {
e.getWhoClicked().closeInventory();
}
}
}
}
#SuppressWarnings("unused")
public interface OptionClickEventHandler {
public void onOptionClick(MenuClickEvent event);
}
}
The item menu class
package me.lakan.test;
import me.lakan.util.inventory.InventoryMenu;
import me.lakan.util.inventory.MenuClickEvent;
import me.lakan.util.inventory.MenuOption;
import me.lakan.util.item.ItemBuilder;
import org.apache.commons.lang.Validate;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryType;
public class ItemMenu implements Listener {
private PluginEntry plugin;
private InventoryMenu menu;
// Commands
private TestCommand testCmd;
public ItemMenu(PluginEntry plugin) {
Validate.notNull(this.plugin, "The plugin reference may not be null");
this.plugin = plugin;
this.menu = new InventoryMenu(InventoryType.CHEST, "" + ChatColor.DARK_GRAY + "Abilities", this.plugin);
// Test
this.menu.addOption(1,
new MenuOption(
new ItemBuilder()
.amount(1)
.material(Material.RAW_FISH)
.name(ChatColor.LIGHT_PURPLE + "Test")
.lore(ChatColor.WHITE + "Click me")
.build(),
"TestIdentifier"));
this.testCmd= new TestCmd(this.plugin);
}
public void openFor(Player p) {
this.menu.openFor(p);
}
#EventHandler(priority = EventPriority.NORMAL)
public void onOptionClick(MenuClickEvent e) {
// Test
if (e.getName().equals("TestIdentifier")) {
this.testCmd.executeFor(e.getWhoClicked());
}
}
}
Exception stack trace
[12:48:25] [Server thread/ERROR]: Error occurred while enabling Test v1.0 (Is it up to date?)
java.lang.NoSuchMethodError: me.lakan.util.inventory.InventoryMenu.(Lorg/bukkit/event/inventory/InventoryType;Ljava/lang/String;Lorg/bukkit/plugin/java/JavaPlugin;)V
at me.lakan.test.ItemMenu.(ItemMenu.java:33) ~[?:?]
at me.lakan.test.CommandParser.(CommandParser.java:20) ~[?:?]
at me.lakan.test.PluginEntry.onEnable(PluginEntry.java:21) ~[?:?]
at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:321) ~[spigot_server.jar:git-Spigot-1d14d5f-ba32592]
at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:335) [spigot_server.jar:git-Spigot-1d14d5f-ba32592]
at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:405) [spigot_server.jar:git-Spigot-1d14d5f-ba32592]
at org.bukkit.craftbukkit.v1_8_R2.CraftServer.loadPlugin(CraftServer.java:356) [spigot_server.jar:git-Spigot-1d14d5f-ba32592]
at org.bukkit.craftbukkit.v1_8_R2.CraftServer.enablePlugins(CraftServer.java:316) [spigot_server.jar:git-Spigot-1d14d5f-ba32592]
at net.minecraft.server.v1_8_R2.MinecraftServer.r(MinecraftServer.java:416) [spigot_server.jar:git-Spigot-1d14d5f-ba32592]
at net.minecraft.server.v1_8_R2.MinecraftServer.k(MinecraftServer.java:382) [spigot_server.jar:git-Spigot-1d14d5f-ba32592]
at net.minecraft.server.v1_8_R2.MinecraftServer.a(MinecraftServer.java:337) [spigot_server.jar:git-Spigot-1d14d5f-ba32592]
at net.minecraft.server.v1_8_R2.DedicatedServer.init(DedicatedServer.java:257) [spigot_server.jar:git-Spigot-1d14d5f-ba32592]
at net.minecraft.server.v1_8_R2.MinecraftServer.run(MinecraftServer.java:522) [spigot_server.jar:git-Spigot-1d14d5f-ba32592]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_31]
As you can see the constructor is there and is to my knowledge properly called. So is this error a mistake in my project setup, an API thing, or something entirely different?
The utility classes are in a seperate module and everything works if I paste them into my test plugin module, but not inside the other module. However any other constructor in any other class inside me.lakan.util.inventory can be called normally.
The problem was in the project structure.
For the test artifact, I chose the module output of the util module.
Changing it to the artifact output of the util module fixed it.

using attach(this); in a GUI program

I'm looking at a GUI program made using MVC and they have this method. What does this method do and when will you need to use it?
attach(this);
Here is one of the classes with the method.
import model.*;
import java.awt.*;
import java.text.*;
import javax.swing.*;
public class IncomePanel extends JPanel implements View
{ private Stadium stadium;
private JLabel label;
public IncomePanel(Stadium stadium)
{ this.stadium = stadium;
for (Group group: stadium.seats())
group.attach(this);
setup();
build(); }
private void setup()
{ setBorder(BorderFactory.createLineBorder(Color.blue));
setLayout(new FlowLayout()); }
private void build()
{ label = new JLabel(income());
label.setForeground(Color.blue);
add(label); }
public void update()
{ label.setText(income()); }
private String income()
{ return "Income is $" + twoDec(stadium.income()); }
private String twoDec(double value)
{ DecimalFormat twoD = new DecimalFormat("#0.00");
return twoD.format(value); }
}
Look inside the model package which is part of your project. In there you'll find a file named group.java. It contains the source for the Group class or interface.
All this snippet tells us is that Group's attach method takes an IncomePanel as an argument. If you want to find out what it does with it you have to look at the Group file.

Categories