免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2066 | 回复: 0

JADE的booktrading中GUI使用解析 [复制链接]

论坛徽章:
0
发表于 2007-12-27 09:53 |显示全部楼层

                                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中怎么用了八。
               
               
               
               
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/17663/showart_451134.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP