-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGui.java
75 lines (59 loc) · 2.14 KB
/
Gui.java
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
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.subscriptions.Subscriptions;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Gui {
private static int numClicks = 0;
private static void createAndShowGUI() {
final JFrame frame = new JFrame("RxSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel();
frame.getContentPane().add(panel);
final JLabel label = new JLabel("Number of clicks: " + numClicks);
final JButton button = new JButton("click me");
final Observable<ActionEvent> buttonClicks = Observable.create(
new Observable.OnSubscribe<ActionEvent>() {
@Override
public void call(Subscriber<? super ActionEvent> subscriber) {
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
subscriber.onNext(e);
} catch(Throwable t) {
subscriber.onError(t);
}
}
};
button.addActionListener(listener);
subscriber.add(Subscriptions.create(new Action0() {
@Override
public void call() {
button.removeActionListener(listener);
}
}));
}
});
buttonClicks.subscribe(new Action1<ActionEvent>() {
@Override
public void call(ActionEvent x) {
label.setText("Number of clicks: " + ++numClicks);
}
});
panel.add(label);
panel.add(button);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}