First, you need a couple of model classes
You'll need an Order
public Order {
private String name;
public Order(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
And a list of orders
public OrderList extends DefaultListModel<Order> {
}
And a cook to cook the orders
public void Cook extends Thread implements ActionListener {
private OrderList waiting;
private OrderList finished;
private boolean keepCooking;
public Cook(OrderList waiting, OrderList finished) {
this.waiting = waiting;
this.finished = finished;
this.keepCooking = false;
}
public void run() {
keepCooking = true;
while (keepCooking) {
if (orders.size() > 0) {
try {
currentOrder = orders.remove(0);
} catch (Exception e) {
// someone else emptied the list
}
}
prepareOrder(order);
if (keepCooking && orders.size() <= 0) {
try {
Thread.sleep(1000);
} catch (Exception e) {
// back to work
}
}
}
}
public void prepareOrder(Order order) {
try {
Thread.sleep(Math.random() % 10000);
finished.add(order);
} catch (Exception e) {
waiting.add(order);
}
}
public void goHome() {
keepCooking = false;
}
}
and you'll need some customers to place the orders
public Customers extends Thread {
private OrderList orders;
public Customers(OrderList orders) {
this.orders = orders;
}
public void run() {
int number = 0;
while (true) {
number++;
try {
Thread.sleep(Math.random() % 10000)
orders.add(new Order(String.format("Order %d", number)));
} catch (Exception e) {
return;
}
}
}
}
Now a component to help configure the Controller
public CloseKitchen extends AbstractAction {
private Cook cook;
public CloseKitchen(Cook cook) {
super("Close Kitchen");
this.cook = cook;
}
public void actionPerformed(ActionEvent e) {
cook.goHome();
}
}
... in some block of code ...
// building the model
OrderList waiting = new OrderList();
OrderList finished = new OrderList();
Cook cook = new Cook(waiting, finished);
Customers customers = new Customers(waiting);
// attaching the view
somePanel.add(new JList(waiting));
somePanel.add(new JList(finished));
// building the controller plug-in
CloseKitchen closeKitchen = new CloseKitchen(cook);
// wiring the plugin into the controller
somePanel.add(new JButton(closeKitchen));
// show the view
somePanel.setVisible(true);
// start the cook and customers
cook.start();
customers.start();
and you will see the orders populate in one list and move to the other. That is, until you click the "Close Kitchen" button, after which the cook will goHome()
and the Customers will keep ordering.
There are many ways to implement the Cook and Customers. I deliberately didn't use a ListDataListener implementation to avoid confusion about what the model needed to use. Basically, the real model doesn't have to use anything swing related for its internal coordination, provided it can be adapted to the correct [List|Table|Button|...]Model
interface.