本文介绍了Java的图书买家代理代码中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好...
我在购买人代码中有问题...
我在图书买家代理"中进行了一些更改...我在GUI中有问题
执行此代码时,GUI界面中没有任何内容...


谢谢

///////////////代码 ........... .........

/************************* BuyerAgent *********************** *** \

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**************************\

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 ******************* ************* \
导入jade.gui.TimeChooser;

导入java.awt.*;
导入java.awt.event.*;
导入javax.swing.*;
导入javax.swing.border.*;

导入java.util.Date;

/**
代理的GUI的J2SE(基于SWing)实现,
尝试代表其用户购买书籍
*/
公共类BookBuyerGuiImpl扩展了JFrame实现的BookBuyerGui {
私人BookBuyerAgent myAgent;

私有JTextField titleTF,desiresCostTF,maxCostTF,deadmissionTF;
私有JButton setDeadlineB;
私有JButton setCCB,buyB,resetB,exitB;
私有JTextArea logTA;

//私人日期截止日期;

公共BookBuyerGuiImpl(){
super();

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



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

//////////
//第0行
//////////
JLabel l =新的JLabel(要购买的书:");
l.setHorizo​​ntalAlignment(SwingConstants.LEFT);
GridBagConstraints gridBagConstraints =新的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 =新的JTextField(64);
titleTF.setMinimumSize(new Dimension(222,20));
titleTF.setPreferredSize(new Dimension(222,20));
gridBagConstraints =新的GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.anchor = GridBagConstraints.NORTHWEST;
gridBagConstraints.insets =新的Insets(5,3,0,3);
rootPanel.add(titleTF,gridBagConstraints);


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

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


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


p =新的JPanel();
buyB = new JButton("Buy");
buyB.addActionListener(new ActionListener(){
公共无效actionPerformed(ActionEvent e){
字符串targetBookTitle = titleTF.getText().trim();
//字符串标题= titleField.getText().trim();
//字符串数量=数量TF.getText().trim();
//myAgent.updateCatalogue(targetBookTitle,Integer.parseInt(quantity));
titleTF.setText(");
//quantityTF.setText(");
//int wantedCost = -1;
//int maxCost = -1;
if(targetBookTitle!= null&&targetBookTitle.length()> 0){
//if(quantity!= null&& quantity.length()> 0){


}
其他{
//未指定书名
JOptionPane.showMessageDialog(BookBuyerGuiImpl.this,未指定书名","WARNING",JOptionPane.WARNING_MESSAGE);
}
}
});
resetB = new JButton("Reset");
resetB.addActionListener(new ActionListener(){
公共无效actionPerformed(ActionEvent e){
titleTF.setText(");
requiredCostTF.setText(");
maxCostTF.setText(");
最后期限TF.setText(");
//截止日期= null;
}
});
exitB = new JButton("Exit");
exitB.addActionListener(new ActionListener(){
公共无效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");
}
}




/*****************************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(newWindowAdapter() {
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");
}
}

推荐答案



这篇关于Java的图书买家代理代码中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 09:23