diff options
Diffstat (limited to 'src/com/vaadin/tests/book/ChatApplication.java')
-rw-r--r-- | src/com/vaadin/tests/book/ChatApplication.java | 83 |
1 files changed, 83 insertions, 0 deletions
diff --git a/src/com/vaadin/tests/book/ChatApplication.java b/src/com/vaadin/tests/book/ChatApplication.java new file mode 100644 index 0000000000..a70d9d450f --- /dev/null +++ b/src/com/vaadin/tests/book/ChatApplication.java @@ -0,0 +1,83 @@ +package com.vaadin.tests.book; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import com.vaadin.Application; +import com.vaadin.ui.Button; +import com.vaadin.ui.ProgressIndicator; +import com.vaadin.ui.Table; +import com.vaadin.ui.TextField; +import com.vaadin.ui.Window; +import com.vaadin.ui.Button.ClickEvent; + +public class ChatApplication extends Application implements + Button.ClickListener { + /* + * ChatApplication instances of different users. Warning: a hack, not safe, + * because sessions can expire. + */ + static List users = new ArrayList(); + + /* Messages as a shared list. */ + static List messages = new ArrayList(); + int localSize = 0; + + /* User interface. */ + Table messageTable = new Table(); + TextField username = new TextField("Username:"); + TextField message = new TextField("Message:"); + + @Override + public void init() { + final Window main = new Window("Chat"); + setMainWindow(main); + setTheme("tests-magi"); + users.add(this); + + main.addComponent(username); + + main.addComponent(messageTable); + messageTable.addContainerProperty("Sender", String.class, ""); + messageTable.addContainerProperty("Message", String.class, ""); + updateTable(); + + main.addComponent(message); + + Button send = new Button("Send"); + send.addListener(this); + main.addComponent(send); + + // Poll for new messages once a second. + ProgressIndicator poller = new ProgressIndicator(); + poller.addStyleName("invisible"); + main.addComponent(poller); + } + + public void buttonClick(ClickEvent event) { + synchronized (users) { + // Create the new message in the shared list. + messages.add(new String[] { + new String((String) username.getValue()), + new String((String) message.getValue()) }); + + // Update the message tables for all users. + for (Iterator i = users.iterator(); i.hasNext();) { + ((ChatApplication) i.next()).updateTable(); + } + } + } + + void updateTable() { + if (localSize == messages.size()) { + return; // No updating needed + } + + // Add new messages to the table + while (localSize < messages.size()) { + messageTable.addItem((Object[]) messages.get(localSize++), + new Integer(localSize - 1)); + } + } +} |