Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
hi all ......
i have a problem in buer code ...
i make some changes in Book buyer Agent ... & I have a problem in GUI
when execute this code there is nothing appear in GUI interface ...


thanks

//////////////// code...................................

/*************************BuyerAgent**************************\
Java
import jade.core.Agent;
import jade.core.AID;
import jade.core.behaviours.*;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;

public class BookBuyerAgent extends Agent {
	// The title of the book to buy
	private String targetBookTitle;
	// The GUI to interact with the user
  private BookBuyerGui myGui;
	// The list of known seller agents
	private AID[] sellerAgents;
    //  Bank Agents
		private AID bankAgent;
	//  My Balance
		private String MyBalance;
	// Put agent initializations here
	protected void setup() {
		// Create the catalogue
		//catalogue = new Hashtable();
		// Printout a welcome message
		System.out.println("Hallo! Buyer-agent "+getAID().getName()+" is ready.");
		// Show the GUI to interact with the user
					    myGui = new BookBuyerGuiImpl();
					    myGui.setAgent(this);
						myGui.show();
						

		// Get the title of the book to buy as a start-up argument
		//Object[] args = getArguments();
			//if (args != null && args.length > 0) {

			targetBookTitle = (String) args[0];
			myGui.notifyUser("Target book is "+targetBookTitle);
			//System.out.println("Target book is "+targetBookTitle);

			// Create Account of sally buyer
            addBehaviour(new CreateAccount());

			// Add a TickerBehaviour that schedules a request to seller agents every minute
			addBehaviour(new TickerBehaviour(this, 1000) {
				protected void onTick() {
					myGui.notifyUser("Trying to buy "+targetBookTitle);
					//System.out.println("Trying to buy "+targetBookTitle);
					// Update the list of seller agents
					DFAgentDescription template = new DFAgentDescription();
					ServiceDescription sd = new ServiceDescription();
					sd.setType("book-selling");
					template.addServices(sd);
					try {
						DFAgentDescription[] result = DFService.search(myAgent, template);
						myGui.notifyUser("Found the following seller agents:");
						//System.out.println("Found the following seller agents:");
						sellerAgents = new AID[result.length];
						for (int i = 0; i < result.length; ++i) {
							sellerAgents[i] = result[i].getName();
							myGui.notifyUser(sellerAgents[i].getName());
							//System.out.println(sellerAgents[i].getName());
						}
					}
					catch (FIPAException fe) {
						fe.printStackTrace();
					}

					// Perform the request
					myAgent.addBehaviour(new RequestPerformer());
				}
			} );
		}/*
		else {
			// Make the agent terminate
			System.out.println("No target book title specified");
			doDelete();
		}*/
	}

	// Put agent clean-up operations here
	protected void takeDown() {
		// Printout a dismissal message
		//muGui.dispose();
		System.out.println("Buyer-agent "+getAID().getName()+" terminating.");
	}

	/*
	/**********************************************************
	   	//*****************************************************
	*/
	private class CreateAccount extends OneShotBehaviour {
				   private MessageTemplate mt; // The template to receive replies
				   private ACLMessage reply;
				   String myID="";
			 		public void action() {
						//System.out.println("Trying to Search Bank Agent ");
						myGui.notifyUser("Trying to Search Bank Agent ");
						// Update the list of seller agents
						DFAgentDescription template = new DFAgentDescription();
						ServiceDescription sd = new ServiceDescription();
						sd.setType("BANK_AGENT");
						template.addServices(sd);
						try {
							DFAgentDescription[] result = DFService.search(myAgent, template);
							//System.out.println("Bank Agent Found is :");
							myGui.notifyUser("Bank Agent Found is :");
							for (int i = 0; i < result.length; ++i) {
								  bankAgent= result[i].getName();
								  myGui.notifyUser(bankAgent.getName());
								  //System.out.println(bankAgent.getName());
							}
							ACLMessage request = new ACLMessage(ACLMessage.REQUEST);
							request.addReceiver(bankAgent);
						    request.setContent("b");
						    //request.setConversationId("book-trade");
							//request.setReplyWith("request"+System.currentTimeMillis()); // Unique value
						    myAgent.send(request);
						    mt = MessageTemplate.MatchPerformative(ACLMessage.INFORM);
							for(;;){
							reply = myAgent.receive(mt);
						     if(reply!=null)
						          break;
							}

						   if (reply != null) {
								// Reply received
								if (reply.getPerformative() == ACLMessage.INFORM) {
									// This is an ID
									myID = reply.getContent();
									//myGui.notifyUser("Found the following seller agents:");
									System.out.println("The ID Received From Bank Agent is: "+myID.toString());
						//********* getbalance **************
								    MyBalance=getBalance();
								    //myGui.notifyUser("Found the following seller agents:");
								    System.out.println("My Balance Received from bank is ="+MyBalance.toString());
								}
								else
								    //myGui.notifyUser("Found the following seller agents:");
									System.out.println("Reply Performative is  NULL ");
							}
							else
							   //myGui.notifyUser("Found the following seller agents:");
							   System.out.println("Reply Messege is NULL ");
							   start();


					}//try
						catch (FIPAException fe) {
							fe.printStackTrace();
						}
						}
				public String getBalance(){
					String balance="";
					ACLMessage request = new ACLMessage(ACLMessage.QUERY_REF);
					request.addReceiver(bankAgent);
					request.setContent("");
					request.setConversationId("balance");
					request.setReplyWith("QUERY_REF"+System.currentTimeMillis()); // Unique value
					myAgent.send(request);
					mt = MessageTemplate.and(MessageTemplate.MatchConversationId("balance"),
					MessageTemplate.MatchInReplyTo(request.getReplyWith()));
					//ACLMessage reply = myAgent.receive(mt);
					for(;;){
							reply = myAgent.receive(mt);
							 if(reply!=null)
								  break;
							}
					if (reply != null) {
						// Reply received
						if (reply.getPerformative() == ACLMessage.INFORM) {
							// This is an ID
						   balance = reply.getContent();
						   //myGui.notifyUser("Found the following seller agents:");
						   //System.out.println("Messege From Bank is : "+balance);

						}
						else
						   //myGui.notifyUser("Found the following seller agents:");
						   System.out.println("Reply Messege of Balance is NULL ");
					}
					else
					    //myGui.notifyUser("Found the following seller agents:");
					    System.out.println("Reply Performative of Balance is not INFORM ");
					return balance;
				}//get balance

				//************************************ start operation *********************************
												public void start(){

												 mt=MessageTemplate.MatchPerformative(ACLMessage.INFORM);
												      ACLMessage start = myAgent.receive(mt);
															if (start != null) {
																String starts = (String) start.getContent();
														//myGui.notifyUser("Found the following seller agents:");
														System.out.println( myAgent.getLocalName() + " <- " +starts);
															}
										}// end start
				//*******************************************************************************************

			}  // End of inner class CreateAccount


	/**
	   Inner class RequestPerformer.
	   This is the behaviour used by Book-buyer agents to request seller
	   agents the target book.
	 */
	private class RequestPerformer extends Behaviour {
		private AID bestSeller; // The agent who provides the best offer
		private int bestPrice;  // The best offered price
		private int repliesCnt = 0; // The counter of replies from seller agents
		private MessageTemplate mt; // The template to receive replies
		private int step = 0;
		private int quantity;
        private int mony;
        private String rbalance="";
		public void action() {
			switch (step) {
			case 0:
				// Send the cfp to all sellers
				ACLMessage cfp = new ACLMessage(ACLMessage.CFP);
				for (int i = 0; i < sellerAgents.length; ++i) {
					cfp.addReceiver(sellerAgents[i]);
				}
				cfp.setContent(targetBookTitle);
				cfp.setConversationId("book-trade");
				cfp.setReplyWith("cfp"+System.currentTimeMillis()); // Unique value
				myAgent.send(cfp);
				// Prepare the template to get proposals
				mt = MessageTemplate.and(MessageTemplate.MatchConversationId("book-trade"),
						MessageTemplate.MatchInReplyTo(cfp.getReplyWith()));
				step = 1;
				break;
			case 1:
				// Receive all proposals/refusals from seller agents
				ACLMessage reply = myAgent.receive(mt);
				if (reply != null) {
					// Reply received
					if (reply.getPerformative() == ACLMessage.PROPOSE) {
						// This is an offer
						int price = Integer.parseInt(reply.getContent());
						if (bestSeller == null || price < bestPrice) {
							// This is the best offer at present
							bestPrice = price;
							bestSeller = reply.getSender();
						}
					}
					repliesCnt++;
					if (repliesCnt >= sellerAgents.length) {
						// We received all replies
						step = 2;
					}
				}
				else {
					block();
				}
				break;
			case 2:
				// Send the purchase order to the seller that provided the best offer
				ACLMessage order = new ACLMessage(ACLMessage.ACCEPT_PROPOSAL);
				order.addReceiver(bestSeller);
				order.setContent(targetBookTitle);
				order.setConversationId("book-trade");
				order.setReplyWith("order"+System.currentTimeMillis());
				myAgent.send(order);
				// Prepare the template to get the purchase order reply
				mt = MessageTemplate.and(MessageTemplate.MatchConversationId("book-trade"),
						MessageTemplate.MatchInReplyTo(order.getReplyWith()));
				step = 3;
				break;
			case 3:
				// Receive the purchase order reply
				reply = myAgent.receive(mt);
				if (reply != null) {
					// Purchase order reply received
					if (reply.getPerformative() == ACLMessage.INFORM) {
						// Purchase successful. We can terminate
						//myGui.notifyUser("Found the following seller agents:");
						System.out.println(targetBookTitle+" successfully purchased from agent "+reply.getSender().getName());
						//myGui.notifyUser("Found the following seller agents:");
						System.out.println("Price = "+bestPrice);
						myAgent.doDelete();

						// Send the Transfer order to the Banker
						ACLMessage Transefer = new ACLMessage(ACLMessage.QUERY_REF);
						Transefer.addReceiver(bankAgent);
						Transefer.setContent("1,"+bestSeller.getName()+","+bestPrice);
						Transefer.setConversationId("Transefer");
						//Transefer.setReplyWith("Transefer"+System.currentTimeMillis());
						myAgent.send(Transefer);
						//myGui.notifyUser("Found the following seller agents:");
						System.out.println("send transfer to\t"+bankAgent.getLocalName()+Transefer.getContent()+" to buy"+targetBookTitle+"\t mony"+bestPrice);
						//mt = MessageTemplate.and(MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.INFORM)),MessageTemplate.MatchInReplyTo(order.getReplyWith()));

						mt = MessageTemplate.and(MessageTemplate.MatchConversationId("Transefer"),
						    MessageTemplate.MatchPerformative(ACLMessage.INFORM));
						    MessageTemplate.MatchInReplyTo(Transefer.getReplyWith());
						//  ******************
						for(;;){
													reply = myAgent.receive(mt);
												     if(reply!=null)
												          break;
													}

												   if (reply != null) {
														// Reply received
														if (reply.getPerformative() == ACLMessage.INFORM) {
															// This is an ID
															rbalance = reply.getContent();
															//myGui.notifyUser("Found the following seller agents:");
															System.out.println("The ID Received From Bank Agent is: "+rbalance.toString());
												//********* getbalance **************
														   MyBalance=getBalance();
														    //myGui.notifyUser("Found the following seller agents:");
														    System.out.println("My Balance Received from bank is ="+MyBalance.toString());
														}
														else
														    //myGui.notifyUser("Found the following seller agents:");
															System.out.println("Reply Performative is  NULL ");
													}
													else
								//myGui.notifyUser("Found the following seller agents:");
							   System.out.println("Reply Messege is NULL ");

//**********************
					}
					else {
						//myGui.notifyUser("Found the following seller agents:");
						System.out.println("Attempt failed: requested book already sold.");
					}

					step = 4;
				}
				else {
					block();
				}
				break;
			}
		}
public String getBalance(){

					String balance="";
				    ACLMessage reply;
					ACLMessage request = new ACLMessage(ACLMessage.QUERY_REF);
					request.addReceiver(bankAgent);
					request.setContent("");
					request.setConversationId("balance");
					request.setReplyWith("QUERY_REF"+System.currentTimeMillis()); // Unique value
					myAgent.send(request);
					mt = MessageTemplate.and(MessageTemplate.MatchConversationId("balance"),
					MessageTemplate.MatchInReplyTo(request.getReplyWith()));
					//ACLMessage reply = myAgent.receive(mt);
					for(;;){
							reply = myAgent.receive(mt);
							 if(reply!=null)
								  break;
							}
					if (reply != null) {
						// Reply received
						if (reply.getPerformative() == ACLMessage.INFORM) {
							// This is an ID
						   balance = reply.getContent();
						   //myGui.notifyUser("Found the following seller agents:");
						   //System.out.println("Messege From Bank is : "+balance);

						}
						else
						//myGui.notifyUser("Found the following seller agents:");
						   System.out.println("Reply Messege of Balance is NULL ");
					}
					else
					//myGui.notifyUser("Found the following seller agents:");
					    System.out.println("Reply Performative of Balance is not INFORM ");
					return balance;
				}//get balance


		public boolean done() {
			if (step == 2 && bestSeller == null) {
				//myGui.notifyUser("Found the following seller agents:");
				System.out.println("Attempt failed: "+targetBookTitle+" not available for sale");
			}
			return ((step == 2 && bestSeller == null) || step == 4);
		}
	}  // End of inner class RequestPerformer
}



/*****************************BookBuyerGuiImpl********************************\
import jade.gui.TimeChooser;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

import java.util.Date;

/**
J2SE (Swing-based) implementation of the GUI of the agent that
tries to buy books on behalf of its user
*/
public class BookBuyerGuiImpl extends JFrame implements BookBuyerGui {
private BookBuyerAgent myAgent;

private JTextField titleTF, desiredCostTF, maxCostTF, deadlineTF;
private JButton setDeadlineB;
private JButton setCCB, buyB, resetB, exitB;
private JTextArea logTA;

//private Date deadline;

public BookBuyerGuiImpl() {
super();

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
myAgent.doDelete();
}
} );



JPanel rootPanel = new JPanel();
rootPanel.setLayout(new GridBagLayout());
rootPanel.setMinimumSize(new Dimension(330, 125));
rootPanel.setPreferredSize(new Dimension(330, 125));

///////////
// Line 0
///////////
JLabel l = new JLabel("Book to buy:");
l.setHorizontalAlignment(SwingConstants.LEFT);
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(5, 3, 0, 3);
rootPanel.add(l, gridBagConstraints);

titleTF = new JTextField(64);
titleTF.setMinimumSize(new Dimension(222, 20));
titleTF.setPreferredSize(new Dimension(222, 20));
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.anchor = GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new Insets(5, 3, 0, 3);
rootPanel.add(titleTF, gridBagConstraints);


rootPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));

getContentPane().add(rootPanel, BorderLayout.NORTH);


logTA = new JTextArea();
logTA.setEnabled(false);
JScrollPane jsp = new JScrollPane(logTA);
jsp.setMinimumSize(new Dimension(300, 180));
jsp.setPreferredSize(new Dimension(300, 180));
JPanel p = new JPanel();
p.setBorder(new BevelBorder(BevelBorder.LOWERED));
p.add(jsp);
getContentPane().add(p, BorderLayout.CENTER);


p = new JPanel();
buyB = new JButton("Buy");
buyB.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String targetBookTitle = titleTF.getText().trim();
//String title = titleField.getText().trim();
//String quantity = quantityTF.getText().trim();
//myAgent.updateCatalogue(targetBookTitle, Integer.parseInt(quantity));
titleTF.setText("");
//quantityTF.setText("");
// int desiredCost = -1;
//int maxCost = -1;
if (targetBookTitle != null && targetBookTitle.length() > 0) {
// if (quantity != null && quantity.length() > 0) {


}
else {
// No book title specified
JOptionPane.showMessageDialog(BookBuyerGuiImpl.this, "No book title specified", "WARNING", JOptionPane.WARNING_MESSAGE);
}
}
} );
resetB = new JButton("Reset");
resetB.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
titleTF.setText("");
desiredCostTF.setText("");
maxCostTF.setText("");
deadlineTF.setText("");
// deadline = null;
}
} );
exitB = new JButton("Exit");
exitB.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
myAgent.doDelete();
}
} );

buyB.setPreferredSize(resetB.getPreferredSize());
exitB.setPreferredSize(resetB.getPreferredSize());

p.add(buyB);
p.add(resetB);
p.add(exitB);

p.setBorder(new BevelBorder(BevelBorder.LOWERED));
getContentPane().add(p, BorderLayout.SOUTH);

pack();

setResizable(false);
}

public void setAgent(BookBuyerAgent a) {
myAgent = a;
setTitle(myAgent.getName());
}

public void notifyUser(String message) {
logTA.append(message+"\n");
}
}
Posted
Updated 13-Aug-11 2:21am
v2

This is not a question, it's an advertisement for cluelessness. You talk about 'bookbuyeragent' code as if we should know what that is. You dump a ton of code on us. You tell us you have a GUI problem, but not what your problem is. Surely you realise that we can't possibly help you based on this post ?
 
Share this answer
 
Comments
selloma 12-Aug-11 18:17pm    
hi .. thanx for reply ...
when execute this code there is nothing appear in GUI interface ...
OK, so you have edited your question, what a pity you did not take note of Christian's comments and explain where your code is failing and what you think is going wrong. I would suggest you spend some time with your debugger working out exactly where it is going wrong and then come back here with a more specific question.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900