0% found this document useful (0 votes)
28 views40 pages

Check

Uploaded by

23020651
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views40 pages

Check

Uploaded by

23020651
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 40

package com.hat.

view;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import javax.swing.table.DefaultTableModel;

import com.hat.controller.InitInformation;
import com.hat.model.BookSearchApp;
import com.hat.model.BorrowedDocument;
import com.hat.model.DatabaseConnection;
import com.hat.model.Document;
import com.hat.model.PublicUser;
import com.hat.model.Student;
import com.hat.model.User;
import com.hat.model.ValidationUtils;

public class adminUI extends JFrame {


Color colorBackground = new Color(170, 207, 224);
Color colorButton = new Color(198, 233, 240);
Color hoverColor = new Color(150, 200, 210);
ImageIcon homeIcon;
ImageIcon bookIcon;
ImageIcon notificationIcon;
ImageIcon userIcon;
ImageIcon infoIcon;
ImageIcon borrowBookIcon;
ImageIcon background;
ImageIcon returnedBookIcon;
ImageIcon edit;
private JPanel ChatPanel;
private JPanel borrowedBookContainer;
private JPanel borrowedBookPanel;
private JPanel notificationContainer;
private final CardLayout cardLayout;
private CardLayout bookCardLayout;
private CardLayout userCardLayout;
private final JPanel contentPane;
private JPanel bookContentPane;
private JPanel userContentPane;
private JPanel homePanel;
private JPanel bookPanel;
private JPanel sidebar;
private JPanel userPanel;
private JPanel detailPanel;
JPanel foundDocumentsPanel;
ActionListener buttonListener;
private JButton homeButton;
private JButton bookButton;
private JButton userButton;
private JButton logoutButton;
private JButton manageButton;
private JButton chatButton;
private RoundCheckBox checkbox1;
private RoundCheckBox checkbox2;
private RoundCheckBox studentBox;
private RoundCheckBox publicUserBox;

private Map<String, RoundedTextField> textFieldMap;


private List<Document> foundDocuments;
private static PublicUser publicUser;
private static Student student;
private DefaultTableModel model;
private JTable table;
private BookSearchApp bookSearchApp;
private static final String[] STUDENT_COLUMNS = {"ID", "Name", "Date of Birth",
"Address", "Email", "Phone",
"Account", "Password", "Faculty", "Major", "Student ID"};
private static final String[] PUBLIC_USER_COLUMNS = {"ID", "Name", "Date of
Birth", "Address", "Email", "Phone",
"Account", "Password", "Identity Card", "Job"};
private static final String[] USER_COLUMNS = {"ID", "Name", "Date of Birth",
"Address", "Email", "Phone",
"Account", "Password"};

public adminUI() {
String[] columnNames = {"ID", "Name", "Date of Birth", "Address", "Email",
"Phone", "Account", "Password"};
model = new DefaultTableModel(columnNames, 0);
table = new JTable(model);
setColumnWidths(table, USER_COLUMNS);
bookSearchApp = new BookSearchApp();
JPanel mainPanel = new JPanel(new BorderLayout());
setTitle("Custom UI");
setSize(1000, 700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

buttonListener = new adminUI.ButtonActionListener();


cardLayout = new CardLayout();
contentPane = new JPanel(cardLayout);
textFieldMap = new HashMap<>();
upImage();

createHomePanel();
createUserManagement();
createBookManagement();
createNotificationPanel();
createBorrowedBookList();

contentPane.add(homePanel, "home");
contentPane.add(ChatPanel, "ChatPanel");
contentPane.add(bookPanel, "bookManagement");
contentPane.add(userPanel, "userManagement");
contentPane.add(borrowedBookPanel, "borrowedBookList");

createSideBar();

mainPanel.add(sidebar, BorderLayout.WEST);
mainPanel.add(contentPane, BorderLayout.CENTER);
add(mainPanel);
}

private void setColumnWidths(JTable table, String[] columns) {


int[] widths;
if (columns == USER_COLUMNS) {
widths = new int[]{25, 150, 100, 200, 150, 100, 100, 100};
} else if (columns == STUDENT_COLUMNS) {
widths = new int[]{25, 150, 100, 200, 150, 100, 100, 100, 100, 100,
100};
} else if (columns == PUBLIC_USER_COLUMNS) {
widths = new int[]{25, 150, 100, 200, 150, 100, 100, 100, 100, 100};
} else {
return;
}
for (int i = 0; i < columns.length; i++) {
table.getColumnModel().getColumn(i).setPreferredWidth(widths[i]);
}
}

private void createHomePanel() {


homePanel = new JPanel();
homePanel.setBackground(Color.WHITE);
homePanel.setLayout(new BorderLayout());
JPanel searchPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 40, 0, 0);
RoundedTextField searchField = new RoundedTextField(40, 30, "search");
searchField.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
searchField.setBackground(new Color(198, 233, 240));
searchPanel.setOpaque(false);
searchPanel.add(searchField, gbc);
gbc.insets = new Insets(15, 10, 0, 0);
RoundedButton searchButton = createButton(35, 17, "Search", 100, 35,
colorButton, hoverColor, false);
searchPanel.add(searchButton, gbc);

searchField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
SwingUtilities.invokeLater(() -> {
// Tạo và thêm loadingPanel vào homePanel trước khi bắt đầu
tìm kiếm
MovingImagePanel loadingPanel = new MovingImagePanel();

// Đảm bảo homePanel sử dụng BorderLayout


if (!(homePanel.getLayout() instanceof BorderLayout)) {
homePanel.setLayout(new BorderLayout());
}

// Xóa component cũ trong CENTER


Component centerComponent = ((BorderLayout)
homePanel.getLayout())
.getLayoutComponent(BorderLayout.CENTER);
if (centerComponent != null) {
homePanel.remove(centerComponent);
}

// Thêm loadingPanel vào CENTER


homePanel.add(loadingPanel, BorderLayout.CENTER);

// Cập nhật giao diện để hiển thị loadingPanel ngay lập tức
homePanel.revalidate();
homePanel.repaint();

// Tạo SwingWorker để tìm kiếm trong nền


SwingWorker<JPanel, Void> worker = new SwingWorker<JPanel,
Void>() {
@Override

protected JPanel doInBackground() throws Exception {

long start = System.currentTimeMillis();


JPanel resultPanel =
bookSearchApp.initialize(searchField.getText());
long end = System.currentTimeMillis();
System.out.println("Time to execute search: " +
(end - start) + "ms");
return resultPanel;
}

@Override
protected void done() {
try {
// Lấy kết quả từ SwingWorker
JPanel resultPanel = get(); // Nhận JPanel kết
quả tìm kiếm từ doInBackground

// Tạo Timer để xóa loadingPanel sau 1 giây và


thêm resultPanel
Timer timer = new Timer(1000, e -> {
// Xóa loadingPanel
Component centerComponent = ((BorderLayout)
homePanel.getLayout())
.getLayoutComponent(BorderLayout.CE
NTER);
if (centerComponent != null) {
homePanel.remove(centerComponent); //
Xóa loadingPanel
}

// Thêm resultPanel vào CENTER


homePanel.add(resultPanel,
BorderLayout.CENTER);

// Cập nhật giao diện


homePanel.revalidate();
homePanel.repaint();
});

// Đảm bảo Timer chỉ chạy một lần


timer.setRepeats(false);
timer.start();
} catch (Exception ex) {
ex.printStackTrace(); // Xử lý lỗi nếu có
}
}

};

worker.execute(); // Thực thi worker


});
}
}
});

homePanel.add(searchPanel, BorderLayout.NORTH);

JPanel backgroundPanel = new JPanel();


backgroundPanel.setBackground(Color.WHITE);
backgroundPanel.setLayout(null);
JLabel backgroundLabel = new JLabel(background);
backgroundLabel.setBounds(200, 70, 510, 380);
backgroundPanel.add(backgroundLabel);
homePanel.add(backgroundPanel, BorderLayout.CENTER);
}

private void createUserManagement() {


userCardLayout = new CardLayout();
userContentPane = new JPanel(userCardLayout);
userPanel = new JPanel();
userPanel.setLayout(new BorderLayout());
userPanel.setBackground(Color.WHITE);

JPanel searchPanel = new JPanel(new GridBagLayout());


GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 40, 30, 0);
RoundedTextField searchField = new RoundedTextField(40, 30, "Search");
searchField.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
searchField.setBackground(new Color(198, 233, 240));
searchPanel.setOpaque(false);
searchPanel.add(searchField, gbc);
gbc.insets = new Insets(15, 10, 30, 0);
RoundedButton searchButton = createButton(35, 17, "Search", 100, 35,
colorButton, hoverColor, false);
searchPanel.add(searchButton, gbc);
searchField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
// Kiểm tra nếu phím Enter được nhấn
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
searchButton.doClick();
}
}
});

// addUserPanelắng nghe sự kiện click vào nút "Search"

userPanel.add(searchPanel, BorderLayout.NORTH);

JPanel userListPanel = new JPanel(new GridBagLayout());


gbc.insets = new Insets(0, 0, 0, 0);
gbc.gridx = 0;
gbc.gridy = 0;
userListPanel.setBackground(Color.WHITE);

