/*****************************************************************************
l StockPanel.java
l How to link agent with extra resources
* *****************************************************************************/
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.border.*;
import zeus.util.*;
import zeus.concepts.*;
import zeus.actors.*;
import zeus.actors.event.*;
import zeus.concepts.fn.*;
public class StockPanel extends JPanel implements FactMonitor, ActionListener
{
protected JLabel appleLabel = new JLabel();
protected JLabel orangeLabel = new JLabel();
protected JLabel pearLabel = new JLabel();
protected JLabel bananaLabel = new JLabel();
protected JLabel melonLabel = new JLabel();
protected JButton moreApplesBtn;
protected JButton moreOrangesBtn;
protected JButton morePearsBtn;
protected JButton moreBananasBtn;
protected JButton moreMelonsBtn;
protected JLabel cashLabel;
protected TraderFrontEnd UI;
public StockPanel(TraderFrontEnd frontend) {
UI = frontend;
GridBagLayout gb = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gb);
setBackground(Color.lightGray);
setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
moreApplesBtn = new JButton("Supply");
moreApplesBtn.addActionListener(this);
gbc.insets = new Insets(4,8,4,0);
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
gb.setConstraints(appleLabel,gbc);
add(appleLabel);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(4,16,4,8);
gb.setConstraints(moreApplesBtn, gbc);
add(moreApplesBtn);
moreOrangesBtn = new JButton("Supply");
moreOrangesBtn.addActionListener(this);
gbc.insets = new Insets(4,8,4,0);
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
gb.setConstraints(orangeLabel,gbc);
add(orangeLabel);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(4,16,4,8);
gb.setConstraints(moreOrangesBtn, gbc);
add(moreOrangesBtn);
morePearsBtn = new JButton("Supply");
morePearsBtn.addActionListener(this);
gbc.insets = new Insets(4,8,4,0);
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
gb.setConstraints(pearLabel,gbc);
add(pearLabel);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(4,16,4,8);
gb.setConstraints(morePearsBtn, gbc);
add(morePearsBtn);
moreBananasBtn = new JButton("Supply");
moreBananasBtn.addActionListener(this);
gbc.insets = new Insets(4,8,4,0);
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
gb.setConstraints(bananaLabel,gbc);
add(bananaLabel);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(4,16,4,8);
gb.setConstraints(moreBananasBtn, gbc);
add(moreBananasBtn);
moreMelonsBtn = new JButton("Supply");
moreMelonsBtn.addActionListener(this);
gbc.insets = new Insets(4,8,4,0);
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
gb.setConstraints(melonLabel,gbc);
add(melonLabel);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(4,16,4,8);
gb.setConstraints(moreMelonsBtn, gbc);
add(moreMelonsBtn);
Fact[] tmp = UI.agent.ResourceDb().all(OntologyDb.MONEY);
double cash = 0;
for(int i = 0; i < tmp.length; i++ ) {
tmp[i].resolve(new Bindings());
PrimitiveNumericFn numFn =
(PrimitiveNumericFn)tmp[i].getFn(OntologyDb.AMOUNT);
cash += numFn.doubleValue();
}
cashLabel = new JLabel("Bank Balance: " + Misc.decimalPlaces(cash,2));
cashLabel.setFont(new Font("Helvetica",Font.PLAIN, 12));
gbc.insets = new Insets(4,8,4,0);
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
gb.setConstraints(cashLabel, gbc);
add(cashLabel);
UI.agent.ResourceDb().addFactMonitor(this,
FactEvent.ADD_MASK|FactEvent.DELETE_MASK, true);
}
protected void update(Fact f) {
Fact[] tmp = UI.agent.ResourceDb().all(f.getType());
int num = 0;
for(int i = 0; i < tmp.length; i++ )
num += tmp[i].getNumber();
if (f.getType().equals("apple"))
appleLabel.setText("Boxes of apples in stock: " + num);
else if (f.getType().equals("orange"))
orangeLabel.setText("Boxes of oranges in stock: " + num);
else if (f.getType().equals("pear"))
pearLabel.setText("Boxes of pears in stock: " + num);
else if (f.getType().equals("banana"))
bananaLabel.setText("Boxes of bananas in stock: " + num);
else if (f.getType().equals("melon"))
melonLabel.setText("Boxes of melons in stock: " + num);
}
public void actionPerformed(ActionEvent evt) {
String fruit = null;
if (evt.getSource() == moreApplesBtn)
fruit = "apple";
if (evt.getSource() == moreOrangesBtn)
fruit = "orange";
if (evt.getSource() == morePearsBtn)
fruit = "pear";
if (evt.getSource() == moreBananasBtn)
fruit = "banana";
if (evt.getSource() == moreMelonsBtn)
fruit = "melon";
UI.display("A box of " + fruit + "s arrives.");
Fact[] tmp = UI.agent.ResourceDb().all(fruit);
if ( tmp.length > 0 ) {
Fact f2 = new Fact(tmp[0]);
int no = f2.getNumber();
f2.setNumber(++no);
UI.agent.ResourceDb().modify(tmp[0], f2);
}
}
public void factAddedEvent(FactEvent event) {
Fact fact = event.getFact();
if ( fact.getType().equals(OntologyDb.MONEY) ) {
Fact[] tmp = UI.agent.ResourceDb().all(OntologyDb.MONEY);
double cash = 0;
for(int i = 0; i < tmp.length; i++ ) {
tmp[i].resolve(new Bindings());
PrimitiveNumericFn numFn =
(PrimitiveNumericFn)tmp[i].getFn(OntologyDb.AMOUNT);
cash += numFn.doubleValue();
}
cashLabel.setText("Bank Balance: " + Misc.decimalPlaces(cash,2));
}
else
update(fact);
}
public void factModifiedEvent(FactEvent event) {}
public void factAccessedEvent(FactEvent event) {}
public void factDeletedEvent(FactEvent event) {
Fact fact = event.getFact();
if ( fact.getType().equals(OntologyDb.MONEY) ) {
Fact[] tmp = UI.agent.ResourceDb().all(OntologyDb.MONEY);
double cash = 0;
for(int i = 0; i < tmp.length; i++ ) {
tmp[i].resolve(new Bindings());
PrimitiveNumericFn numFn =
(PrimitiveNumericFn)tmp[i].getFn(OntologyDb.AMOUNT);
cash += numFn.doubleValue();
}
cashLabel.setText("Bank Balance: " + Misc.decimalPlaces(cash,2));
}
else
update(fact);
}
}
/**************************************************************************
* TraderFrontEnd.java
* Window to implement trade
**************************************************************************/
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.border.*;
import zeus.util.*;
import zeus.concepts.*;
import zeus.gui.fields.*;
import zeus.actors.*;
import zeus.actors.event.*;
import zeus.generator.util.*;
public class TraderFrontEnd extends JFrame
implements WindowListener, ConversationMonitor {
// root class for GUI
protected JTabbedPane tabbedPane;
protected JPanel sellPanel;
protected JPanel buyPanel;
protected JPanel stockPanel;
public JTextArea infoArea;
public AgentContext agent;
public JScrollPane scrollPane;
public TraderFrontEnd(AgentContext ac) {
agent = ac;
setTitle(agent.whoami() + " Trade Window");
addWindowListener(this);
agent.Engine().addConversationMonitor(this,
ConversationEvent.INITIATE_MASK | ConversationEvent.CONTINUE_MASK);
getContentPane().setBackground(java.awt.Color.gray);
String path = "gifs" + System.getProperty("file.separator");
ImageIcon icon = new ImageIcon(path + "banana.gif");
setIconImage(icon.getImage());
GridBagLayout gridBagLayout = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
getContentPane().setLayout(gridBagLayout);
JLabel header = new JLabel(new ImageIcon(path + "header.gif")) {
public void paint(Graphics g) {
Dimension size = getSize();
g.setColor(java.awt.Color.white);
g.fillRect(0, 0, size.width, size.height);
getIcon().paintIcon(this, g, 0, 0);
}
};
header.setBorder(new BevelBorder(BevelBorder.RAISED));
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.NORTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = gbc.weighty = 0;
gbc.insets = new Insets(0,0,0,0);
((GridBagLayout)getContentPane().getLayout()).setConstraints(header, gbc);
getContentPane().add(header);
infoArea = new JTextArea(6,60);
infoArea.setForeground(Color.black);
infoArea.setBackground(Color.white);
infoArea.setEditable(true);
scrollPane = new JScrollPane(infoArea);
scrollPane.setBorder(new BevelBorder(BevelBorder.LOWERED));
scrollPane.setPreferredSize(new Dimension(300,100));
infoArea.setText(agent.whoami() + " is awaiting your instructions...\n");
infoArea.setCaretPosition(infoArea.getDocument().getLength());
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = gbc.weighty = 0;
gbc.insets = new Insets(8,8,0,8);
((GridBagLayout)getContentPane().getLayout()).setConstraints(scrollPane, gbc);
getContentPane().add(scrollPane);
tabbedPane = new JTabbedPane();
sellPanel = new TradePanel(false, this);
buyPanel = new TradePanel(true, this);
stockPanel = new StockPanel(this);
tabbedPane.addTab("Inventory", stockPanel);
tabbedPane.addTab("Sell Fruit", sellPanel);
tabbedPane.addTab("Buy Fruit", buyPanel);
tabbedPane.setSelectedIndex(0);
tabbedPane.setTabPlacement(JTabbedPane.BOTTOM);
gbc.anchor = GridBagConstraints.SOUTH;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = gbc.weighty = 1;
gbc.insets = new Insets(8,8,0,8);
((GridBagLayout)getContentPane().getLayout()).setConstraints(tabbedPane, gbc);
getContentPane().add(tabbedPane);
pack();
setResizable(false);
show();
}
public void windowClosed(WindowEvent event) {}
public void windowDeiconified(WindowEvent event) {}
public void windowIconified(WindowEvent event) {}
public void windowActivated(WindowEvent event) {}
public void windowDeactivated(WindowEvent event) {}
public void windowOpened(WindowEvent event) {}
public void windowClosing(WindowEvent event) {
this.setVisible(false);
this.dispose();
System.exit(0);
}
public void display(String message)
{
infoArea.append(message + "\n");
infoArea.setCaretPosition(infoArea.getDocument().getLength());
}
public void conversationInitiatedEvent(ConversationEvent event) {
String correspondent = event.getReceiver();
String mode = " to ";
if (correspondent.equals(agent.whoami()))
{
correspondent = event.getSender();
mode = " from ";
}
Goal g = (Goal)(event.getData().elementAt(0));
double cost = g.getCost();
String f = g.getFactType();
display("Conversation started...");
display("[" + event.getMessageType() + "]" + mode + correspondent +
" >> " + f + " @ " + Misc.decimalPlaces(cost,3));
}
public void conversationContinuedEvent(ConversationEvent event) {
String correspondent = event.getReceiver();
String mode = " to ";
if (correspondent.equals(agent.whoami())) {
correspondent = event.getSender();
mode = " from ";
}
if ( event.isGoalEventType() ) {
Goal g = (Goal)(event.getData().elementAt(0));
double cost = g.getCost();
String f = g.getFactType();
display("[" + event.getMessageType() + "]" + mode + correspondent +
" >> " + f + " @ " + Misc.decimalPlaces(cost,3));
}
else {
Fact f = (Fact)(event.getData().elementAt(0));
display("[" + event.getDataType() + "]" + mode + correspondent);
}
}
}
class TradePanel extends JPanel implements ActionListener, FactSelector
{
//Panel to choose goods
protected FactDialog factWin;
protected NameField fruitField;
protected WholeNumberField askPriceField;
protected WholeNumberField timeField;
protected JButton chooseBtn;
protected JButton tradeBtn;
protected TraderFrontEnd UI;
protected boolean buying;
public TradePanel(boolean b, TraderFrontEnd frontend)
{
buying = b;
UI = frontend;
GridBagLayout gb = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gb);
setBackground(Color.lightGray);
setPreferredSize(new Dimension(360,220));
setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
askPriceField = new WholeNumberField(0, 9999);
askPriceField.setBackground(Color.white);
askPriceField.setPreferredSize(new Dimension(60,20));
askPriceField.setValue(10); // or read value from database
timeField = new WholeNumberField(0, 9999);
timeField.setBackground(Color.white);
timeField.setPreferredSize(new Dimension(60,20));
timeField.setValue(3);
fruitField = new NameField(7);
fruitField.setBackground(Color.white);
chooseBtn = new JButton("Choose");
chooseBtn.addActionListener(this);
JLabel label0 = new JLabel("Commodity to Trade: ");
label0.setFont(new Font("Helvetica",Font.PLAIN, 12));
label0.setToolTipText("The type of fruit that will be traded");
gbc.insets = new Insets(4,8,4,0);
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
gb.setConstraints(label0,gbc);
add(label0);
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.insets = new Insets(4,8,4,8);
gb.setConstraints(fruitField, gbc);
add(fruitField);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(4,8,4,8);
gb.setConstraints(chooseBtn, gbc);
add(chooseBtn);
String q = "Reserve price: ";
if (buying) q = "Maximum offer price: ";
JLabel label1 = new JLabel(q);
label1.setFont(new Font("Helvetica",Font.PLAIN, 12));
label1.setToolTipText("The initial offer price");
gbc.insets = new Insets(4,8,4,0);
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
gb.setConstraints(label1,gbc);
add(label1);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.NONE;
gbc.insets = new Insets(4,8,4,8);
gb.setConstraints(askPriceField, gbc);
add(askPriceField);
JLabel label3 = new JLabel("Deadline (time-grains): ");
label3.setFont(new Font("Helvetica",Font.PLAIN, 12));
label3.setToolTipText("The deadline by which trading should have concluded");
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.insets = new Insets(4,8,4,0);
gb.setConstraints(label3, gbc);
add(label3);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.NONE;
gbc.insets = new Insets(4,8,4,8);
gbc.weightx = 1;
gb.setConstraints(timeField, gbc);
add(timeField);
tradeBtn = new JButton("Trade");
tradeBtn.addActionListener(this);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.NONE;
gbc.insets = new Insets(16,8,8,8);
gbc.weightx = 1;
gb.setConstraints(tradeBtn, gbc);
add(tradeBtn);
factWin = new FactDialog((Frame)SwingUtilities.getRoot(this),
UI.agent.OntologyDb());
}
public void factSelected(String[] names)
{
// Show selected item and send its value
String str = names[0];
if (str.equals("ZeusFact") || str.equals("Money")) return;
fruitField.setText(str);
}
public void actionPerformed(ActionEvent evt)
{
if (UI.agent == null ) return;
if (evt.getSource() == chooseBtn)
{
factWin.setLocationRelativeTo(chooseBtn);
factWin.display(this);
}
else if (evt.getSource() == tradeBtn)
{
// trade button pressed: do some error checking first
String fruit = fruitField.getText();
if (!UI.agent.OntologyDb().hasFact(fruit))
{
UI.display("** Error: " + fruit + " does not exist in the ontology.");
return;
}
Fact[] tmp = UI.agent.ResourceDb().all(fruit);
if (!buying && tmp[0].getNumber() == 0)
{
UI.display("Ooops, we're out of " + tmp[0].getType() + "s !");
return;
}
//????
Long askl = askPriceField.getValue();
Long timel = timeField.getValue();
int ask = (int)askl.longValue();
int time = (int)timel.longValue();
if (buying)
beginBuy(fruit, ask, time);
else
beginSell(fruit, ask, time);
}
}
public void beginBuy(String fruit, int ask, int time)
{
UI.display("\nAttempting to buy: " + fruit);
UI.display("My preferences: price= " + ask + ", within " + time + " time-grains");
Fact fact = UI.agent.OntologyDb().getFact(Fact.VARIABLE, fruit);
fact.setNumber(1);
int now = (int)UI.agent.now();
Goal g = new Goal(UI.agent.newId("goal"), fact, now+time, ask,
UI.agent.whoami(), (double)(now+time-0.5));
UI.agent.Engine().buy(g);
}
public void beginSell(String fruit, int ask, int time)
{
UI.display("\nAttempting to sell: " + fruit);
UI.display("My preferences: price= " + ask + ", within " + time + " time-grains");
Fact fact = UI.agent.OntologyDb().getFact(Fact.VARIABLE, fruit);
fact.setNumber(1);
int now = (int)UI.agent.now();
Goal g = new Goal(UI.agent.newId("goal"), fact, now+time, ask,
UI.agent.whoami(), (double)(0));
UI.agent.Engine().sell(g);
}
}
/**************************************************************************
*It's interface of Tom
**************************************************************************/
import zeus.actors.*;
import zeus.agents.*;
public class TomUI implements ZeusExternal
{
public void exec(AgentContext agent)
{
TraderFrontEnd thiswin=new TraderFrontEnd(agent);
}
public void showMsg(String message) {}
public static void main(String[] args)
{
TomUI win=new TomUI();
win.exec(null);
}
}
/*******************************************************************************
It's the interface of Jack
******************************************************************************/
import zeus.actors.*;
import zeus.agents.*;
public class JackUI implements ZeusExternal
{
public void exec(AgentContext agent)
{
TraderFrontEnd thiswin=new TraderFrontEnd(agent);
}
public void showMsg(String message) {}
public static void main(String[] args)
{
JackUI win=new JackUI();
win.exec(null);
}
}
[Return to Jie Bao's Homepage]