Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1280167
  • 博文数量: 135
  • 博客积分: 10588
  • 博客等级: 上将
  • 技术积分: 1325
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-18 11:12
文章分类

全部博文(135)

文章存档

2013年(6)

2012年(3)

2011年(11)

2010年(7)

2009年(14)

2008年(6)

2007年(42)

2006年(46)

分类: Java

2007-12-27 09:53:23

jade的bookTrading中有关于Agent与gui应用界面结合的例子,其实gui在jade中的使用非常简单,主要是要把jade的Agent类当成一个普通类来使用就可以了。如果这个例子看不懂,说明java的学习还要加强一点。
现在我来解析一下,主要是针对BoolSellerAgent类文件和BookSellerGui类文件。大家看BookSellerGui.java的主要框架:
import java.awt.*;//表明要用哪些类来实现gui界面,
import java.awt.event.*;
import javax.swing.*;

/**
  @author Giovanni Caire - TILAB
 */
class BookSellerGui extends JFrame {   
    private BookSellerAgent myAgent;//该Agent作为一个成员,因为在添加图书的时候要调用该对象成员的方法
   
    private JTextField titleField, priceField;
   
    BookSellerGui(BookSellerAgent a) {
        super(a.getLocalName());
       
        myAgent = a;//Agent成员初始化
       
        JPanel p = new JPanel();
        p.setLayout(new GridLayout(2, 2));
        p.add(new JLabel("Book title:"));
        titleField = new JTextField(15);
        p.add(titleField);
        p.add(new JLabel("Price:"));
        priceField = new JTextField(15);
        p.add(priceField);
        getContentPane().add(p, BorderLayout.CENTER);
       
        JButton addButton = new JButton("Add");
        addButton.addActionListener( new ActionListener() {
            public void actionPerformed(ActionEvent ev) {
                try {
                    String title = titleField.getText().trim();
                    String price = priceField.getText().trim();
                    myAgent.updateCatalogue(title, Integer.parseInt(price));//调用该成员的方法对图书数据进行更新
                    titleField.setText("");
                    priceField.setText("");
                }
                catch (Exception e) {
                    JOptionPane.showMessageDialog(BookSellerGui.this, "Invalid values. "+e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        } );
        p = new JPanel();
        p.add(addButton);
        getContentPane().add(p, BorderLayout.SOUTH);
       
        // Make the agent terminate when the user closes
        // the GUI using the button on the upper right corner   
        addWindowListener(new    WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                myAgent.doDelete();//同样是调用某个方法,干什么的自己猜猜
            }
        } );
       
        setResizable(false);
    }
   
    public void show() {
        pack();
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int centerX = (int)screenSize.getWidth() / 2;
        int centerY = (int)screenSize.getHeight() / 2;
        setLocation(centerX - getWidth() / 2, centerY - getHeight() / 2);
        super.show();
    }   
}
然后是卖书者文件的框架:
package examples.bookTrading;

import jade.core.Agent;
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;

import java.util.*;

public class BookSellerAgent extends Agent {
  // The catalogue of books for sale (maps the title of a book to its price)
  private Hashtable catalogue;
  // The GUI by means of which the user can add books in the catalogue
  private BookSellerGui myGui;//注意看是个gui界面类的成员

  // Put agent initializations here
  protected void setup() {
    // Create the catalogue
    catalogue = new Hashtable();

    // Create and show the GUI
    myGui = new BookSellerGui(this);
    myGui.show();//这两句表示当该Agent类一运行,就调用该界面对象的show方法显示出来

    // Register the book-selling service in the yellow pages
    DFAgentDescription dfd = new DFAgentDescription();
    dfd.setName(getAID());
    ServiceDescription sd = new ServiceDescription();
    sd.setType("book-selling");
    sd.setName("JADE-book-trading");
    dfd.addServices(sd);
    try {
      DFService.register(this, dfd);
    }
    catch (FIPAException fe) {
      fe.printStackTrace();
    }
   
    // Add the behaviour serving queries from buyer agents
    addBehaviour(new OfferRequestsServer());

    // Add the behaviour serving purchase orders from buyer agents
    addBehaviour(new PurchaseOrdersServer());
  }

  // Put agent clean-up operations here
  protected void takeDown() {
    // Deregister from the yellow pages
    try {
      DFService.deregister(this);
    }
    catch (FIPAException fe) {
      fe.printStackTrace();
    }
      // Close the GUI
      myGui.dispose();
    // Printout a dismissal message
    System.out.println("Seller-agent "+getAID().getName()+" terminating.");
  }

  /**
     This is invoked by the GUI when the user adds a new book for sale
   */
  public void updateCatalogue(final String title, final int price) {
    addBehaviour(new OneShotBehaviour() {
      public void action() {
        catalogue.put(title, new Integer(price));
        System.out.println(title+" inserted into catalogue. Price = "+price);
      }
    } );
  }
 
    /**
       Inner class OfferRequestsServer.
       This is the behaviour used by Book-seller agents to serve incoming requests
       for offer from buyer agents.
       If the requested book is in the local catalogue the seller agent replies
       with a PROPOSE message specifying the price. Otherwise a REFUSE message is
       sent back.
     */
    private class OfferRequestsServer extends CyclicBehaviour {
      public void action() {
          MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.CFP);
          ACLMessage msg = myAgent.receive(mt);
        if (msg != null) {
          // CFP Message received. Process it
          String title = msg.getContent();
          ACLMessage reply = msg.createReply();
   
          Integer price = (Integer) catalogue.get(title);
          if (price != null) {
            // The requested book is available for sale. Reply with the price
            reply.setPerformative(ACLMessage.PROPOSE);
            reply.setContent(String.valueOf(price.intValue()));
          }
          else {
            // The requested book is NOT available for sale.
            reply.setPerformative(ACLMessage.REFUSE);
            reply.setContent("not-available");
          }
          myAgent.send(reply);
        }
          else {
            block();
          }
      }
    }  // End of inner class OfferRequestsServer
   
    /**
       Inner class PurchaseOrdersServer.
       This is the behaviour used by Book-seller agents to serve incoming
       offer acceptances (i.e. purchase orders) from buyer agents.
       The seller agent removes the purchased book from its catalogue
       and replies with an INFORM message to notify the buyer that the
       purchase has been sucesfully completed.
     */
    private class PurchaseOrdersServer extends CyclicBehaviour {
      public void action() {
          MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.ACCEPT_PROPOSAL);
          ACLMessage msg = myAgent.receive(mt);
        if (msg != null) {
          // ACCEPT_PROPOSAL Message received. Process it
          String title = msg.getContent();
          ACLMessage reply = msg.createReply();
         
          Integer price = (Integer) catalogue.remove(title);
          if (price != null) {
            reply.setPerformative(ACLMessage.INFORM);
            System.out.println(title+" sold to agent "+msg.getSender().getName());
          }
          else {
            // The requested book has been sold to another buyer in the meanwhile .
            reply.setPerformative(ACLMessage.FAILURE);
            reply.setContent("not-available");
          }
          myAgent.send(reply);
        }
          else {
            block();
          }
      }
    }  // End of inner class OfferRequestsServer
}
两个类相互调用以使用gui界面的实质内容我已经标注出来了,其实就跟平常写的java程序是一样的。这下知道gui在jade中怎么用了八。
阅读(5039) | 评论(3) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-07-30 11:48:20

您好,刚开始学习Agent,希望向您学习,我的邮箱wdlwgl@163.com,qq:582800698 希望能和您取得联系,谢谢

chinaunix网友2010-01-17 20:55:28

您好楼主 我是新学习agent的 不知道您的联系方式 qq 邮箱都可以 可以向您请教 谢谢 我的qq 79830517

chinaunix网友2009-05-09 17:11:22

谢谢楼主,我做毕设,找Agent的中文资料找的好辛苦,终于让我碰上了