// Define column names matching user table structure


String[] columnNames = {
"ID",
"Name",
"Date of Birth",
"Address",
"Email",
"Phone Number",
"Account",
"Password"
};

// Create empty data array for initial table


String[][] data = new String[InitInformation.users.size()][8];

for (int i = 0; i < InitInformation.users.size(); i++) {


data[i][0] = String.valueOf(InitInformation.users.get(i).getId());
data[i][1] = InitInformation.users.get(i).getName();
data[i][2] = InitInformation.users.get(i).getDateOfBirth();
data[i][3] = InitInformation.users.get(i).getAddress();
data[i][4] = InitInformation.users.get(i).getEmail();
data[i][5] = InitInformation.users.get(i).getPhoneNumber();
data[i][6] = InitInformation.users.get(i).getAccount();
data[i][7] = InitInformation.users.get(i).getPassword();
}

// Create table model with column names


DefaultTableModel model = new DefaultTableModel(data, columnNames) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
searchButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String searchText = searchField.getText();
if (searchText.isEmpty()) {
JOptionPane.showMessageDialog(null, "Please enter a search
query.");
return;
}
studentBox.setSelected(false);
publicUserBox.setSelected(false);

model.setColumnIdentifiers(USER_COLUMNS); // Revert to default user


columns
List<User> users =
DatabaseConnection.getUserBySubstring(searchText);
System.out.println(users.size());
loadUsersToTable(users, model); // Load users into table
setColumnWidths(table, USER_COLUMNS); // Set column widths
userListPanel.revalidate(); // Update UI
userListPanel.repaint();

}
});

// Create table with model


JTable table = new JTable(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// table.setModel(model);

// Set preferred width for each column


table.getColumnModel().getColumn(0).setPreferredWidth(50); // ID
table.getColumnModel().getColumn(1).setPreferredWidth(150); // Name
table.getColumnModel().getColumn(2).setPreferredWidth(100); // Date of
Birth
table.getColumnModel().getColumn(3).setPreferredWidth(200); // Address
table.getColumnModel().getColumn(4).setPreferredWidth(150); // Email
table.getColumnModel().getColumn(5).setPreferredWidth(100); // Phone
table.getColumnModel().getColumn(6).setPreferredWidth(100); // Account
table.getColumnModel().getColumn(7).setPreferredWidth(100); // Password

// Tạo JScrollPane và thêm JTable vào JScrollPane


JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(600, 330));

scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// Kiểm tra sự kiện nhấn đúp chuột
if (e.getClickCount() == 2) {
int selectedRow = table.getSelectedRow(); // Lấy hàng được chọn
if (selectedRow != -1) { // Kiểm tra nếu hàng hợp lệ
// Lấy dữ liệu từ hàng
try {
Object id = table.getValueAt(selectedRow, 0);
int userId = Integer.parseInt(id.toString());
User user = DatabaseConnection.getUserById(userId);
if (user != null) {
if (detailPanel != null) {
userContentPane.remove(detailPanel);
}
createDetailPanel(user, model);
userContentPane.add(detailPanel, "detail");
userCardLayout.show(userContentPane, "detail");
} else {
System.out.println("Không tìm thấy User với ID: " +
userId);
}
} catch (Exception ex) {
ex.printStackTrace(); // In lỗi chi tiết để xác định
vấn đề
}

}
}
}
});

userListPanel.add(scrollPane);
gbc.gridx = 0;
gbc.gridy = 10;
gbc.insets = new Insets(10, -200, 0, 0);
studentBox = new RoundCheckBox("student");
userListPanel.add(studentBox, gbc);
gbc.insets = new Insets(10, 200, 0, 10);
publicUserBox = new RoundCheckBox("public user");
userListPanel.add(publicUserBox, gbc);

studentBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
publicUserBox.setSelected(false); // Deselect publicUserBox if
studentBox is selected
model.setColumnIdentifiers(STUDENT_COLUMNS); // Update table
columns
loadStudentsToTable(DatabaseConnection.getAllStudents(),
model); // Load students into table
setColumnWidths(table, STUDENT_COLUMNS); // Set column widths
} else if (e.getStateChange() == ItemEvent.DESELECTED) {
model.setColumnIdentifiers(USER_COLUMNS); // Revert to default
user columns
loadUsersToTable(DatabaseConnection.getAllUsers(), model); //
Load users into table
setColumnWidths(table, USER_COLUMNS); // Set column widths
}
userListPanel.revalidate(); // Update UI
userListPanel.repaint();
}
});
publicUserBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
studentBox.setSelected(false); // Deselect studentBox if
publicUserBox is selected
model.setColumnIdentifiers(PUBLIC_USER_COLUMNS); // Update
table columns
loadPublicUsersToTable(DatabaseConnection.getAllPublicUsers(),
model); // Load public users into
// table
setColumnWidths(table, PUBLIC_USER_COLUMNS); // Set column
widths
} else if (e.getStateChange() == ItemEvent.DESELECTED) {
model.setColumnIdentifiers(USER_COLUMNS); // Revert to default
user columns
loadUsersToTable(DatabaseConnection.getAllUsers(), model); //
Load users into table
setColumnWidths(table, USER_COLUMNS); // Set column widths
}
userListPanel.revalidate(); // Update UI
userListPanel.repaint();
}
});

gbc.gridx = 1;
gbc.gridy = 11;
gbc.insets = new Insets(10, -450, 30, 10);
RoundedButton addButton = createButton(30, 17, "Add user", 120, 30,
colorBackground, hoverColor, false);
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
userCardLayout.show(userContentPane, "addUser");
}
});
userListPanel.add(addButton, gbc);
gbc.insets = new Insets(10, -140, 30, 10);
RoundedButton removeUserButton = createButton(30, 17, "Remove user", 150,
30, colorBackground, hoverColor,
false);

removeUserButton.addActionListener(e -> {
int selectedRow = table.getSelectedRow();
if (selectedRow >= 0) {
// Get user ID and name from selected row
int userId = Integer.parseInt(table.getValueAt(selectedRow,
0).toString());
String userName = table.getValueAt(selectedRow, 1).toString();

// Show confirmation dialog


int confirm = JOptionPane.showConfirmDialog(
null,
"Are you sure you want to delete user: " + userName + "?",
"Confirm Delete",
JOptionPane.YES_NO_OPTION);
if (confirm == JOptionPane.YES_OPTION) {
DatabaseConnection.removeUserById(userId);
InitInformation.users = DatabaseConnection.getAllUsers();
model.setColumnIdentifiers(USER_COLUMNS); // Revert to default
user columns
loadUsersToTable(InitInformation.users, model); // Load users
into table
setColumnWidths(table, USER_COLUMNS); // Set column widths
studentBox.setSelected(false);
publicUserBox.setSelected(false);
JOptionPane.showMessageDialog(null, "User removed
successfully!");
}

} else {
JOptionPane.showMessageDialog(null, "Please select a user to
remove.");
}
});
userListPanel.add(removeUserButton, gbc);

JPanel useraddPanel = new JPanel();


JPanel addUserPanel = new JPanel(new GridBagLayout());
useraddPanel.setBackground(Color.WHITE);
addUserPanel.setPreferredSize(new Dimension(550, 550));
addUserPanel.setBackground(new Color(198, 233, 240));
gbc = new GridBagConstraints();

gbc.insets = new Insets(15, 10, 5, 0);


gbc.gridx = 0;
gbc.gridy = 0;
JLabel welcomeLabel = new JLabel("Add new user");
welcomeLabel.setFont(new Font("Arial", Font.BOLD, 27));
addUserPanel.add(welcomeLabel, gbc);
gbc.insets = new Insets(0, 10, 10, 0);
gbc.gridx = 0;
gbc.gridy = 1;
JPanel fullName = createTextField("fullNameSignUp", null, 30, 15, "Enter
user's full name");
addUserPanel.add(fullName, gbc);

gbc.gridy = 2;
JPanel email = createTextField("emailSignUp", null, 30, 15, "Enter user's
email");
addUserPanel.add(email, gbc);

gbc.gridy = 3;
JPanel user = createTextField("userSignUp", null, 30, 15, "Enter user's
username");
addUserPanel.add(user, gbc);

gbc.gridy = 4;
JPanel ID = createTextField("ID", null, 30, 15, "Enter user's ID");
addUserPanel.add(ID, gbc);
gbc.gridy = 5;
gbc.insets = new Insets(0, -150, 5, 0);
RoundedComboBox faculty = new RoundedComboBox(
new String[]{"FIT", "FET", "IAI", "FEMA", "SAE", "FEPN", "FAT",
"FCE"}, "Enter faculty", 15,
130, 35);
faculty.setBackground(colorBackground);
addUserPanel.add(faculty, gbc);

String[] majorList = new String[20];


for (int i = 1; i < 19; i++) {
majorList[i] = "CN" + i;
}

gbc.insets = new Insets(0, 170, 5, 0);


RoundedComboBox major = new RoundedComboBox(majorList, "Enter major", 15,
130, 35);
major.setBackground(colorBackground);
addUserPanel.add(major, gbc);
gbc.insets = new Insets(0, 10, 5, 0);
gbc.gridx = 0;

JPanel job = createTextField("job", null, 30, 15, "Enter user's job");


addUserPanel.add(job, gbc);
job.setVisible(false);

gbc.gridy = 7;
JPanel phoneNumber = createTextField("phoneNumber", null, 30, 15, "Enter
your phone number");
addUserPanel.add(phoneNumber, gbc);

gbc.gridy = 8;
JPanel address = createTextField("address", null, 30, 15, "Enter your
address");
addUserPanel.add(address, gbc);

gbc.gridy = 9;
JPanel dob = createTextField("dob", null, 30, 15, "Enter your date of
birth");
addUserPanel.add(dob, gbc);

gbc.gridy = 10;
gbc.insets = new Insets(5, -50, 5, 10);
checkbox1 = new RoundCheckBox("Student");
addUserPanel.add(checkbox1, gbc);

gbc.insets = new Insets(5, 100, 5, 0);


checkbox2 = new RoundCheckBox("Public User");
addUserPanel.add(checkbox2, gbc);

ButtonGroup groupadd = new ButtonGroup();


groupadd.add(checkbox1);
groupadd.add(checkbox2);
checkbox1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (checkbox1.isSelected()) {
System.out.println("Checkbox 1 is selected");
textFieldMap.get("ID").setInitialText("Enter user's ID");
faculty.setVisible(true);
major.setVisible(true);
addUserPanel.revalidate(); // cập nhật giao diện
addUserPanel.repaint();
}
}
});

// Thêm ActionListener cho checkbox2


checkbox2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (checkbox2.isSelected()) {
System.out.println("Checkbox 2 is selected");
textFieldMap.get("ID").setInitialText("Enter user's identify
card");
faculty.setVisible(false);
job.setVisible(true);
major.setVisible(false);
addUserPanel.revalidate(); // cập nhật giao diện
addUserPanel.repaint();
}
}
});

gbc.gridy = 11;
gbc.insets = new Insets(10, 40, 30, 10);
RoundedButton addUserButton = createButton(30, 17, "Add user", 120, 30,
colorBackground, hoverColor, false);
addUserButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String fullName = getTextFromField("fullNameSignUp");
String email = getTextFromField("emailSignUp");
String username = getTextFromField("userSignUp");
String ID = getTextFromField("ID");

String phoneNumber = getTextFromField("phoneNumber");


String address = getTextFromField("address");
String dob = getTextFromField("dob");

if (checkbox1.isSelected()) {
String newFaculty = faculty.getSelectedItem().toString();
String newMajor = major.getSelectedItem().toString();
Student student = new Student(fullName, dob, address, email,
phoneNumber, username, "123456",
newFaculty, newMajor,
ID);
student.signUp(InitInformation.library);
loadUsersToTable(DatabaseConnection.getAllUsers(), model); //
Load users into table

} else {
String job = getTextFromField("job");
PublicUser publicUser = new PublicUser(fullName, dob, address,
email, phoneNumber, username,
"123456", ID, job);
publicUser.signUp(InitInformation.library);
}
loadUsersToTable(DatabaseConnection.getAllUsers(), model); // Load
users into table
JOptionPane.showMessageDialog(null, "dang ky thanh cong");
userCardLayout.show(userContentPane, "list");

}
});

addUserPanel.add(addUserButton, gbc);
useraddPanel.add(addUserPanel, gbc);

userContentPane.add(userListPanel, "list");
userContentPane.add(useraddPanel, "addUser");

userPanel.add(userContentPane, BorderLayout.CENTER);

private void createDetailPanel(User currentUser, DefaultTableModel model) {

Student student = null;


PublicUser publicUser = null;
if (currentUser instanceof Student) {
student = (Student) currentUser;
} else {
publicUser = (PublicUser) currentUser;
}
detailPanel = new JPanel(new GridBagLayout());
detailPanel.setBackground(Color.WHITE);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 10, 5, 0);
gbc.gridx = 0;
gbc.gridy = 0;
JLabel welcomeLabel = new JLabel("User Detail");
welcomeLabel.setFont(new Font("Arial", Font.BOLD, 27));
detailPanel.add(welcomeLabel, gbc);
CardLayout detailCardLayout = new CardLayout();
JPanel detailContentPane = new JPanel(detailCardLayout);

detailContentPane.setBackground(Color.WHITE);

JPanel userPanel = new JPanel();


userPanel.setLayout(new GridBagLayout());
userPanel.setBackground(colorButton);

JPanel infoPanel = new JPanel(new GridBagLayout());


infoPanel.setBackground(Color.WHITE);
gbc = new GridBagConstraints();
gbc.gridy = 0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.CENTER;
infoPanel.add(userPanel, gbc);

gbc.gridy = 1;
gbc.weighty = 1.0;
// gbc1.fill = GridBagConstraints.CENTER
gbc.fill = GridBagConstraints.BOTH;
detailPanel.add(detailContentPane, gbc);
detailContentPane.add(infoPanel, "userPanel");

gbc = new GridBagConstraints();


gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.insets = new Insets(5, 40, 5, 0);
JPanel fullName = createTextField("fullNameSignUp", null, 30, 15,
currentUser.getName(), "Full name: ", false);
userPanel.add(fullName, gbc);

gbc.insets = new Insets(5, 40, 5, 0);


gbc.gridy = 2;
JPanel email = createTextField("emailSignUp", null, 30, 15,
currentUser.getEmail(), "Email: ", false);
userPanel.add(email, gbc);

gbc.gridy = 3;
JPanel user = createTextField("userSignUp", null, 30, 15,
currentUser.getAccount(), "Username: ", false);
userPanel.add(user, gbc);

gbc.gridy = 4;
JPanel ID;
if (student != null) {
ID = createTextField("ID", null, 30, 15, student.getStudentId(), "ID:
", false);
} else {
ID = createTextField("ID", null, 30, 15, publicUser.getIdentityCard(),
"Identify card: ", false);
}
userPanel.add(ID, gbc);

gbc.gridy = 5;
JPanel faculty;
JPanel job;
if (student != null) {
faculty = createTextField("faculty", null, 30, 15,
student.getFaculty(), "Faculty: ", false);
userPanel.add(faculty, gbc);
} else {
job = createTextField("job", null, 30, 15, publicUser.getJob(), "Job:
", false);
userPanel.add(job, gbc);
}

if (student != null) {
gbc.gridy = 6;
JPanel major = createTextField("major", null, 30, 15,
student.getMajor(), "Major: ", false);
major.setBackground(colorBackground);
userPanel.add(major, gbc);
}

gbc.gridy = 7;
JPanel phoneNumber = createTextField("phoneNumber", null, 30, 15,
currentUser.getPhoneNumber(), "Phone number: ",
false);
userPanel.add(phoneNumber, gbc);

gbc.gridy = 8;
JPanel address = createTextField("address", null, 30, 15,
currentUser.getAddress(), "Address: ", false);
userPanel.add(address, gbc);

gbc.gridy = 9;
JPanel dob = createTextField("dob", null, 30, 15,
currentUser.getDateOfBirth(), "Date of birth: ", false);
userPanel.add(dob, gbc);

gbc.gridy = 10;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(5, 300, 5, 0);
JButton editButton = new JButton(edit);
editButton.setBackground(colorBackground);
editButton.setOpaque(false);
editButton.setBorderPainted(false);
editButton.setFocusPainted(false);
editButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
detailCardLayout.show(detailContentPane, "displayInfoPanel");

}
});
userPanel.add(editButton, gbc);

JPanel displayUserPanel = new JPanel();


displayUserPanel.setLayout(new GridBagLayout());
displayUserPanel.setBackground(colorButton);

JPanel displayInfoPanel = new JPanel(new GridBagLayout());


displayInfoPanel.setBackground(Color.WHITE);
gbc = new GridBagConstraints();
gbc.gridy = 0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.CENTER;
displayUserPanel.setPreferredSize(new Dimension(400, 500));
displayInfoPanel.add(displayUserPanel, gbc);
detailContentPane.add(displayInfoPanel, "displayInfoPanel");

gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL; // Mở rộng chiều ngang
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.insets = new Insets(5, 40, 5, 0);
JPanel displayName = createTextField("displayName", null, 30, 15,
currentUser.getName(), "Full name: ", true);
displayUserPanel.add(displayName, gbc);

gbc.insets = new Insets(5, 40, 5, 0);


gbc.gridy = 2;
JPanel displayEmail = createTextField("displayEmail", null, 30, 15,
currentUser.getEmail(), "Email: ", true);
displayUserPanel.add(displayEmail, gbc);

gbc.gridy = 3;
JPanel displayUser = createTextField("displayUser", null, 30, 15,
currentUser.getAccount(), "Username: ",
false);
displayUserPanel.add(displayUser, gbc);

gbc.gridy = 4;
JPanel displayID;
if (student != null) {
displayID = createTextField("displayID", null, 30, 15,
student.getStudentId(), "ID: ", false);
} else {
displayID = createTextField("displayID", null, 30, 15,
publicUser.getIdentityCard(), "Identify card: ",
true);
}
displayUserPanel.add(displayID, gbc);

