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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
package UI;
import Client.Book;
import Client.SocketClient;
import UI.Components.BooksList;
import UI.Components.LoginPanel;
import org.json.JSONException;
import javax.swing.*;
import java.awt.*;
public class MainWindow extends JFrame {
public static String url = "http://localhost:8080";
public static int userId = 0;
private LoginPanel loginPanel;
public MainWindow() {
this.setTitle("User Panel - Library Management System");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(650, 500);
this.setResizable(false);
this.setLocationRelativeTo(null);
CardLayout cardLayout = new CardLayout();
JPanel cardPanel = new JPanel(cardLayout);
loginPanel = new LoginPanel();
loginPanel.loginButton.addActionListener(e -> {
if (SocketClient.socket == null) {
new SocketClient(url);
SocketClient.socket.connect();
}
login(cardLayout, cardPanel);
});
loginPanel.signUpButton.addActionListener(e -> {
if (SocketClient.socket == null) {
new SocketClient(url);
SocketClient.socket.connect();
}
loginPanel.statusLabel.setText("Attempting to Sign Up...");
SocketClient.socket.emit("signUp",
"{" +
"\"userName\": \"" + loginPanel.usernameInput.getValue() + "\"," +
"\"password\": \"" + loginPanel.passwordInput.getValue() + "\"" +
"}");
SocketClient.socket.on("signedUp", data -> {
this.login(cardLayout, cardPanel);
});
SocketClient.socket.on("signUpFailed", data -> {
loginPanel.statusLabel.setText("Sign Up Failed");
});
});
cardPanel.add(loginPanel);
cardPanel.add(new BooksList());
this.add(cardPanel);
}
private void login(CardLayout cardLayout, JPanel cardPanel) {
SocketClient.socket.emit("login",
"{" +
"\"userName\": \"" + loginPanel.usernameInput.getValue() + "\"," +
"\"password\": \"" + loginPanel.passwordInput.getValue() + "\"" +
"}");
SocketClient.socket.on("loginFailed", data -> {
loginPanel.statusLabel.setText("Failed to Log In. Check Username or Password.");
});
SocketClient.socket.on("loggedIn", data -> {
MainWindow.userId = (int) data[0];
SocketClient.socket.on("allBooksList", d -> {
try {
BooksList.refreshBooks(Book.fromObjects(d));
} catch (JSONException ex) {
throw new RuntimeException(ex);
}
});
SocketClient.socket.on("booksUpdated", d -> {
try {
BooksList.refreshBooks(Book.fromObjects(d));
} catch (JSONException ex) {
throw new RuntimeException(ex);
}
});
SocketClient.socket.emit("getAllBooks");
cardLayout.next(cardPanel);
});
}
}
|