blob: a70d9d450fe3487171a4dbcaa287776a257618f0 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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));
}
}
}
|