gbc.gridy = 5;
JPanel displayFaculty;
JPanel displayJob;
if (student != null) {
displayFaculty = createTextField("displayFaculty", null, 30, 15,
student.getFaculty(), "Faculty: ", true);
displayUserPanel.add(displayFaculty, gbc);
gbc.gridy = 6;

JPanel displayMajor = createTextField("displayMajor", null, 30, 15,


student.getMajor(), "Major: ", true);
displayMajor.setBackground(colorBackground);
displayUserPanel.add(displayMajor, gbc);
} else {
displayJob = createTextField("displayJob", null, 30, 15,
publicUser.getJob(), "Job: ", true);
displayUserPanel.add(displayJob, gbc);
}

gbc.gridy = 6;

gbc.gridy = 7;
gbc.insets = new Insets(5, 40, 5, 0);
JPanel displayPhoneNumber = createTextField("displayPhoneNumber", null, 30,
15, currentUser.getPhoneNumber(),
"Phone number: ", true);
displayUserPanel.add(displayPhoneNumber, gbc);

gbc.gridy = 8;
JPanel displayAddress = createTextField("displayAddress", null, 30, 15,
currentUser.getAddress(), "Address: ",
true);
displayUserPanel.add(displayAddress, gbc);

gbc.gridy = 9;
JPanel displayDob = createTextField("displayDob", null, 30, 15,
currentUser.getDateOfBirth(),
"Date of birth: ", true);
displayUserPanel.add(displayDob, gbc);
gbc.gridy = 12;
gbc.insets = new Insets(5, 40, 5, 40);
RoundedButton saveButton = createButton(35, 17, "Save", 100, 35,
colorButton, hoverColor, false);
gbc.anchor = GridBagConstraints.EAST;
displayUserPanel.add(saveButton, gbc);
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Retrieve input values from textFieldMap
String email = textFieldMap.get("displayEmail").getText();
if (email.equals("")) {
email = currentUser.getEmail();
}

String phoneNumber =
textFieldMap.get("displayPhoneNumber").getText();
if (phoneNumber.equals("")) {
phoneNumber = currentUser.getPhoneNumber();
}

String address = textFieldMap.get("displayAddress").getText();


if (address.equals("")) {
address = currentUser.getAddress();
}

String dob = textFieldMap.get("displayDob").getText();


if (dob.equals("")) {
dob = currentUser.getDateOfBirth();
}

String id = textFieldMap.get("displayID").getText();

String faculty = null;


String major = null;
String identityCard = null;
String job = null;

if (currentUser instanceof Student) {


faculty = textFieldMap.get("displayFaculty").getText();
if (faculty.equals("")) {
faculty = ((Student) currentUser).getFaculty();
}
System.out.println("Student ID for email validation: " + id);

major = textFieldMap.get("displayMajor").getText();
if (major.equals("")) {
major = ((Student) currentUser).getMajor();
}
id = ((Student) currentUser).getStudentId();
} else if (currentUser instanceof PublicUser) {
identityCard =
textFieldMap.get("displayIdentityCard").getText();
if (identityCard.equals("")) {
identityCard = ((PublicUser)
currentUser).getIdentityCard();
}
job = textFieldMap.get("displayJob").getText();
if (job.equals("")) {
job = ((PublicUser) currentUser).getJob();
}
System.out.println("Identity Card: " + identityCard);
}

System.out.println("Email: " + email);


System.out.println("Phone: " + phoneNumber);
System.out.println("ID: " + id);

boolean hasError = false;

if (currentUser instanceof Student) {


// String studentId = textFieldMap.get("displayID").getText();
if (!id.isEmpty()) {
if (!ValidationUtils.isValidStudentEmail(email, id)) {
JOptionPane.showMessageDialog(null, "Invalid student
email format. Must be: [email protected]");
hasError = true;
}
if (!ValidationUtils.isValidStudentId(id)) {
JOptionPane.showMessageDialog(null, "Invalid student ID
format. Must be 8 digits");
hasError = true;
}
}
} else if (currentUser instanceof PublicUser) {
if (!ValidationUtils.isValidPublicUserEmail(email)) {
JOptionPane.showMessageDialog(null, "Invalid email format
for public user. Must end with @gmail.com");
hasError = true;
}
if (!identityCard.isEmpty() && !
ValidationUtils.isValidIdentityCard(identityCard)) {
JOptionPane.showMessageDialog(null, "Invalid identity card
format. Must be 12 digits");
hasError = true;
}
}

if (!phoneNumber.isEmpty() && !
ValidationUtils.isValidPhoneNumber(phoneNumber)) {
JOptionPane.showMessageDialog(null, "Invalid phone number
format. Must be 10 digits");
hasError = true;
}

if (hasError) {
return;
}
currentUser.setEmail(email);
currentUser.setPhoneNumber(phoneNumber);
currentUser.setAddress(address);
currentUser.setDateOfBirth(dob);

if (currentUser instanceof Student) {


((Student) currentUser).setStudentId(id);
((Student) currentUser).setFaculty(faculty);
((Student) currentUser).setMajor(major);
} else if (currentUser instanceof PublicUser) {
((PublicUser) currentUser).setIdentityCard(identityCard);
((PublicUser) currentUser).setJob(job);
}

JOptionPane.showMessageDialog(null, "Information saved


successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);

userPanel.revalidate();
userPanel.repaint();
loadUsersToTable(DatabaseConnection.getAllUsers(), model);
userCardLayout.show(userContentPane, "list");
}
});

// Method to load students into the table


private void loadStudentsToTable(List<Student> students, DefaultTableModel
model) {
// Clear existing rows
model.setRowCount(0);

// Add rows with correct column order


for (Student student : students) {
model.addRow(new Object[]{
student.getId(),
student.getName(),
student.getDateOfBirth(),
student.getAddress(),
student.getEmail(),
student.getPhoneNumber(),
student.getAccount(),
student.getPassword(),
student.getFaculty(),
student.getMajor(),
student.getStudentId()
});
}
}

// Method to load public users into the table


private void loadPublicUsersToTable(List<PublicUser> publicUsers,
DefaultTableModel model) {
// Clear existing rows
model.setRowCount(0);

// Add rows with correct column order


for (PublicUser publicUser : publicUsers) {
model.addRow(new Object[]{
publicUser.getId(),
publicUser.getName(),
publicUser.getDateOfBirth(),
publicUser.getAddress(),
publicUser.getEmail(),
publicUser.getPhoneNumber(),
publicUser.getAccount(),
publicUser.getPassword(),
publicUser.getIdentityCard(),
publicUser.getJob()
});
}
}

private void createBookManagement() {


bookCardLayout = new CardLayout();

bookContentPane = new JPanel(bookCardLayout);


bookPanel = new JPanel();
bookPanel.setLayout(new BorderLayout());
bookPanel.setBackground(Color.WHITE);
foundDocumentsPanel = new JPanel();
bookContentPane.add(foundDocumentsPanel, "foundDocuments");
JPanel searchPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 40, 30, 0);
RoundedTextField searchField = new RoundedTextField(40, 30, "Search");
searchField.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
searchField.setBackground(new Color(198, 233, 240));
searchPanel.setOpaque(false);
searchPanel.add(searchField, gbc);
gbc.insets = new Insets(15, 10, 30, 0);
RoundedButton searchButton = createButton(35, 17, "Search", 100, 35,
colorButton, hoverColor, false);
searchPanel.add(searchButton, gbc);
searchField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
// Kiểm tra nếu phím Enter được nhấn
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
searchButton.doClick();
}
}
});

// addUserPanelắng nghe sự kiện click vào nút "Search"


searchButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
foundDocuments =
InitInformation.admin.searchDocumentsBySubstring(searchField.getText(),
InitInformation.library);
foundDocumentsPanel = createFoundBook(foundDocuments);
bookContentPane.remove(foundDocumentsPanel);
bookContentPane.add(foundDocumentsPanel, "foundDocuments");

// Hiển thị panel mới


bookCardLayout.show(bookContentPane, "foundDocuments");
bookContentPane.revalidate();
bookContentPane.repaint();
}
});
bookPanel.add(searchPanel, BorderLayout.NORTH);

JPanel bookListPanel = new JPanel(new GridBagLayout());


gbc.insets = new Insets(0, 0, 0, 0);
gbc.gridx = 0;
gbc.gridy = 0;
bookListPanel.setBackground(Color.WHITE);

String[][] data = new String[InitInformation.documents.size()][7];

for (int i = 0; i < InitInformation.documents.size(); i++) {


data[i][0] = String.valueOf(InitInformation.documents.get(i).getId());
data[i][1] = InitInformation.documents.get(i).getTitle();
data[i][2] = InitInformation.documents.get(i).getCategory();
data[i][3] = InitInformation.documents.get(i).getAuthor();
data[i][4] = InitInformation.documents.get(i).getPublisher();
data[i][5] =
String.valueOf(InitInformation.documents.get(i).getQuantity());
data[i][6] =
String.valueOf(InitInformation.documents.get(i).getPrice());
}
String[] columnNames = {"ID", "Title", "Category", "Author", "Publisher",
"Quantity", "Price"};
DefaultTableModel model = new DefaultTableModel(data, columnNames) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};

JTable table = new JTable(model);

table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

table.getColumnModel().getColumn(0).setPreferredWidth(25);
table.getColumnModel().getColumn(1).setPreferredWidth(400);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(200);
table.getColumnModel().getColumn(4).setPreferredWidth(150);
table.getColumnModel().getColumn(5).setPreferredWidth(50);
table.getColumnModel().getColumn(6).setPreferredWidth(60);

// Tạo JScrollPane và thêm JTable vào JScrollPane


JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(600, 350));

scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// Kiểm tra sự kiện nhấn đúp chuột
if (e.getClickCount() == 2) {
int selectedRow = table.getSelectedRow(); // Lấy hàng được chọn
if (selectedRow != -1) { // Kiểm tra nếu hàng hợp lệ
// Lấy dữ liệu từ hàng
try {
Object id = table.getValueAt(selectedRow, 0);
int bookId = Integer.parseInt(id.toString());
Document document =
DatabaseConnection.getDocumentById(bookId);
if (document != null) {
if (detailPanel != null) {
bookContentPane.remove(detailPanel);
}
createDetailPanel(document, model);
bookContentPane.add(detailPanel, "detail");
bookCardLayout.show(bookContentPane, "detail");
} else {
System.out.println("Không tìm thấy sách với ID: " +
bookId);
}
} catch (Exception ex) {
ex.printStackTrace(); // In lỗi chi tiết để xác định
vấn đề
}

}
}
}
});

bookListPanel.add(scrollPane);
gbc.gridx = 1;
gbc.gridy = 10;
gbc.insets = new Insets(10, -450, 30, 10);
RoundedButton addButton = createButton(30, 17, "Add book", 120, 30,
colorBackground, hoverColor, false);
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {

bookCardLayout.show(bookContentPane, "addBook");
}
});
bookListPanel.add(addButton, gbc);

gbc.insets = new Insets(10, -140, 30, 10);


RoundedButton removeBookButton = createButton(30, 17, "Remove book", 150,
30, colorBackground, hoverColor,
false);
removeBookButton.setActionCommand("removeBook");
removeBookButton.addActionListener(e -> {
int selectedRow = table.getSelectedRow();
if (selectedRow >= 0) {
// Get id and title from selected row
int bookId = Integer.parseInt(table.getValueAt(selectedRow,
0).toString());
String bookTitle = table.getValueAt(selectedRow, 1).toString();

// Show confirmation dialog


int confirm = JOptionPane.showConfirmDialog(
null,
"Are you sure you want to delete book: " + bookTitle + "?",
"Confirm Delete",
JOptionPane.YES_NO_OPTION);

if (confirm == JOptionPane.YES_OPTION) {
DatabaseConnection.removeDocumentById(bookId);
InitInformation.documents =
DatabaseConnection.getAllDocuments();
loadBooksToTable(InitInformation.documents, model);
JOptionPane.showMessageDialog(null, "Book removed
successfully!");
}
} else {
JOptionPane.showMessageDialog(null, "Please select a book to
remove.");
}
});
bookListPanel.add(removeBookButton, gbc);

JPanel bookAddPanel = new JPanel();


JPanel addBookPanel = new JPanel(new GridBagLayout());
bookAddPanel.setBackground(Color.WHITE);
addBookPanel.setPreferredSize(new Dimension(500, 450));
addBookPanel.setBackground(new Color(198, 233, 240));
gbc = new GridBagConstraints();

gbc.insets = new Insets(15, 10, 10, 0);


gbc.gridx = 0;
gbc.gridy = 0;
JLabel welcomeLabel = new JLabel("Add new book");
welcomeLabel.setFont(new Font("Arial", Font.BOLD, 27));
addBookPanel.add(welcomeLabel, gbc);
gbc.insets = new Insets(15, 10, 10, 0);
gbc.gridx = 0;
gbc.gridy = 1;
JPanel title = createTextField("title", null, 30, 15, "Name of book");
addBookPanel.add(title, gbc);

gbc.gridy = 2;
JPanel author = createTextField("author", null, 30, 15, "author");
addBookPanel.add(author, gbc);

gbc.gridy = 3;
JPanel category = createTextField("category", null, 30, 15, "faculty");
addBookPanel.add(category, gbc);

gbc.gridy = 4;
JPanel publisher = createTextField("publisher", null, 30, 15, "publisher");
addBookPanel.add(publisher, gbc);

gbc.gridy = 5;
gbc.insets = new Insets(15, -140, 10, 0);
JPanel quantity = createTextField("quantity", null, 13, 15, "quantity");
addBookPanel.add(quantity, gbc);

gbc.insets = new Insets(15, 0, 10, -165);


JPanel price = createTextField("price", null, 13, 15, "price");
addBookPanel.add(price, gbc);

gbc.gridy = 6;
gbc.insets = new Insets(10, 0, 30, 10);
RoundedButton addBookButton = createButton(30, 17, "Add book", 120, 30,
colorBackground, hoverColor, false);

addBookButton.setActionCommand("addBook");
addBookButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String title = getTextFromField("title");
String author = getTextFromField("author");
String category = getTextFromField("category");
String publisher = getTextFromField("publisher");
String quantity = getTextFromField("quantity");
String price = getTextFromField("price");

if (title == null || author == null || category == null ||


publisher == null || quantity == null
|| price == null) {
JOptionPane.showMessageDialog(null, "Please fill in all
fields", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}

try {
Document document = new Document(title, category, author,
publisher, Integer.parseInt(quantity),
Long.parseLong(price));
DatabaseConnection.insertDocument(document);
InitInformation.documents =
DatabaseConnection.getAllDocuments();
loadBooksToTable(InitInformation.documents, model);
JOptionPane.showMessageDialog(null, "Add book successfully",
"Success",
JOptionPane.INFORMATION_MESSAGE);
bookCardLayout.show(bookContentPane, "list");
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Price and quantity must be
numbers", "Error",
JOptionPane.ERROR_MESSAGE);
bookCardLayout.show(bookContentPane, "list");
}
}
});

addBookPanel.add(addBookButton, gbc);

bookAddPanel.add(addBookPanel, gbc);

bookContentPane.add(bookListPanel, "list");
bookContentPane.add(bookAddPanel, "addBook");

bookPanel.add(bookContentPane, BorderLayout.CENTER);

private void createDetailPanel(Document document, DefaultTableModel model) {

detailPanel = new JPanel(new GridBagLayout());


detailPanel.setBackground(Color.WHITE);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 10, 5, 0);
gbc.gridx = 0;
gbc.gridy = 0;
JLabel welcomeLabel = new JLabel("Book Detail");
welcomeLabel.setFont(new Font("Arial", Font.BOLD, 27));
detailPanel.add(welcomeLabel, gbc);

CardLayout detailCardLayout = new CardLayout();


JPanel detailContentPane = new JPanel(detailCardLayout);
gbc.gridy = 1;
detailPanel.add(detailContentPane, gbc);

detailContentPane.setBackground(Color.WHITE);

JPanel userPanel = new JPanel();


userPanel.setLayout(new GridBagLayout());
userPanel.setBackground(colorButton);

JPanel infoPanel = new JPanel(new GridBagLayout());


infoPanel.setBackground(Color.WHITE);
gbc = new GridBagConstraints();
gbc.gridy = 0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.CENTER;
userPanel.setPreferredSize(new Dimension(500, 500));
infoPanel.add(userPanel, gbc);

detailContentPane.add(infoPanel, "userPanel");

gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL; // Mở rộng chiều ngang
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.insets = new Insets(5, 40, 5, 0);
JPanel fullName = createTextField("Book title", null, 30, 15,
document.getTitle(), "Book title: ", false);
userPanel.add(fullName, gbc);

gbc.gridy = 2;
JPanel ID = createTextField("ID", null, 30, 15,
String.valueOf(document.getId()), "ID: ", false);
userPanel.add(ID, gbc);

gbc.gridy = 3;
JPanel author = createTextField("author", null, 30, 15,
document.getAuthor(), "Author: ", false);
userPanel.add(author, gbc);

gbc.gridy = 4;
JPanel category = createTextField("category", null, 30, 15,
document.getCategory(), "Category: ", false);
userPanel.add(category, gbc);

gbc.gridy = 5;
JPanel publisher = createTextField("publisher", null, 30, 15,
document.getPublisher(), "Publisher: ", false);
userPanel.add(publisher, gbc);

gbc.gridy = 6;
JPanel quantity = createTextField("quantity", null, 30, 15,
String.valueOf(document.getQuantity()), "Quantity: ", false);
userPanel.add(quantity, gbc);

gbc.gridy = 7;
JPanel price = createTextField("price", null, 30, 15, String.valueOf((int)
document.getPrice()) + " VND", "Price: ", false);
userPanel.add(price, gbc);

gbc.gridy = 10;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(5, 300, 5, 0);
JButton editButton = new JButton(edit);
editButton.setBackground(colorBackground);
editButton.setOpaque(false);
editButton.setBorderPainted(false);
editButton.setFocusPainted(false);
editButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
detailCardLayout.show(detailContentPane, "displayInfoPanel");

}
});
userPanel.add(editButton, gbc);

JPanel displayUserPanel = new JPanel();


displayUserPanel.setLayout(new GridBagLayout());
displayUserPanel.setBackground(colorButton);

JPanel displayInfoPanel = new JPanel(new GridBagLayout());


displayInfoPanel.setBackground(Color.WHITE);
gbc = new GridBagConstraints();
gbc.gridy = 0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.CENTER;
displayUserPanel.setPreferredSize(new Dimension(500, 500));
displayInfoPanel.add(displayUserPanel, gbc);
detailContentPane.add(displayInfoPanel, "displayInfoPanel");

gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL; // Mở rộng chiều ngang
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.insets = new Insets(5, 40, 5, 0);
JPanel displayName = createTextField("displayName", null, 30, 15,
document.getTitle(), "Book title: ", false);
displayUserPanel.add(displayName, gbc);

gbc.gridy = 2;
JPanel displayID = createTextField("displayID", null, 30, 15,
String.valueOf(document.getId()), "ID: ", false);
displayUserPanel.add(displayID, gbc);

gbc.gridy = 3;
JPanel displayAuthor = createTextField("displayAuthor", null, 30, 15,
document.getAuthor(), "Author: ", true);
displayUserPanel.add(displayAuthor, gbc);

gbc.gridy = 4;
JPanel displayCategory = createTextField("displayCategory", null, 30, 15,
document.getCategory(), "Category: ", true);
displayUserPanel.add(displayCategory, gbc);

gbc.gridy = 5;
JPanel displayPublisher = createTextField("displayPublisher", null, 30, 15,
document.getPublisher(), "Publisher: ", true);
displayUserPanel.add(displayPublisher, gbc);

gbc.gridy = 6;
JPanel displayQuantity = createTextField("displayQuantity", null, 30, 15,
String.valueOf(document.getQuantity()), "Quantity: ", true);
displayUserPanel.add(displayQuantity, gbc);

gbc.gridy = 7;
JPanel displayPrice = createTextField("displayPrice", null, 30, 15,
String.valueOf((int) document.getPrice()) + " VND", "Price: ", true);
displayUserPanel.add(displayPrice, gbc);

gbc.gridy = 8;
gbc.insets = new Insets(5, 40, 5, 40);
RoundedButton saveButton = createButton(35, 17, "Save", 100, 35,
colorButton, hoverColor, false);
gbc.anchor = GridBagConstraints.EAST;
displayUserPanel.add(saveButton, gbc);
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Retrieve input values from textFieldMap

String author = textFieldMap.get("displayAuthor").getText();


if (author.equals("")) {
author = document.getAuthor();
}

String category = textFieldMap.get("displayCategory").getText();


if (category.equals("")) {
category = document.getCategory();
}

String publisher = textFieldMap.get("displayPublisher").getText();


if (publisher.equals("")) {
publisher = document.getPublisher();
}

String quantity = textFieldMap.get("displayQuantity").getText();


if (quantity.equals("")) {
quantity = String.valueOf(document.getQuantity());
}

String price = textFieldMap.get("displayPrice").getText();


if (price.equals("")) {
price = String.valueOf((int) document.getPrice());
}

document.setAuthor(author);
document.setCategory(category);
document.setPublisher(publisher);
document.setQuantity(Integer.parseInt(quantity));
document.setPrice(Long.parseLong(price));

JOptionPane.showMessageDialog(null, "Information saved


successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);

userPanel.revalidate();
userPanel.repaint();
loadBooksToTable(DatabaseConnection.getAllDocuments(), model);
bookCardLayout.show(bookContentPane, "list");
}
});

private JPanel createFoundBook(List<Document> document) {


GridBagConstraints gbc = new GridBagConstraints();
JPanel bookListPanel = new JPanel(new GridBagLayout());
gbc.insets = new Insets(0, 0, 0, 0);
gbc.gridx = 0;
gbc.gridy = 0;

bookListPanel.setBackground(Color.WHITE);

String[][] data = new String[document.size()][7];


for (int i = 0; i < document.size(); i++) {
data[i][0] = String.valueOf(document.get(i).getId());
data[i][1] = document.get(i).getTitle();
data[i][2] = document.get(i).getCategory();
data[i][3] = document.get(i).getAuthor();
data[i][4] = document.get(i).getPublisher();
data[i][5] = String.valueOf(document.get(i).getQuantity());
data[i][6] = String.valueOf(document.get(i).getPrice());

}
String[] columnNames = {"ID", "Title", "Category", "Author", "Publisher",
"Quantity", "Price"};
DefaultTableModel model = new DefaultTableModel(data, columnNames) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
JTable table = new JTable(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getColumnModel().getColumn(0).setPreferredWidth(25);
table.getColumnModel().getColumn(1).setPreferredWidth(400);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(200);
table.getColumnModel().getColumn(4).setPreferredWidth(150);
table.getColumnModel().getColumn(5).setPreferredWidth(50);
table.getColumnModel().getColumn(6).setPreferredWidth(60);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(600, 350));

scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
bookListPanel.add(scrollPane);
return bookListPanel;
}

private void loadBooksToTable(List<Document> documents, DefaultTableModel


model) {
model.setRowCount(0); // Xóa dữ liệu cũ
for (Document document : documents) {
model.addRow(
new Object[]{document.getId(), document.getTitle(),
document.getAuthor(), document.getCategory(),
document.getPublisher(), document.getQuantity(),
document.getPrice()});
}
}

private void loadUsersToTable(List<User> users, DefaultTableModel model) {


// Clear existing rows
model.setRowCount(0);

// Add rows with correct column order


for (User user : users) {
model.addRow(new Object[]{
user.getId(),
user.getName(),
user.getDateOfBirth(),
user.getAddress(),
user.getEmail(),
user.getPhoneNumber(),
user.getAccount(),
user.getPassword()
});
}
}

private void createSideBar() {


sidebar = new JPanel();
sidebar.setBackground(colorBackground); // addUserPanelight blue color
sidebar.setLayout(new GridLayout(6, 1, 5, 5));
sidebar.setPreferredSize(new Dimension(80, 0));
// Add sidebar icons (home, chat, profile, etc.) as buttons
homeButton = new JButton(homeIcon);
homeButton.setBackground(colorBackground);
homeButton.setOpaque(false);
homeButton.setContentAreaFilled(false);
homeButton.setBorderPainted(false);
homeButton.setFocusPainted(false);
homeButton.setActionCommand("homepanel");
homeButton.addActionListener(buttonListener);

chatButton = new JButton(notificationIcon);


chatButton.setBackground(colorBackground);
chatButton.setOpaque(false);
chatButton.setContentAreaFilled(false);
chatButton.setBorderPainted(false);
chatButton.setFocusPainted(false);
chatButton.setActionCommand("chatpanel");
chatButton.addActionListener(buttonListener);

userButton = new JButton(userIcon);


userButton.setBackground(colorBackground);
userButton.setOpaque(false);
userButton.setContentAreaFilled(false);
userButton.setBorderPainted(false);
userButton.setFocusPainted(false);
userButton.setActionCommand("userpanel");
userButton.addActionListener(buttonListener);

bookButton = new JButton(bookIcon);


bookButton.setBackground(colorBackground);
bookButton.setOpaque(false);
bookButton.setContentAreaFilled(false);
bookButton.setBorderPainted(false);
bookButton.setFocusPainted(false);
bookButton.setActionCommand("bookpanel");
bookButton.addActionListener(buttonListener);

manageButton = new JButton(borrowBookIcon);


manageButton.setBackground(colorBackground);
manageButton.setOpaque(false);
manageButton.setContentAreaFilled(false);
manageButton.setBorderPainted(false);
manageButton.setFocusPainted(false);
manageButton.setActionCommand("managepanel");
manageButton.addActionListener(buttonListener);

logoutButton = new JButton(infoIcon);


logoutButton.setBackground(colorBackground);
logoutButton.setOpaque(false);
logoutButton.setContentAreaFilled(false);
logoutButton.setBorderPainted(false);
logoutButton.setFocusPainted(false);
logoutButton.setActionCommand("logoutpanel");
logoutButton.addActionListener(buttonListener);

sidebar.add(homeButton);
sidebar.add(chatButton);
sidebar.add(userButton);
sidebar.add(bookButton);
sidebar.add(manageButton);
sidebar.add(logoutButton);

private void createNotificationPanel() {


// Tạo panel tiêu đề với GridBagLayout để chứa tiêu đề "Notification"
JPanel titlePanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 10, 10, 0);
gbc.gridx = 0;
gbc.gridy = 0;
titlePanel.setBackground(Color.WHITE);

JLabel welcomeLabel = new JLabel("Notification");


welcomeLabel.setFont(new Font("Arial", Font.BOLD, 27));
titlePanel.add(welcomeLabel, gbc);

// Tạo notificationContainer để chứa các thông báo


notificationContainer = new JPanel();
notificationContainer.setLayout(new BoxLayout(notificationContainer,
BoxLayout.Y_AXIS));
notificationContainer.setOpaque(true);
notificationContainer.setBackground(Color.WHITE); // Đặt màu nền cho
notificationContainer

// Tạo JScrollPane bao quanh notificationContainer


JScrollPane scrollPane = new JScrollPane(notificationContainer);

scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBorder(BorderFactory.createEmptyBorder()); // Bỏ viền của
JScrollPane
scrollPane.getViewport().setBackground(Color.WHITE); // Đặt màu nền cho
viewport của JScrollPane

// Tạo panel chứa scrollPane và titlePanel


ChatPanel = new JPanel(new BorderLayout());
ChatPanel.add(scrollPane, BorderLayout.CENTER);
ChatPanel.add(titlePanel, BorderLayout.NORTH);
addNotification();

// Cập nhậtaddUserPanelại giao diện sau khi thêm thành phần


scrollPane.revalidate();
scrollPane.repaint();
}

private void addNotification() {


// Clear existing content
notificationContainer.removeAll();

// Get borrowed documents from database for current user


for (User user : InitInformation.users) {
List<BorrowedDocument> borrowedDocuments =
DatabaseConnection.getBorrowedDocumentsByUserId(user.getId());
for (BorrowedDocument borrowedDoc : borrowedDocuments) {
Document document = borrowedDoc.getDocument();
// Create panel for notification
JPanel notificationPanel = new JPanel();
notificationPanel.setLayout(new BoxLayout(notificationPanel,
BoxLayout.X_AXIS));
notificationPanel.setBorder(BorderFactory.createEmptyBorder(10, 10,
10, 10));
notificationPanel.setBackground(colorButton);

Dimension fixedSize = new Dimension(890, 150);


notificationPanel.setPreferredSize(fixedSize);
notificationPanel.setMaximumSize(fixedSize);
notificationPanel.setMinimumSize(fixedSize);

// Add notification info


JPanel infoPanel = new JPanel();
infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
infoPanel.setBackground(colorButton);
infoPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));

infoPanel.add(new JLabel("User ID: " + user.getId() + " - " +


user.getName() + " borrowed book: "));
infoPanel.add(new JLabel("Title: " + document.getTitle()));
infoPanel.add(new JLabel("Borrow Date: " +
borrowedDoc.getBorrowedDate()));
infoPanel.add(new JLabel("Return Date: " +
borrowedDoc.getReturnDate()));

notificationPanel.add(infoPanel);

notificationContainer.add(Box.createRigidArea(new Dimension(0,
10)));

notificationContainer.add(notificationPanel);
}
}

notificationContainer.revalidate();
notificationContainer.repaint();
}

private void createBorrowedBookList() {


// Tạo panel tiêu đề
JPanel titlePanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 10, 10, 0);
gbc.gridx = 0;
gbc.gridy = 0;
titlePanel.setBackground(Color.WHITE);

JLabel welcomeLabel = new JLabel("Borrowed Books List");


welcomeLabel.setFont(new Font("Arial", Font.BOLD, 27));
titlePanel.add(welcomeLabel, gbc);

// Tạo panel nút bấm


JPanel buttonPanel = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 10, 20, 0);
gbc.gridx = 0;
gbc.gridy = 0;
buttonPanel.setBackground(Color.WHITE);

// Tạo nút "Add Borrowed Book"


RoundedButton addBorrowedButton = createButton(30, 17, "Add Borrowed Book",
200, 40,
colorBackground, hoverColor, false);
buttonPanel.add(addBorrowedButton);

// Xử lý sự kiện khi nhấn nút


addBorrowedButton.addActionListener(e -> {
// Mở dialog để nhập thông tin sách mượn
JTextField userIDField = new JTextField(15);
JTextField bookIDField = new JTextField(15);
JTextField returnDateField = new JTextField(15);
JTextField quantityField = new JTextField(15);

JPanel inputPanel = new JPanel(new GridLayout(4, 2, 10, 10));


inputPanel.add(new JLabel("User ID:"));
inputPanel.add(userIDField);
inputPanel.add(new JLabel("Book ID:"));
inputPanel.add(bookIDField);
inputPanel.add(new JLabel("Quantity:"));
inputPanel.add(quantityField);
inputPanel.add(new JLabel("Return Date:"));
inputPanel.add(returnDateField);

int result = JOptionPane.showConfirmDialog(


null,
inputPanel,
"Enter Borrowed Book Details",
JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
String userID = userIDField.getText();
User currentUser =
DatabaseConnection.getUserById(Integer.parseInt(userID));
String bookID = bookIDField.getText();
Document document =
DatabaseConnection.getDocumentById(Integer.parseInt(bookID));
String returnDate = returnDateField.getText();
String quantity = quantityField.getText();
if (returnDate != null && !returnDate.trim().isEmpty()) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false);
Date parsedDate = sdf.parse(returnDate);
Date currentDate = new Date();

if (parsedDate.before(currentDate)) {
JOptionPane.showMessageDialog(null, "Return date cannot
be in the past!");
return;
}

if (quantity != null && !quantity.trim().isEmpty()) {


try {
int quantityToBorrow = Integer.parseInt(quantity);
if (quantityToBorrow <= 0) {
JOptionPane.showMessageDialog(null, "Quantity
must be positive!");
return;
}

if (quantityToBorrow > document.getQuantity()) {


JOptionPane.showMessageDialog(null, "Not enough
copies available!");
return;
}

// Proceed with borrowing


if (currentUser.borrowDocument(document,
quantityToBorrow, InitInformation.library,
sdf.format(parsedDate))) {

// Update UI after successful borrow


Document updatedDoc = DatabaseConnection
.getDocumentWithQuantity(document.getId
());
if (updatedDoc != null) {

document.setQuantity(updatedDoc.getQuantity());

}
// Refresh borrowed books list
addBorrowedBook();
}

} catch (NumberFormatException ex) {


JOptionPane.showMessageDialog(null, "Please enter a
valid number!");
}
}
} catch (ParseException ex) {
JOptionPane.showMessageDialog(
null,
"Invalid date format. Please use yyyy-MM-dd
format.",
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
});

// Tạo container cho danh sách sách mượn


borrowedBookContainer = new JPanel();
borrowedBookContainer.setLayout(new BoxLayout(borrowedBookContainer,
BoxLayout.Y_AXIS));
borrowedBookContainer.setBorder(BorderFactory.createEmptyBorder(10, 0, 10,
10));
borrowedBookContainer.setOpaque(true);
borrowedBookContainer.setBackground(Color.WHITE);

// Tạo JScrollPane bao quanh borrowedBookContainer


JScrollPane scrollPane = new JScrollPane(borrowedBookContainer);

scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBorder(BorderFactory.createEmptyBorder()); // Loại bỏ viền
mặc định
scrollPane.getViewport().setBackground(Color.WHITE); // Đặt màu nền cho
viewport

// Tạo panel chính chứa tất cả


borrowedBookPanel = new JPanel(new BorderLayout());
borrowedBookPanel.add(titlePanel, BorderLayout.NORTH);
borrowedBookPanel.add(scrollPane, BorderLayout.CENTER);
borrowedBookPanel.add(buttonPanel, BorderLayout.SOUTH);
addBorrowedBook();
// Làm mới giao diện
borrowedBookPanel.revalidate();
borrowedBookPanel.repaint();
}

private void addBorrowedBook() {


// Clear existing content
borrowedBookContainer.removeAll();

// Get borrowed documents from database for current user


for (User user : InitInformation.users) {
List<BorrowedDocument> borrowedDocuments =
DatabaseConnection.getBorrowedDocumentsByUserId(user.getId());
// List<BorrowedDocument> borrowedDocuments =
DatabaseConnection.getBorrowedDocumentsByUserId(currentUser.getId());

for (BorrowedDocument borrowedDoc : borrowedDocuments) {


Document document = borrowedDoc.getDocument();

// Create panel for borrowed book


JPanel bookPanel = new JPanel();
bookPanel.setLayout(new BoxLayout(bookPanel, BoxLayout.X_AXIS));
bookPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10,
10));
bookPanel.setBackground(colorButton);

Dimension fixedSize = new Dimension(890, 190);


bookPanel.setPreferredSize(fixedSize);
bookPanel.setMaximumSize(fixedSize);
bookPanel.setMinimumSize(fixedSize);

// Add book info


JPanel infoPanel = new JPanel();
infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
infoPanel.setBackground(colorButton);
infoPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));

infoPanel.add(new JLabel("User ID: " + user.getId() + " - " +


user.getName()));
infoPanel.add(new JLabel("Book ID: " + document.getId()));
infoPanel.add(new JLabel("Title: " + document.getTitle()));
infoPanel.add(new JLabel("Author: " + document.getAuthor()));
infoPanel.add(new JLabel("Publisher: " + document.getPublisher()));
infoPanel.add(new JLabel("Category: " + document.getCategory()));
infoPanel.add(new JLabel("Borrowed Quantity: " +
borrowedDoc.getQuantity()));
infoPanel.add(new JLabel("Borrow Date: " +
borrowedDoc.getBorrowedDate()));
infoPanel.add(new JLabel("Return Date: " +
borrowedDoc.getReturnDate()));

bookPanel.add(infoPanel);
bookPanel.add(Box.createHorizontalGlue());

// Add return button


JButton returnButton = new JButton(returnedBookIcon);
returnButton.setBackground(colorBackground);
returnButton.setOpaque(false);
returnButton.setBorderPainted(false);
returnButton.setFocusPainted(false);
returnButton.setPreferredSize(new Dimension(50, 50));

returnButton.addActionListener(e -> {
if (user.returnDocument(document, borrowedDoc.getQuantity(),
InitInformation.library)) {
borrowedBookContainer.remove(bookPanel);
borrowedBookContainer.revalidate();
borrowedBookContainer.repaint();
}
});

bookPanel.add(returnButton);
borrowedBookContainer.add(bookPanel);
borrowedBookContainer.add(Box.createRigidArea(new Dimension(0,
10)));
}

borrowedBookContainer.revalidate();
borrowedBookContainer.repaint();
}
}

private void upImage() {


ImageIcon originalIcon6 = new ImageIcon("lma\\src\\resource\\
returnBook.png");
Image scaledImage6 = originalIcon6.getImage().getScaledInstance(45, 45,
Image.SCALE_SMOOTH);
returnedBookIcon = new ImageIcon(scaledImage6);
if (returnedBookIcon.getIconWidth() == -1) {
System.out.println("Hình ảnh không thể tải ở adminUI .");
}

ImageIcon originalIcon5 = new ImageIcon("lma\\src\\resource\\logout.png");


Image scaledImage5 = originalIcon5.getImage().getScaledInstance(45, 45,
Image.SCALE_SMOOTH);
infoIcon = new ImageIcon(scaledImage5);
if (infoIcon.getIconWidth() == -1) {
System.out.println("Hình ảnh không thể tải ở adminUI .");
}

homeIcon = new ImageIcon("lma\\src\\resource\\homeicon.png");


ImageIcon originalIcon3 = new ImageIcon("lma\\src\\resource\\
bookicon.png");
Image scaledImage3 = originalIcon3.getImage().getScaledInstance(50, 50,
Image.SCALE_SMOOTH);
bookIcon = new ImageIcon(scaledImage3);
if (bookIcon.getIconWidth() == -1) {
System.out.println("Hình ảnh không thể tải ở adminUI .");
}

ImageIcon originalIcon2 = new ImageIcon("lma\\src\\resource\\


borrowbook.png");
Image scaledImage2 = originalIcon2.getImage().getScaledInstance(50, 50,
Image.SCALE_SMOOTH);
borrowBookIcon = new ImageIcon(scaledImage2);

ImageIcon originalIcon1 = new ImageIcon("lma\\src\\resource\\


chaticon.png");
Image scaledImage1 = originalIcon1.getImage().getScaledInstance(50, 50,
Image.SCALE_SMOOTH);
notificationIcon = new ImageIcon(scaledImage1);

ImageIcon originalIcon = new ImageIcon("lma\\src\\resource\\usericon.png");


Image scaledImage = originalIcon.getImage().getScaledInstance(50, 50,
Image.SCALE_SMOOTH);
userIcon = new ImageIcon(scaledImage);

ImageIcon originalIcon0 = new ImageIcon("lma\\src\\resource\\


newbackground.png");
Image scaledImage0 = originalIcon0.getImage().getScaledInstance(510, 380,
Image.SCALE_SMOOTH);
background = new ImageIcon(scaledImage0);
if (background.getIconWidth() == -1) {
System.out.println("Hình ảnh không thể tải ở adminUI .");

}
originalIcon0 = new ImageIcon("lma\\src\\resource\\edit.png"); //
SửaaddUserPanelại đường dẫn nếu
scaledImage0 = originalIcon0.getImage().getScaledInstance(25, 25,
Image.SCALE_SMOOTH);
edit = new ImageIcon(scaledImage0);
if (edit.getIconWidth() == -1) {
System.out.println("Hình ảnh không thể tải ở adminUI .");

private RoundedButton createButton(int radius, int fontSize, String text, int


width, int height, Color color,
Color hoverColor, boolean check) {
RoundedButton Button = new RoundedButton(text, radius, fontSize, check);
Button.setBackgroundColor(color);
Button.setHoverColor(hoverColor);
Button.setPreferredSize(new Dimension(width, height));
return Button;

public JPanel createTextField(String id, ImageIcon icon, int column, int


radius, String text) {
RoundedTextField textField = new RoundedTextField(column, radius, text);
textFieldMap.put(id, textField); // addUserPanelưu vào map với ID

JPanel textPanel = new JPanel(new BorderLayout());


textField.setBackground(colorBackground);
textField.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

if (icon != null) {
JLabel textLabel = new JLabel(icon);
textPanel.add(textLabel, BorderLayout.WEST);
}

textPanel.setOpaque(false);
textPanel.add(textField, BorderLayout.CENTER);

return textPanel;
}

public String getTextFromField(String id) {


RoundedTextField textField = textFieldMap.get(id);
return textField != null ? textField.getText() : null;
}

public JPanel createTextField(String id, ImageIcon icon, int column, int


radius, String text, String labelText,
boolean check) {
RoundedTextField textField = new RoundedTextField(column, radius, text);
textFieldMap.put(id, textField); // lưu vào map với ID
JPanel textPanel = new JPanel(new BorderLayout());
textField.setBackground(colorButton);
textField.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
textField.setEditable(check);
textField.setFocusable(check);

// Panel để chứa label và icon (nếu có)


JPanel labelPanel = new JPanel();
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.X_AXIS));
labelPanel.setOpaque(false); // giữ nền trong suốt

if (labelText != null && !labelText.isEmpty()) {


JLabel textLabel = new JLabel(labelText);
textLabel.setForeground(Color.BLACK); // hoặc màu khác theo ý muốn
labelPanel.add(textLabel);
}

if (icon != null) {
JLabel iconLabel = new JLabel(icon);
labelPanel.add(Box.createRigidArea(new Dimension(5, 0))); // khoảng
cách giữa label và icon
labelPanel.add(iconLabel);
}

textPanel.setOpaque(false);
textPanel.add(labelPanel, BorderLayout.WEST); // Thêm label panel vào WEST
textPanel.add(textField, BorderLayout.CENTER); // Text field ở CENTER

return textPanel;
}

private class ButtonActionListener implements ActionListener {

private JButton selectedButton = null; // Nút hiện tại được chọn

@Override
public void actionPerformed(ActionEvent e) {
JButton currentButton = (JButton) e.getSource(); // Nút được bấm

// Khôi phục màu nút trước đó (nếu có và không phải nút hiện tại)
if (selectedButton != null && selectedButton != currentButton) {
selectedButton.setBackground(colorBackground); // Màu nền gốc
selectedButton.setOpaque(false);
}

// Đổi màu nút hiện tại


currentButton.setBackground(colorButton); // Màu được chọn
currentButton.setOpaque(true);

selectedButton = currentButton; // Cập nhật nút được chọn

// Chuyển đổi panel hoặc thực hiện hành động


String actionCommand = currentButton.getActionCommand();
switch (actionCommand) {
case "homepanel":
cardLayout.show(contentPane, "home");
break;
case "chatpanel":
cardLayout.show(contentPane, "ChatPanel");
break;
case "userpanel":
cardLayout.show(contentPane, "userManagement");
userCardLayout.show(userContentPane, "list");
break;
case "bookpanel":
cardLayout.show(contentPane, "bookManagement");
bookCardLayout.show(bookContentPane, "list");

break;
case "managepanel":
cardLayout.show(contentPane, "borrowedBookList");
break;

}
}
}

public static JPanel createMovingImagePanel() {


JPanel panel = new JPanel() {
private ImageIcon[] images = new ImageIcon[]{
new ImageIcon("lma\\lma\\src\\resource\\loading(1).png"),
new ImageIcon("lma\\lma\\src\\resource\\loading(2).png"),
new ImageIcon("lma\\lma\\src\\resource\\loading(3).png"),
new ImageIcon("lma\\lma\\src\\resource\\loading(4).png")
};
private int currentImageIndex = 0;
private int x = 0;
private int y = 100;

// Tạo Timer để thay đổi ImageIcon và di chuyển hình ảnh


{
Timer timer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Thay đổi ImageIcon (di chuyển tới hình ảnh tiếp theo
trong mảng)
currentImageIndex = (currentImageIndex + 1) %
images.length;

// Cập nhật vị trí di chuyển


x += 5;
if (x > getWidth()) {
x = -images[currentImageIndex].getIconWidth(); // Khi
hình ảnh ra ngoài màn hình, quay lại
// từ đầu
}

repaint(); // Vẽ lại JPanel để hiển thị ImageIcon mới


}
});

timer.start(); // Bắt đầu Timer


}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Vẽ ImageIcon tại vị trí (x, y)
images[currentImageIndex].paintIcon(this, g, x, y);
}
};

return panel;
}

public void setButtonLogoutListener(ActionListener listener) {


logoutButton.addActionListener(listener);
}

You might also like