├── img
├── demo.png
├── russian.png
├── romanian.png
├── howtoconnect.png
├── chooselanguage.png
├── manageyourtable.png
└── internationalization.png
├── .gitignore
├── .github
└── workflows
│ └── maven.yml
├── pom.xml
├── test
└── java
│ └── sms
│ └── sms
│ ├── ConnectionViewTest.java
│ ├── DBHandlerTest.java
│ └── ManagementViewTest.java
├── README.md
├── src
└── main
│ └── java
│ └── sms
│ ├── Translator.java
│ ├── Student.java
│ ├── ConnectionView.java
│ ├── ManagementView.java
│ └── DBHandler.java
└── Languages.xml
/img/demo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Yashmerino/student-management-system/HEAD/img/demo.png
--------------------------------------------------------------------------------
/img/russian.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Yashmerino/student-management-system/HEAD/img/russian.png
--------------------------------------------------------------------------------
/img/romanian.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Yashmerino/student-management-system/HEAD/img/romanian.png
--------------------------------------------------------------------------------
/img/howtoconnect.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Yashmerino/student-management-system/HEAD/img/howtoconnect.png
--------------------------------------------------------------------------------
/img/chooselanguage.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Yashmerino/student-management-system/HEAD/img/chooselanguage.png
--------------------------------------------------------------------------------
/img/manageyourtable.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Yashmerino/student-management-system/HEAD/img/manageyourtable.png
--------------------------------------------------------------------------------
/img/internationalization.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Yashmerino/student-management-system/HEAD/img/internationalization.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 | pom.xml.tag
3 | pom.xml.releaseBackup
4 | pom.xml.versionsBackup
5 | pom.xml.next
6 | release.properties
7 | dependency-reduced-pom.xml
8 | buildNumber.properties
9 | .mvn/timing.properties
10 | # https://github.com/takari/maven-wrapper#usage-without-binary-jar
11 | .mvn/wrapper/maven-wrapper.jar
12 |
13 | # Eclipse m2e generated files
14 | # Eclipse Core
15 | .project
16 | # JDT-specific (Eclipse Java Development Tools)
17 | .classpath
18 | org.eclipse.jdt.core.prefs
19 | # .class files
20 | *.class
--------------------------------------------------------------------------------
/.github/workflows/maven.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time
2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven
3 |
4 | # This workflow uses actions that are not certified by GitHub.
5 | # They are provided by a third-party and are governed by
6 | # separate terms of service, privacy policy, and support
7 | # documentation.
8 |
9 | name: Java CI with Maven
10 |
11 | on:
12 | push:
13 | branches: [ "master" ]
14 | pull_request:
15 | branches: [ "master" ]
16 |
17 | jobs:
18 | build:
19 |
20 | runs-on: ubuntu-latest
21 |
22 | steps:
23 | - uses: actions/checkout@v3
24 | - name: Set up JDK 11
25 | uses: actions/setup-java@v3
26 | with:
27 | java-version: '11'
28 | distribution: 'temurin'
29 | cache: maven
30 | - name: Build with Maven
31 | run: mvn -B package --file pom.xml
32 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
4 | 4.0.0
5 | S-M-S
6 | S-M-S
7 | 0.0.1-SNAPSHOT
8 |
9 |
10 | 1.6
11 | 1.6
12 |
13 |
14 |
15 |
16 |
17 | org.openjfx
18 | javafx-swing
19 | 16
20 |
21 |
22 |
23 |
24 | mysql
25 | mysql-connector-java
26 | 8.0.27
27 |
28 |
29 |
30 |
31 | org.easytesting
32 | fest-swing
33 | 1.2.1
34 |
35 |
36 |
37 |
38 | jdom
39 | jdom
40 | 1.0
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/test/java/sms/sms/ConnectionViewTest.java:
--------------------------------------------------------------------------------
1 | package sms;
2 |
3 | import org.fest.swing.fixture.FrameFixture;
4 | import org.junit.After;
5 | import org.junit.Before;
6 | import org.junit.Test;
7 |
8 | /**
9 | * The class that tests ConnectionView class' GUI
10 | *
11 | * @author Artiom
12 | *
13 | */
14 | public class ConnectionViewTest {
15 |
16 | private FrameFixture connectionFrame;
17 | private ConnectionView connectionView;
18 |
19 | @Before
20 | public void setUp() {
21 | connectionView = new ConnectionView();
22 | connectionFrame = new FrameFixture(ConnectionView.connectionFrame);
23 | }
24 |
25 | @After
26 | public void tearDown() {
27 | connectionFrame.cleanUp();
28 | }
29 |
30 | @Test
31 | public void emptyFieldsTest() {
32 | connectionFrame.button("connectButton").click();
33 | connectionFrame.optionPane().requireErrorMessage().requireMessage("Please fill in all the empty fields!");
34 | }
35 |
36 | @Test
37 | public void wrongDatabaseUrl() {
38 | connectionFrame.textBox("loginField").enterText("root");
39 | connectionFrame.textBox("passwordField").enterText("simplepassword123");
40 | connectionFrame.textBox("databaseUrlField").enterText("dawgfaea");
41 | connectionFrame.button("connectButton").click();
42 | connectionFrame.optionPane().requireErrorMessage().requireMessage(
43 | "Connection with the database hasn't been established!\nPlease check your credentials!");
44 | }
45 |
46 | @Test
47 | public void correctCredentials() {
48 | connectionFrame.textBox("loginField").enterText("root");
49 | connectionFrame.button("connectButton").click();
50 | connectionFrame.optionPane().requireMessage("Connection with the database has been successfully established!");
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
Student Management System
2 | 
3 |
4 | # How to run the app?
5 |
6 | To run this application:
7 |
8 | * You have to have Java installed. You can download it here: Link
9 | * After that accees the Releases section and download the last version of the application.
10 | * Right-click the zipped folder saved to your computer and choose "Extract All". Run the application and enjoy!
11 |
12 | Demonstration
13 | 
14 |
15 | # Student Management System has 3 languages!
16 |
17 | In order to change the language, click this button and select out of 3 languages your preferred language(English will be set by default):
18 | 
19 | 
20 |
21 | Russian
22 | 
23 |
24 | Romanian
25 | 
26 |
27 | # How to connect to my database?
28 |
29 | To connect to the desired database, you have to type your database url, login and password(if you don't have one, just leave the field blank)
30 | 
31 |
32 | If the connection was successfully established, this window will show up where you can start adding faculties/courses/students!
33 | 
34 |
--------------------------------------------------------------------------------
/test/java/sms/sms/DBHandlerTest.java:
--------------------------------------------------------------------------------
1 | package sms;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import java.sql.SQLException;
6 |
7 | import org.junit.Before;
8 | import org.junit.Test;
9 |
10 | /**
11 | * The class that tests DBHandler class' methods
12 | *
13 | * @author Artiom
14 | *
15 | */
16 | public class DBHandlerTest {
17 |
18 | public DBHandlerTest() {
19 | // In case I set a password for the database
20 | // DBHandler.setPassword("password");
21 | }
22 |
23 | @Before
24 | public void init() {
25 | // Create tables in order to test methods that modifies them
26 | DBHandler.createTables();
27 | }
28 |
29 | @Test
30 | public void checkIfTableExistsTest() throws SQLException {
31 |
32 | boolean result = DBHandler.checkIfTableExists("Test");
33 | assertEquals(false, result);
34 |
35 | result = DBHandler.checkIfTableExists("students");
36 | assertEquals(true, result);
37 |
38 | result = DBHandler.checkIfTableExists("courses");
39 | assertEquals(true, result);
40 |
41 | result = DBHandler.checkIfTableExists("faculties");
42 | assertEquals(true, result);
43 |
44 | result = DBHandler.checkIfTableExists("Students");
45 | assertEquals(false, result);
46 |
47 | result = DBHandler.checkIfTableExists("coures");
48 | assertEquals(false, result);
49 |
50 | result = DBHandler.checkIfTableExists("5161521");
51 | assertEquals(false, result);
52 |
53 | result = DBHandler.checkIfTableExists("=-/*-+");
54 | assertEquals(false, result);
55 |
56 | result = DBHandler.checkIfTableExists("");
57 | assertEquals(false, result);
58 |
59 | result = DBHandler.checkIfTableExists(" ");
60 | assertEquals(false, result);
61 |
62 | }
63 |
64 | @Test
65 | public void addFacultyTest() throws SQLException {
66 | boolean result = DBHandler.addFaculty("Test");
67 | assertEquals(true, result);
68 |
69 | result = DBHandler.addFaculty("students");
70 | assertEquals(true, result);
71 |
72 | result = DBHandler.addFaculty("automatica");
73 | assertEquals(true, result);
74 |
75 | result = DBHandler.addFaculty("calculatoare");
76 | assertEquals(true, result);
77 |
78 | result = DBHandler.addFaculty("electronica");
79 | assertEquals(true, result);
80 |
81 | result = DBHandler.addFaculty("y y y y y");
82 | assertEquals(true, result);
83 |
84 | result = DBHandler.addFaculty("5161521");
85 | assertEquals(true, result);
86 |
87 | result = DBHandler.addFaculty("=-/*-+");
88 | assertEquals(true, result);
89 |
90 | result = DBHandler.addFaculty("");
91 | assertEquals(true, result);
92 |
93 | result = DBHandler.addFaculty(" ");
94 | assertEquals(true, result);
95 | }
96 |
97 | @Test
98 | public void addCourse() throws SQLException {
99 | boolean result = DBHandler.addCourse("matematica", "Test", 12);
100 | assertEquals(true, result);
101 |
102 | result = DBHandler.addCourse("bigint", "students", 999999999);
103 | assertEquals(true, result);
104 |
105 | result = DBHandler.addCourse("negativeint", "automatica", -9515141);
106 | assertEquals(true, result);
107 |
108 | result = DBHandler.addCourse("zero", "calculatoare", 0);
109 | assertEquals(true, result);
110 |
111 | result = DBHandler.addCourse("fizica", "electronica", 6);
112 | assertEquals(true, result);
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/src/main/java/sms/Translator.java:
--------------------------------------------------------------------------------
1 | package sms;
2 |
3 | import java.io.File;
4 | import java.util.HashMap;
5 | import java.util.Vector;
6 |
7 | import javax.xml.parsers.DocumentBuilder;
8 | import javax.xml.parsers.DocumentBuilderFactory;
9 |
10 | import org.w3c.dom.Document;
11 | import org.w3c.dom.Element;
12 | import org.w3c.dom.Node;
13 | import org.w3c.dom.NodeList;
14 |
15 | /**
16 | * The enum that represents the selected language
17 | *
18 | * @author Artiom
19 | *
20 | */
21 | enum Language {
22 | ENG, RU, RO
23 | }
24 |
25 | /**
26 | * The class that handles internationalization and language changes
27 | *
28 | * @author Artiom
29 | *
30 | */
31 | public class Translator {
32 | /**
33 | * HashMap that holds tags as keys and messages as values
34 | */
35 | private static HashMap messages;
36 | /**
37 | * The variable that holds currently selected language
38 | */
39 | private static Language language;
40 |
41 | static {
42 | messages = new HashMap();
43 | setLanguage(Language.ENG);
44 | }
45 |
46 | /**
47 | * The constructor
48 | */
49 | public Translator() {
50 |
51 | }
52 |
53 | /**
54 | * Gets the messages in the language selected by the user
55 | */
56 | public static void getMessagesFromXML() {
57 | try {
58 | // An array that will store keys
59 | Vector keys = new Vector();
60 | // An array that will store values
61 | Vector values = new Vector();
62 |
63 | // Reading the .xml document
64 | DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
65 | DocumentBuilder builder = factory.newDocumentBuilder();
66 | Document document = builder.parse(new File("Languages.xml"));
67 | document.getDocumentElement().normalize();
68 | // Get all elements with tag key
69 | NodeList keysList = document.getElementsByTagName("key");
70 | // Get all elements with tag val
71 | NodeList valuesList = document.getElementsByTagName("val");
72 |
73 | for (int i = 0; i < keysList.getLength(); i++) {
74 | // Add to the keys array every met key in the .xml document
75 | Node keyNode = keysList.item(i);
76 | Element keyElement = (Element) keyNode;
77 | keys.add(keyElement.getAttribute("value"));
78 | }
79 |
80 | for (int j = 0; j < valuesList.getLength(); j++) {
81 | Node valueNode = valuesList.item(j);
82 | Element valueElement = (Element) valueNode;
83 |
84 | // Add to the values array every value met in the .xml document according to the
85 | // selected language
86 | if (valueElement.getAttribute("lang").equals(language.toString())) {
87 | values.add(valueElement.getTextContent());
88 | }
89 | }
90 |
91 | // Putting keys and values in the messages HashMap
92 | for (int i = 0; i < keys.size(); i++)
93 | messages.put(keys.get(i), values.get(i));
94 |
95 | } catch (Exception e) {
96 | e.printStackTrace();
97 | }
98 | }
99 |
100 | /**
101 | * Gets the message in dependance of the key
102 | *
103 | * @param key - The key for the message in the HashMap
104 | * @return The message that contains that key
105 | */
106 | public static String getValue(final String key) {
107 | return messages.get(key);
108 | }
109 |
110 | /**
111 | * @return the currently selected language
112 | */
113 | public static Language getLanguage() {
114 | return language;
115 | }
116 |
117 | /**
118 | * @param language - Language user wishes to select
119 | */
120 | public static void setLanguage(Language language) {
121 | Translator.language = language;
122 | }
123 | }
124 |
--------------------------------------------------------------------------------
/src/main/java/sms/Student.java:
--------------------------------------------------------------------------------
1 | package sms;
2 |
3 | import java.util.Date;
4 |
5 | enum Gender {
6 | Male, Female
7 | }
8 |
9 | /**
10 | * The class that holds and manages the information about students
11 | *
12 | * @author Artiom
13 | *
14 | */
15 | public class Student {
16 | /**
17 | * The name of the student
18 | */
19 | private String name;
20 |
21 | /**
22 | * The surname of the student
23 | */
24 | private String surname;
25 |
26 | /**
27 | * The age of the student
28 | */
29 | private int age;
30 |
31 | /**
32 | * The gender of the student
33 | */
34 | private Gender gender;
35 |
36 | /**
37 | * The course that the student attends
38 | */
39 | private String course;
40 |
41 | /**
42 | * The date when the student started the course
43 | */
44 | private Date started;
45 |
46 | /**
47 | * The date when the student started the course
48 | */
49 | private Date graduation;
50 |
51 | /**
52 | * The unique id of the student
53 | */
54 | int id;
55 |
56 | /**
57 | * The counter that is increased by one everytime a new instance is created,
58 | * used for ID system
59 | */
60 | static int counter;
61 |
62 | /**
63 | * Counter is set to 1 initially
64 | */
65 | static {
66 | counter = 1;
67 | }
68 |
69 | /**
70 | * Default constructor
71 | */
72 | public Student() {
73 | // The unique id of the student is set to value of the counter
74 | this.id = counter;
75 | // The counter after that is increased by one
76 | counter++;
77 | }
78 |
79 | /**
80 | * @return The name of the student
81 | */
82 | public String getName() {
83 | return name;
84 | }
85 |
86 | /**
87 | * @param name - The name to set to the student
88 | */
89 | public void setName(final String name) {
90 | this.name = name;
91 | }
92 |
93 | /**
94 | * @return The surname of the student
95 | */
96 | public String getSurname() {
97 | return surname;
98 | }
99 |
100 | /**
101 | * @param surname - The surname to set to the student
102 | */
103 | public void setSurname(final String surname) {
104 | this.surname = surname;
105 | }
106 |
107 | /**
108 | * @return The age of the student
109 | */
110 | public int getAge() {
111 | return age;
112 | }
113 |
114 | /**
115 | * @param age - The age to set to the student
116 | */
117 | public void setAge(final int age) {
118 | this.age = age;
119 | }
120 |
121 | /**
122 | * @return The course that the student attends
123 | */
124 | public String getCourse() {
125 | return course;
126 | }
127 |
128 | /**
129 | * @param course - The course to set to the student
130 | */
131 | public void setCourse(final String course) {
132 | this.course = course;
133 | }
134 |
135 | /**
136 | * @return The id of the student
137 | */
138 | public int getId() {
139 | return id;
140 | }
141 |
142 | /**
143 | * @return The date when student started the course
144 | */
145 | public Date getStarted() {
146 | return started;
147 | }
148 |
149 | /**
150 | * @param started - The date when student started attending the course
151 | */
152 | public void setStarted(final Date started) {
153 | this.started = started;
154 | }
155 |
156 | /**
157 | * @return The gender of the student
158 | */
159 | public Gender getGender() {
160 | return gender;
161 | }
162 |
163 | /**
164 | * @param gender - The gender to set to the student
165 | */
166 | public void setGender(final Gender gender) {
167 | this.gender = gender;
168 | }
169 |
170 | /**
171 | * @return the date when student will graduate
172 | */
173 | public Date getGraduation() {
174 | return graduation;
175 | }
176 |
177 | /**
178 | * @param graduation - The graduation's date to set to the student
179 | */
180 | public void setGraduation(final Date graduation) {
181 | this.graduation = graduation;
182 | }
183 | }
184 |
--------------------------------------------------------------------------------
/src/main/java/sms/ConnectionView.java:
--------------------------------------------------------------------------------
1 | package sms;
2 |
3 | import java.awt.BorderLayout;
4 | import java.awt.Color;
5 | import java.awt.EventQueue;
6 | import java.awt.Font;
7 | import java.awt.SystemColor;
8 | import java.awt.event.ActionEvent;
9 | import java.awt.event.ActionListener;
10 |
11 | import javax.swing.JButton;
12 | import javax.swing.JFrame;
13 | import javax.swing.JLabel;
14 | import javax.swing.JOptionPane;
15 | import javax.swing.JPanel;
16 | import javax.swing.JPasswordField;
17 | import javax.swing.JTextField;
18 |
19 | /**
20 | * The class that holds the front-end connection part of the application and
21 | * manages the actions performed out there
22 | *
23 | * @author Artiom
24 | *
25 | */
26 | public class ConnectionView {
27 |
28 | /**
29 | * The contents of the connection window where you have to connect to a database
30 | */
31 | static JFrame connectionFrame;
32 |
33 | /**
34 | * The text field that stores the login the user has written
35 | */
36 | private JTextField loginField;
37 | private JPasswordField passwordField;
38 | private JTextField databaseUrlField;
39 |
40 | /**
41 | * Launch the application.
42 | */
43 | public static void main(String[] args) {
44 | EventQueue.invokeLater(new Runnable() {
45 | public void run() {
46 | // Reading messages in dependance of the selected language(by default ENG)
47 | Translator.setLanguage(Language.ENG);
48 | Translator.getMessagesFromXML();
49 |
50 | try {
51 | ConnectionView window = new ConnectionView();
52 | window.connectionFrame.setVisible(true);
53 | } catch (Exception e) {
54 | e.printStackTrace();
55 | }
56 | }
57 | });
58 | }
59 |
60 | /**
61 | * Create the application.
62 | */
63 | public ConnectionView() {
64 | initialize();
65 | // Make it visible in constructor, in order to make tests in
66 | // ConnectionViewTest.java work
67 | connectionFrame.setVisible(true);
68 | }
69 |
70 | /**
71 | * Initialize the contents of the frame.
72 | */
73 | private void initialize() {
74 | connectionFrame = new JFrame();
75 | connectionFrame.setBounds(100, 100, 640, 480);
76 | connectionFrame.setResizable(false);
77 | connectionFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
78 | connectionFrame.setTitle(Translator.getValue("sms"));
79 |
80 | // The blue-colored panel in the top part of the application
81 | JPanel topPanel = new JPanel();
82 | topPanel.setBackground(SystemColor.textHighlight);
83 | connectionFrame.getContentPane().add(topPanel, BorderLayout.NORTH);
84 |
85 | // The text that informs the user that they have to connect to a database
86 | JLabel connectText = new JLabel(Translator.getValue("connectText"));
87 | connectText.setForeground(new Color(255, 255, 255));
88 | connectText.setFont(new Font("Tahoma", Font.PLAIN, 25));
89 | topPanel.add(connectText);
90 |
91 | // The panel in the bottom part of the application
92 | JPanel bottomPanel = new JPanel();
93 | connectionFrame.getContentPane().add(bottomPanel, BorderLayout.CENTER);
94 |
95 | // The text that informs the user where they have to type the login
96 | JLabel loginText = new JLabel(Translator.getValue("loginText"));
97 | loginText.setBounds(68, 134, 162, 25);
98 | loginText.setFont(new Font("Tahoma", Font.PLAIN, 12));
99 |
100 | // The text that informs the user where they have to type the password
101 | JLabel passwordText = new JLabel(Translator.getValue("passwordText"));
102 | passwordText.setBounds(68, 174, 162, 25);
103 | passwordText.setFont(new Font("Tahoma", Font.PLAIN, 12));
104 |
105 | // Initializes the text field where user writes the login
106 | loginField = new JTextField();
107 | loginField.setName("loginField");
108 | loginField.setBounds(240, 139, 330, 20);
109 | loginField.setColumns(10);
110 |
111 | // Initializes the text field where user writes the password
112 | passwordField = new JPasswordField();
113 | passwordField.setName("passwordField");
114 | passwordField.setBounds(240, 179, 330, 20);
115 |
116 | // The field where user should write the database url
117 | databaseUrlField = new JTextField();
118 | databaseUrlField.setName("databaseUrlField");
119 | databaseUrlField.setText("jdbc:mysql://localhost:3306/studentsdb");
120 | databaseUrlField.setColumns(10);
121 | databaseUrlField.setBounds(240, 96, 330, 20);
122 |
123 | // The text that informs user where they have to write database url
124 | JLabel databaseUrlText = new JLabel(Translator.getValue("databaseUrlText"));
125 | databaseUrlText.setFont(new Font("Tahoma", Font.PLAIN, 12));
126 | databaseUrlText.setBounds(68, 91, 162, 25);
127 |
128 | // The button that changes the langauge of the application
129 | JButton changeLanguageButton = new JButton(Translator.getValue("changeLanguage"));
130 |
131 | // Actions to perform when "Change language" button is clicked
132 | changeLanguageButton.addActionListener(new ActionListener() {
133 | public void actionPerformed(ActionEvent e) {
134 | Language selectedLanguage = (Language) JOptionPane.showInputDialog(null, Translator.getValue("sms"),
135 | Translator.getValue("selectLanguage"), JOptionPane.QUESTION_MESSAGE, null, Language.values(),
136 | Language.ENG.toString());
137 |
138 | if (selectedLanguage != null)
139 | Translator.setLanguage(selectedLanguage);
140 | else
141 | return;
142 |
143 | Translator.getMessagesFromXML();
144 |
145 | connectionFrame.dispose();
146 | new ConnectionView();
147 | }
148 | });
149 |
150 | changeLanguageButton.setFont(new Font("Tahoma", Font.PLAIN, 12));
151 | changeLanguageButton.setBounds(480, 365, 135, 25);
152 | bottomPanel.add(changeLanguageButton);
153 |
154 | // The button to press after the login and password were written
155 | JButton connectButton = new JButton(Translator.getValue("connectButton"));
156 | connectButton.setName("connectButton");
157 | connectButton.setBounds(221, 290, 190, 42);
158 | connectButton.setFont(new Font("Tahoma", Font.PLAIN, 20));
159 |
160 | // Execute connection and create a table when "Connect" button pressed
161 | connectButton.addActionListener(new ActionListener() {
162 | public void actionPerformed(ActionEvent e) {
163 | // If one of the fields are empty then warn user about it
164 | if (loginField.getText().equals("") || databaseUrlField.getText().equals("")) {
165 | JOptionPane.showMessageDialog(new JFrame(), Translator.getValue("fillEmptyFields"),
166 | Translator.getValue("error"), JOptionPane.ERROR_MESSAGE);
167 | } else {
168 | // Get login, password and database url from fields and set them for database
169 | // handler
170 | DBHandler.setLogin(loginField.getText());
171 | DBHandler.setPassword(passwordField.getText());
172 | DBHandler.setDatabaseUrl(databaseUrlField.getText());
173 |
174 | // If table has\hasn't been successfully created then inform the user about that
175 | if (DBHandler.createTables()) {
176 | JOptionPane.showMessageDialog(new JFrame(), Translator.getValue("connectionEstablished"),
177 | Translator.getValue("success"), JOptionPane.INFORMATION_MESSAGE);
178 |
179 | // Open a new window where you can manage the table and close the old one
180 | ManagementView.main(null);
181 | connectionFrame.dispose();
182 |
183 | } else {
184 | JOptionPane.showMessageDialog(new JFrame(), Translator.getValue("connectionNotEstablished"),
185 | Translator.getValue("error"), JOptionPane.ERROR_MESSAGE);
186 | }
187 | }
188 |
189 | }
190 | });
191 |
192 | bottomPanel.setLayout(null);
193 | bottomPanel.add(passwordText);
194 | bottomPanel.add(loginText);
195 | bottomPanel.add(passwordField);
196 | bottomPanel.add(loginField);
197 | bottomPanel.add(connectButton);
198 | bottomPanel.add(databaseUrlText);
199 | bottomPanel.add(databaseUrlField);
200 |
201 | }
202 | }
203 |
--------------------------------------------------------------------------------
/test/java/sms/sms/ManagementViewTest.java:
--------------------------------------------------------------------------------
1 | package sms;
2 |
3 | import org.fest.swing.fixture.FrameFixture;
4 | import org.junit.After;
5 | import org.junit.Before;
6 | import org.junit.Test;
7 |
8 | /**
9 | * The class that tests ManagementView class' GUI
10 | *
11 | * @author Artiom
12 | *
13 | */
14 | public class ManagementViewTest {
15 |
16 | private FrameFixture managementFrame;
17 | private ManagementView managementView;
18 |
19 | @Before
20 | public void setUp() {
21 | managementView = new ManagementView();
22 | managementFrame = new FrameFixture(ManagementView.managementFrame);
23 | }
24 |
25 | @After
26 | public void tearDown() {
27 | managementFrame.cleanUp();
28 | }
29 |
30 | @Test
31 | public void emptyFieldsTest() {
32 | managementFrame.button("addButton").click();
33 | if (DBHandler.getCourses().length > 0)
34 | managementFrame.optionPane().requireErrorMessage().requireMessage("Please fill in all the fields!");
35 | else
36 | managementFrame.optionPane().requireErrorMessage()
37 | .requireMessage("You can't add a student yet!\nAdd a faculty and a course first!");
38 | }
39 |
40 | @Test
41 | public void deleteWithoutSelection() {
42 | managementFrame.button("deleteButton").click();
43 | managementFrame.optionPane().requireErrorMessage().requireMessage("No student has been selected!");
44 | }
45 |
46 | @Test
47 | public void disconnectWarning() {
48 | managementFrame.button("disconnectButton").click();
49 | managementFrame.optionPane().requireMessage("Do you want to disconnect from the current database?");
50 | }
51 |
52 | @Test
53 | public void addCourseSuccessfully() {
54 | if (DBHandler.checkIfElementExists(DBHandler.getCoursesTable(), "NewCourse"))
55 | DBHandler.deleteCourse("NewCourse");
56 |
57 | managementFrame.button("addCourseButton").click();
58 | if (DBHandler.getFaculties().length > 0) {
59 | managementFrame.optionPane().requireMessage("Type the name of the course");
60 | managementFrame.optionPane().textBox().enterText("NewCourse");
61 | managementFrame.optionPane().buttonWithText("OK").click();
62 | managementFrame.optionPane().buttonWithText("OK").click();
63 | managementFrame.optionPane().textBox().enterText("12");
64 | managementFrame.optionPane().buttonWithText("OK").click();
65 | managementFrame.optionPane().requireMessage("The course has been added successfully!");
66 | } else
67 | managementFrame.optionPane().requireErrorMessage()
68 | .requireMessage("You can't add a course!\nAdd a faculty first");
69 |
70 | }
71 |
72 | @Test
73 | public void addCourseWithoutName() {
74 | managementFrame.button("addCourseButton").click();
75 | if (DBHandler.getFaculties().length > 0) {
76 | managementFrame.optionPane().requireMessage("Type the name of the course");
77 | managementFrame.optionPane().buttonWithText("OK").click();
78 | managementFrame.optionPane().requireMessage("The course hasn't been added!\nPlease type a name for it!");
79 | } else
80 | managementFrame.optionPane().requireErrorMessage()
81 | .requireMessage("You can't add a course!\nAdd a faculty first");
82 |
83 | }
84 |
85 | @Test
86 | public void addCourseWithWrongDuration() {
87 | managementFrame.button("addCourseButton").click();
88 | if (DBHandler.getFaculties().length > 0) {
89 | managementFrame.optionPane().requireMessage("Type the name of the course");
90 | managementFrame.optionPane().textBox().enterText("NewCourse");
91 | managementFrame.optionPane().buttonWithText("OK").click();
92 | managementFrame.optionPane().buttonWithText("OK").click();
93 | managementFrame.optionPane().textBox().enterText("one year");
94 | managementFrame.optionPane().buttonWithText("OK").click();
95 | managementFrame.optionPane().requireMessage(
96 | "The course hasn't been added!\nPlease type the duration of the course without using other characters than digits!");
97 | } else
98 | managementFrame.optionPane().requireErrorMessage()
99 | .requireMessage("You can't add a course!\nAdd a faculty first");
100 |
101 | }
102 |
103 | @Test
104 | public void addCourseThatExists() {
105 | if (!DBHandler.checkIfElementExists(DBHandler.getCoursesTable(), "CourseAlreadyExists"))
106 | DBHandler.addCourse("CourseAlreadyExists", "Automatica", 12);
107 |
108 | managementFrame.button("addCourseButton").click();
109 | if (DBHandler.getFaculties().length > 0) {
110 | managementFrame.optionPane().requireMessage("Type the name of the course");
111 | managementFrame.optionPane().textBox().enterText("CourseAlreadyExists");
112 | managementFrame.optionPane().buttonWithText("OK").click();
113 | managementFrame.optionPane().buttonWithText("OK").click();
114 | managementFrame.optionPane().textBox().enterText("12");
115 | managementFrame.optionPane().buttonWithText("OK").click();
116 | managementFrame.optionPane().requireErrorMessage()
117 | .requireMessage("The course hasn't been added!\nThe course CourseAlreadyExists already exists!");
118 | } else
119 | managementFrame.optionPane().requireErrorMessage()
120 | .requireMessage("You can't add a course!\nAdd a faculty first");
121 |
122 | }
123 |
124 | @Test
125 | public void addFacultyThatExists() {
126 | if (!DBHandler.checkIfElementExists(DBHandler.getFacultiesTable(), "FacultyAlreadyExists"))
127 | DBHandler.addFaculty("FacultyAlreadyExists");
128 |
129 | managementFrame.button("addFacultyButton").click();
130 | managementFrame.optionPane().requireMessage("Type the name of the faculty");
131 | managementFrame.optionPane().textBox().enterText("FacultyAlreadyExists");
132 | managementFrame.optionPane().buttonWithText("OK").click();
133 | managementFrame.optionPane().requireErrorMessage()
134 | .requireMessage("The faculty hasn't been added!\nThe faculty FacultyAlreadyExists already exists!");
135 | }
136 |
137 | @Test
138 | public void addFacultySuccessfully() {
139 | if (DBHandler.checkIfElementExists(DBHandler.getFacultiesTable(), "NewFaculty"))
140 | DBHandler.deleteFaculty("NewFaculty");
141 |
142 | managementFrame.button("addFacultyButton").click();
143 | managementFrame.optionPane().requireMessage("Type the name of the faculty");
144 | managementFrame.optionPane().textBox().enterText("NewFaculty");
145 | managementFrame.optionPane().buttonWithText("OK").click();
146 | managementFrame.optionPane().requireMessage("The faculty has been added successfully!");
147 | }
148 |
149 | @Test
150 | public void addStudentSuccessfully() {
151 | if (DBHandler.getFaculties().length == 0)
152 | managementFrame.optionPane().requireErrorMessage()
153 | .requireMessage("You can't add a student yet!\nAdd a faculty and a course first!");
154 | else {
155 | managementFrame.textBox("nameField").enterText("Walter");
156 | managementFrame.textBox("surnameField").enterText("White");
157 | managementFrame.textBox("ageField").enterText("52");
158 | managementFrame.textBox("startedDateField").deleteText();
159 | managementFrame.textBox("startedDateField").enterText("2021-04-10");
160 | managementFrame.button("addButton").click();
161 | managementFrame.optionPane().requireMessage("The student has been added successfully!");
162 | }
163 | }
164 |
165 | @Test
166 | public void addStudentWithWrongAge() {
167 | if (DBHandler.getFaculties().length == 0)
168 | managementFrame.optionPane().requireErrorMessage()
169 | .requireMessage("You can't add a student yet!\nAdd a faculty and a course first!");
170 | else {
171 | managementFrame.textBox("nameField").enterText("Walter");
172 | managementFrame.textBox("surnameField").enterText("White");
173 | managementFrame.textBox("ageField").enterText("haerga");
174 | managementFrame.textBox("startedDateField").deleteText();
175 | managementFrame.textBox("startedDateField").enterText("2021-04-10");
176 | managementFrame.button("addButton").click();
177 | managementFrame.optionPane().requireErrorMessage()
178 | .requireMessage("Something went wrong!\nCheck the credentials!");
179 | }
180 | }
181 |
182 | @Test
183 | public void addStudentWithWrongStartedDate() {
184 | if (DBHandler.getFaculties().length == 0)
185 | managementFrame.optionPane().requireErrorMessage()
186 | .requireMessage("You can't add a student yet!\nAdd a faculty and a course first!");
187 | else {
188 | managementFrame.textBox("nameField").enterText("Walter");
189 | managementFrame.textBox("surnameField").enterText("White");
190 | managementFrame.textBox("ageField").enterText("52");
191 | managementFrame.textBox("startedDateField").deleteText();
192 | managementFrame.textBox("startedDateField").enterText("hraeha");
193 | managementFrame.button("addButton").click();
194 | managementFrame.optionPane().requireErrorMessage()
195 | .requireMessage("Please type a correct data according to the format YYYY-MM-DD!");
196 | }
197 | }
198 |
199 | }
200 |
--------------------------------------------------------------------------------
/Languages.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | Student Management System
11 | Система управления студентами
12 | Sistem de management al elevilor
13 |
14 |
15 | Connect to a database:
16 | Подключитесь к базе данных:
17 | Conectați-vă la o bază de date:
18 |
19 |
20 | Login
21 | Логин:
22 | Login:
23 |
24 |
25 | Password:
26 | Пароль:
27 | Password:
28 |
29 |
30 | Database URL:
31 | URL-адрес базы данных:
32 | Adresa URL a bazei de date:
33 |
34 |
35 | Connect
36 | Подключиться
37 | Conectați
38 |
39 |
40 | Error
41 | Ошибка
42 | Eroare
43 |
44 |
45 | Success
46 | Успех
47 | Succes
48 |
49 |
50 | Please, fill in all the empty fields!
51 | Пожалуйста, заполните все пустые поля!
52 | Vă rugăm să completați toate câmpurile goale!
53 |
54 |
55 | Connection with the database has been successfully established!
56 | Соединение с базой данных успешно установлено!
57 | Conexiunea cu baza de date a fost stabilita cu succes!
58 |
59 |
60 | Connection with the database hasn't been established
61 | Соединение с базой данных не было установлено! Проверьте введенные данные!
62 | Conexiunea cu baza de date nu a fost stabilita! Vă rugăm să vă verificați datele!
63 |
64 |
65 | Change language
66 | Изменить язык
67 | Schimbă limba
68 |
69 |
70 | Select a language
71 | Выберите язык
72 | Alege o limbă
73 |
74 |
75 | ID
76 | ID
77 | ID
78 |
79 |
80 | Name
81 | Имя
82 | Nume
83 |
84 |
85 | Surname
86 | Фамилия
87 | Prenume
88 |
89 |
90 | Age
91 | Возраст
92 | Vârsta
93 |
94 |
95 | Gender
96 | Пол
97 | Sex
98 |
99 |
100 | Course
101 | Курс
102 | Curs
103 |
104 |
105 | Started
106 | Начал
107 | A inceput
108 |
109 |
110 | Graduation
111 | Выпускной
112 | Graduarea
113 |
114 |
115 | Add
116 | Добавить
117 | Adăugați
118 |
119 |
120 | Update
121 | Обновить
122 | Actualizare
123 |
124 |
125 | Delete
126 | Удалить
127 | Șterge
128 |
129 |
130 | Disconnect
131 | Отключиться
132 | Deconectați
133 |
134 |
135 | Exit
136 | Выход
137 | Ieșire
138 |
139 |
140 | YYYY-MM-DD
141 | ГГГГ-ММ-ДД
142 | AAAA-LL-DD
143 |
144 |
145 | Add faculty
146 | Добавить факультет
147 | Adăugați o facultate
148 |
149 |
150 | Add course
151 | Добавить курс
152 | Adăugați un curs
153 |
154 |
155 | Delete faculty
156 | Удалить факультет
157 | Șterge o facultate
158 |
159 |
160 | Delete course
161 | Удалить курс
162 | Șterge un curs
163 |
164 |
165 | An error has occured! Check your input one more time!
166 | Произошла ошибка! Проверьте введёную информацию еще раз!
167 | A apărut o eroare! Verificați încă o dată informația întrodusă!
168 |
169 |
170 | No student has been selected!
171 | Ни один студент не выбран!
172 | Niciun student nu a fost selectat!
173 |
174 |
175 | Deleting a student from the table may result in losing important information. Are you sure?
176 | Удаление сутдент из таблицы может привести к потере важной информации. Вы уверены?
177 | Ștergerea unui student din tabel poate duce la pierderea informației importante.\Sunteți sigur?
178 |
179 |
180 | Student successfully deleted!
181 | Студент успешно удален!
182 | Studentul a fost șters cu succes!
183 |
184 |
185 | Something went wrong! Check your credentials!
186 | Что-то пошло не так! Проверьте введёные данные!
187 | Ceva a mers prost! Verificați informația introdusă!
188 |
189 |
190 | Something went wrong! Try restarting the application!
191 | Что-то пошло не так! Попробуйте перезапустить приложение!
192 | Ceva a mers prost! Încercați să reporniți aplicația!
193 |
194 |
195 | Something went wrong! Try Again!
196 | Что-то пошло не так! Попробуйте еще раз!
197 | Ceva a mers prost! Încercați să repornițiaplicația!
198 |
199 |
200 | You can't add a student yet! Add a faculty and a course first!
201 | Вы еще не можете добавить студента! Добавьте факультет и хотя-бы один курс первее!
202 | Nu puteți adăuga încă un student! Adăugați o facultate și un curs mai intai!
203 |
204 |
205 | Please type a correct data according to the format YYYY-MM-DD!
206 | Пожалуйста, введите правильные данные в соответствии с форматом ГГГГ-ММ-ДД!
207 | Vă rugăm să introduceți datele corecte conform formatului AAAA-LL-ZZ!
208 |
209 |
210 | YYYY-MM-DD
211 | ГГГГ-ММ-ДД
212 | AAAA-LL-ZZ
213 |
214 |
215 | The student has been added successfully!
216 | Студент успешно добавлен!
217 | Studentul a fost adăugat cu succes!
218 |
219 |
220 | Are you sure?
221 | Вы уверены?
222 | Sunteți sigur?
223 |
224 |
225 | Type the name of the faculty:
226 | Введите название факультета:
227 | Tastați numele facultății:
228 |
229 |
230 | The faculty hasn't been added! Please type a name for it!
231 | Факультет не добавлен! Пожалуйста, введите имя для него
232 | Facultatea nu a fost adăugată! Vă rugăm să introduceți un nume pentru aceasta!
233 |
234 |
235 | The faculty hasn't been added! The faculty already exists!
236 | Факультет не добавлен! Факультет уже существует!
237 | Facultatea nu a fost adăugată! Facultatea deja exista!
238 |
239 |
240 | The faculty has been successfully added!
241 | Факультет успешно добавлен!
242 | Facultatea a fost adăugată cu succes!
243 |
244 |
245 | The faculty hasn't been added! Try again!
246 | Факультет не добавлен! Повторите попытку!
247 | Facultatea nu a fost adăugată! Încercați din nou!
248 |
249 |
250 | You can't add a course! Add a faculty first
251 | Вы не можете добавить курс! Сначала добавьте факультет
252 | Nu puteți adăuga un curs! Adăugați mai întâi o facultate
253 |
254 |
255 | Type the name of the course:
256 | Введите название курса
257 | Tastați numele cursului:
258 |
259 |
260 | The course hasn't been added! Please type a name for it!
261 | Курс не добавлен! Пожалуйста, введите название для него!
262 | Cursul nu a fost adăugat! Vă rugăm să introduceți un nume pentru acesta!
263 |
264 |
265 | Choose the faculty for the course
266 | Выберите факультет для курса
267 | Alegeți facultatea pentru curs
268 |
269 |
270 | The course hasn't been added! Please select a faculty for it or add a new one!
271 | Курс не добавлен! Пожалуйста, выберите факультет для него или добавьте новый!
272 | Cursul nu a fost adăugat! Vă rugăm să selectați o facultate pentru el sau adaugă una nouă!
273 |
274 |
275 | Type the duration of the course(months)
276 | Введите продолжительность курса (в месяцах)
277 | Introduceți durata cursului (în luni)
278 |
279 |
280 | The course hasn't been added! Please type the duration of the course without using other characters than digits!
281 | Курс не добавлен! Пожалуйста, введите продолжительность курса без использования других символов, кроме цифр!
282 | Cursul nu a fost adăugat! Vă rugăm să tastați durata cursului fără a folosi alte caractere decât cifre!
283 |
284 |
285 | The course hasn't been added! The course already exists!
286 | Курс не добавлен! Курс уже существуют!
287 | Cursul nu a fost adăugat! Cursul deja exista!
288 |
289 |
290 | The course has been successfully added!
291 | Курс успешно добавлен!
292 | Cursul a fost adăugat cu succes!
293 |
294 |
295 | The course hasn't been added! Try again!
296 | Курс не добавлен! Попробуйте еще раз!
297 | Cursul nu a fost adăugat! Încercați din nou!
298 |
299 |
300 | Choose the faculty to delete
301 | Выберите факультет для удаления
302 | Alegeți facultatea spre ștergere
303 |
304 |
305 | Choose the course to delete
306 | Выберите курс для удаления
307 | Alegeți cursul spre ștergere
308 |
309 |
310 | The faculty has been deleted successfully!
311 | Факультет успешно удален!
312 | Facultatea a fost ștearsă cu succes!
313 |
314 |
315 | The course has been deleted successfully!
316 | Курс успешно удален!
317 | Cursul a fost șters cu succes!
318 |
319 |
320 | You can't delete a faculty that has courses! Do you wish to delete all the courses and students attending these courses in that faculty?
321 | Вы не можете удалить факультет, который имеет курсы! Вы хотите удалить все курсы и студентов посещающих этот курс?
322 | Nu puteți șterge o facultate care are cursuri! Doriți să ștergeți toate cursurile și studenții care umblă la aceste cursuri in aceasta facultate?
323 |
324 |
325 | The courses and the students in the faculty have been deleted successfully!
326 | Курсы и студенты на факультете успешно удалены!
327 | Cursurile din facultate au fost șterse cu succes!
328 |
329 |
330 | You can't delete a course that is attended by students! Do you wish to delete all the students attending that course?
331 | Вы не можете удалить курс посещаемый студентами! Вы хотите удалить всех студентов, посещающих этот курс?
332 | Nu puteți șterge un curs care are studenți! Doriți să ștergeți toți studenții care participă la acest curs?
333 |
334 |
335 | The students attending the course have been deleted successfully!
336 | Студенты, посещающие курс успешно удалены!
337 | Studenții care participă la curs au fost ștersi cu succes!
338 |
339 |
340 |
--------------------------------------------------------------------------------
/src/main/java/sms/ManagementView.java:
--------------------------------------------------------------------------------
1 | package sms;
2 |
3 | import java.awt.Color;
4 | import java.awt.EventQueue;
5 | import java.awt.Font;
6 | import java.awt.GridLayout;
7 | import java.awt.SystemColor;
8 | import java.awt.event.ActionEvent;
9 | import java.awt.event.ActionListener;
10 | import java.text.ParseException;
11 | import java.text.SimpleDateFormat;
12 |
13 | import javax.swing.DefaultComboBoxModel;
14 | import javax.swing.JButton;
15 | import javax.swing.JComboBox;
16 | import javax.swing.JFrame;
17 | import javax.swing.JLabel;
18 | import javax.swing.JOptionPane;
19 | import javax.swing.JPanel;
20 | import javax.swing.JScrollPane;
21 | import javax.swing.JTable;
22 | import javax.swing.JTextField;
23 | import javax.swing.UIManager;
24 | import javax.swing.border.LineBorder;
25 | import javax.swing.event.TableModelEvent;
26 | import javax.swing.event.TableModelListener;
27 | import javax.swing.table.DefaultTableModel;
28 | import javax.swing.table.TableRowSorter;
29 |
30 | /**
31 | * The class that holds the front-end table-management part of the application
32 | * and manages the actions performed out there
33 | *
34 | * @author Artiom
35 | *
36 | */
37 | public class ManagementView {
38 |
39 | /**
40 | * The contents of the management window where you read and write students data
41 | */
42 | static JFrame managementFrame;
43 |
44 | /**
45 | * The table containing all students
46 | */
47 | static JTable table;
48 |
49 | /**
50 | * The field where user should write the student's name
51 | */
52 | static JTextField nameField;
53 |
54 | /**
55 | * The field where user should write the student's surname
56 | */
57 | static JTextField surnameField;
58 |
59 | /**
60 | * The field where user should write the student's age
61 | */
62 | static JTextField ageField;
63 |
64 | /**
65 | * The field where user should write the date when the student started attending
66 | * the course
67 | */
68 | static JTextField startedDateField;
69 |
70 | /**
71 | * The box that user uses in order to select student's gender
72 | */
73 | static JComboBox genderSelectionBox;
74 |
75 | /**
76 | * The box that allows user to select a course for a student
77 | */
78 | static JComboBox courseSelectionBox;
79 |
80 | /**
81 | * Launch the application.
82 | */
83 | public static void main(String[] args) {
84 | EventQueue.invokeLater(new Runnable() {
85 | public void run() {
86 | // Reading messages in dependance of the selected language(by default ENG)
87 | Translator.getMessagesFromXML();
88 |
89 | try {
90 | ManagementView window = new ManagementView();
91 | window.managementFrame.setVisible(true);
92 | } catch (Exception e) {
93 | e.printStackTrace();
94 | }
95 | }
96 | });
97 | }
98 |
99 | /**
100 | * Create the application.
101 | */
102 | public ManagementView() {
103 | initialize();
104 | // Clear the selection in the table, to avoid issues with updateDatabase method
105 | // when cells are selected
106 | table.clearSelection();
107 | // Make it visible in constructor, in order to make tests in
108 | // ManagementViewTest.java work
109 | managementFrame.setVisible(true);
110 | DBHandler.updateStudents();
111 | }
112 |
113 | /**
114 | * Updates the list of courses
115 | */
116 | private void updateCourses() {
117 | // Get the lists of courses
118 | DefaultComboBoxModel courses = new DefaultComboBoxModel(DBHandler.getCourses());
119 | courseSelectionBox.setModel(courses);
120 | }
121 |
122 | /**
123 | * Initialize the contents of the frame.
124 | */
125 | private void initialize() {
126 | managementFrame = new JFrame();
127 | managementFrame.setBounds(100, 100, 860, 540);
128 | managementFrame.setResizable(false);
129 | managementFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
130 | managementFrame.setTitle(Translator.getValue("sms"));
131 | managementFrame.getContentPane().setLayout(null);
132 |
133 | // The panel where students table is located
134 | JPanel tablePanel = new JPanel();
135 | tablePanel.setBorder(new LineBorder(SystemColor.textHighlight, 5));
136 | tablePanel.setBounds(260, 10, 575, 395);
137 | managementFrame.getContentPane().add(tablePanel);
138 | tablePanel.setLayout(null);
139 |
140 | // The scroll pane that allows navigation through table
141 | JScrollPane tableScrollPane = new JScrollPane();
142 | tableScrollPane.setBounds(10, 10, 555, 375);
143 | tablePanel.add(tableScrollPane);
144 |
145 | // Initializing the table and setting its model
146 | table = new JTable();
147 | tableScrollPane.setViewportView(table);
148 | table.setColumnSelectionAllowed(true);
149 | table.setModel(new DefaultTableModel(new Object[][] {},
150 | new String[] { Translator.getValue("ID"), Translator.getValue("name"), Translator.getValue("surname"),
151 | Translator.getValue("age"), Translator.getValue("gender"), Translator.getValue("course"),
152 | Translator.getValue("started"), Translator.getValue("graduation") }) {
153 | boolean[] columnEditables = new boolean[] { false, true, true, true, true, false, false, false };
154 |
155 | public boolean isCellEditable(int row, int column) {
156 | return columnEditables[column];
157 | }
158 | });
159 |
160 | // Creating a sorter for the table
161 | TableRowSorter tableSorter = new TableRowSorter(table.getModel());
162 | table.setRowSorter(tableSorter);
163 |
164 | // Creating a Table Listener to detect cell modifications
165 | table.getModel().addTableModelListener(new TableModelListener() {
166 |
167 | // Actions to perform when a cell has been edited
168 | public void tableChanged(TableModelEvent e) {
169 | if (!DBHandler.updateDatabase()) {
170 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("checkInput"),
171 | Translator.getValue("sms"), JOptionPane.ERROR_MESSAGE);
172 | }
173 | }
174 | });
175 |
176 | // The panel where all buttons are located
177 | JPanel buttonsPanel = new JPanel();
178 | buttonsPanel.setBorder(new LineBorder(new Color(0, 120, 215), 5));
179 | buttonsPanel.setBackground(UIManager.getColor("Button.background"));
180 | buttonsPanel.setBounds(10, 415, 825, 80);
181 | managementFrame.getContentPane().add(buttonsPanel);
182 |
183 | // The button to press to delete an information from the table
184 | JButton deleteButton = new JButton(Translator.getValue("delete"));
185 | deleteButton.setName("deleteButton");
186 |
187 | // Actions to perform when "delete" button clicked
188 | deleteButton.addActionListener(new ActionListener() {
189 | public void actionPerformed(ActionEvent e) {
190 | // If no row has been selected
191 | if (table.getSelectedRow() == -1) {
192 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("noStudentSelected"),
193 | Translator.getValue("sms"), JOptionPane.ERROR_MESSAGE);
194 | } else {
195 | // Asking the user if they are sure about that
196 | if (JOptionPane.showConfirmDialog(managementFrame, Translator.getValue("warningDelete"),
197 | Translator.getValue("sms"), JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
198 | if (DBHandler.deleteStudent()) {
199 | JOptionPane.showMessageDialog(managementFrame,
200 | Translator.getValue("studentSuccessfullyDeleted"), Translator.getValue("sms"),
201 | JOptionPane.INFORMATION_MESSAGE);
202 | } else {
203 | JOptionPane.showMessageDialog(managementFrame,
204 | Translator.getValue("somethingWrongUnexpected"), Translator.getValue("sms"),
205 | JOptionPane.ERROR_MESSAGE);
206 | }
207 | }
208 | }
209 | }
210 | });
211 |
212 | deleteButton.setFont(new Font("Tahoma", Font.PLAIN, 16));
213 |
214 | // The button to press to add a student to the table
215 | JButton addButton = new JButton(Translator.getValue("add"));
216 | addButton.setName("addButton");
217 |
218 | // Actions to perform when "add" button clicked
219 | addButton.addActionListener(new ActionListener() {
220 | public void actionPerformed(ActionEvent e) {
221 | table.clearSelection();
222 |
223 | if (DBHandler.getFaculties().length == 0) {
224 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("cannotAddStudent"),
225 | Translator.getValue("error"), JOptionPane.ERROR_MESSAGE);
226 | return;
227 | }
228 |
229 | // If one of the fields are empty warn user about that
230 | if (nameField.getText().equals("") || surnameField.getText().equals("") || ageField.getText().equals("")
231 | || startedDateField.getText().equals("")) {
232 |
233 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("fillEmptyFields"),
234 | Translator.getValue("error"), JOptionPane.ERROR_MESSAGE);
235 | } else {
236 | try {
237 | // Check if the written data is written correctly according to the format
238 | SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
239 | format.setLenient(false);
240 | format.parse(startedDateField.getText());
241 | } catch (ParseException ex) {
242 | ex.printStackTrace();
243 |
244 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("dateFormatError"),
245 | Translator.getValue("error"), JOptionPane.ERROR_MESSAGE);
246 |
247 | return;
248 | }
249 |
250 | if (DBHandler.addStudent()) {
251 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("studentSuccessfullyAdded"),
252 | Translator.getValue("success"), JOptionPane.INFORMATION_MESSAGE);
253 | } else {
254 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("somethingWrongInput"),
255 | Translator.getValue("error"), JOptionPane.ERROR_MESSAGE);
256 | }
257 |
258 | }
259 | }
260 | });
261 | buttonsPanel.setLayout(new GridLayout(0, 5, 0, 0));
262 |
263 | addButton.setFont(new Font("Tahoma", Font.PLAIN, 16));
264 | buttonsPanel.add(addButton);
265 |
266 | // The button to press to update an information in the table
267 | JButton updateButton = new JButton(Translator.getValue("update"));
268 |
269 | // Actions to perform when "update" button clicked
270 | updateButton.addActionListener(new ActionListener() {
271 | public void actionPerformed(ActionEvent e) {
272 | table.clearSelection();
273 | DBHandler.updateStudents();
274 | }
275 | });
276 |
277 | updateButton.setFont(new Font("Tahoma", Font.PLAIN, 16));
278 | buttonsPanel.add(updateButton);
279 | buttonsPanel.add(deleteButton);
280 |
281 | // The button to press to exit the application
282 | JButton exitButton = new JButton(Translator.getValue("exit"));
283 | exitButton.setName("exitButton");
284 |
285 | // Actions to perform when "exit" button clicked
286 | exitButton.addActionListener(new ActionListener() {
287 | public void actionPerformed(ActionEvent e) {
288 | if (JOptionPane.showConfirmDialog(managementFrame, Translator.getValue("confirmDialog"),
289 | Translator.getValue("sms"), JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
290 | managementFrame.dispose();
291 | System.exit(0);
292 | }
293 | }
294 | });
295 |
296 | // The button that user have to press in order to disconnect from the current
297 | // database
298 | JButton disconnectButton = new JButton(Translator.getValue("disconnect"));
299 | disconnectButton.setName("disconnectButton");
300 |
301 | // Actions to perform when "disconnect" button has been clicked
302 | disconnectButton.addActionListener(new ActionListener() {
303 |
304 | public void actionPerformed(ActionEvent e) {
305 | if (JOptionPane.showConfirmDialog(managementFrame, Translator.getValue("confirmDialog"),
306 | Translator.getValue("sms"), JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
307 | // Return back to the connection window
308 | ConnectionView.main(null);
309 | managementFrame.dispose();
310 | }
311 | }
312 | });
313 |
314 | disconnectButton.setFont(new Font("Tahoma", Font.PLAIN, 16));
315 | buttonsPanel.add(disconnectButton);
316 |
317 | exitButton.setFont(new Font("Tahoma", Font.PLAIN, 16));
318 | buttonsPanel.add(exitButton);
319 |
320 | // The panel where user writes information about a student
321 | JPanel studentPanel = new JPanel();
322 | studentPanel.setBorder(new LineBorder(SystemColor.textHighlight, 5));
323 | studentPanel.setBounds(10, 10, 240, 395);
324 | managementFrame.getContentPane().add(studentPanel);
325 | studentPanel.setLayout(null);
326 |
327 | // The text that informs the user where they have to write the student's name
328 | JLabel nameText = new JLabel(Translator.getValue("name"));
329 | nameText.setFont(new Font("Tahoma", Font.PLAIN, 16));
330 | nameText.setBounds(10, 22, 67, 19);
331 | studentPanel.add(nameText);
332 |
333 | // Initializing name text field
334 | nameField = new JTextField();
335 | nameField.setName("nameField");
336 | nameField.setBounds(85, 23, 143, 22);
337 | studentPanel.add(nameField);
338 | nameField.setColumns(10);
339 |
340 | // The text that informs the user where they have to write the student's surname
341 | JLabel surnameText = new JLabel(Translator.getValue("surname"));
342 | surnameText.setFont(new Font("Tahoma", Font.PLAIN, 16));
343 | surnameText.setBounds(10, 54, 67, 19);
344 | studentPanel.add(surnameText);
345 |
346 | // Initializing surname text field
347 | surnameField = new JTextField();
348 | surnameField.setName("surnameField");
349 | surnameField.setColumns(10);
350 | surnameField.setBounds(85, 51, 143, 22);
351 | studentPanel.add(surnameField);
352 |
353 | // The text that informs the user where they have to write the student's age
354 | JLabel ageText = new JLabel(Translator.getValue("age"));
355 | ageText.setFont(new Font("Tahoma", Font.PLAIN, 16));
356 | ageText.setBounds(10, 86, 67, 19);
357 | studentPanel.add(ageText);
358 |
359 | // Initializing age text field
360 | ageField = new JTextField();
361 | ageField.setName("ageField");
362 | ageField.setColumns(10);
363 | ageField.setBounds(85, 83, 143, 22);
364 | studentPanel.add(ageField);
365 |
366 | // The text that informs the user where they have to write the student's
367 | // attended course
368 | JLabel courseText = new JLabel(Translator.getValue("course"));
369 | courseText.setFont(new Font("Tahoma", Font.PLAIN, 16));
370 | courseText.setBounds(10, 156, 67, 19);
371 | studentPanel.add(courseText);
372 |
373 | // The text that informs the user where they have to write the date when student
374 | // started attending the course
375 | JLabel startedDateText = new JLabel(Translator.getValue("started"));
376 | startedDateText.setFont(new Font("Tahoma", Font.PLAIN, 16));
377 | startedDateText.setBounds(10, 188, 67, 19);
378 | studentPanel.add(startedDateText);
379 |
380 | // Initializing startedDate text field
381 | startedDateField = new JTextField();
382 | startedDateField.setName("startedDateField");
383 | startedDateField.setColumns(10);
384 | startedDateField.setBounds(85, 185, 143, 22);
385 | startedDateField.setText(Translator.getValue("dateFormat"));
386 | studentPanel.add(startedDateField);
387 |
388 | // The text that informs the user where they have to select student's gender
389 | JLabel genderText = new JLabel(Translator.getValue("gender"));
390 | genderText.setFont(new Font("Tahoma", Font.PLAIN, 16));
391 | genderText.setBounds(10, 120, 67, 19);
392 | studentPanel.add(genderText);
393 |
394 | // Initializing the box where user selects the student's gender
395 | genderSelectionBox = new JComboBox();
396 | genderSelectionBox.setName("genderSelectionBox");
397 | genderSelectionBox.setFont(new Font("Tahoma", Font.PLAIN, 16));
398 | genderSelectionBox.setModel(new DefaultComboBoxModel(sms.Gender.values()));
399 | genderSelectionBox.setBounds(85, 120, 143, 22);
400 | studentPanel.add(genderSelectionBox);
401 |
402 | // Button that adds a new faculty
403 | JButton addFacultyButton = new JButton(Translator.getValue("addFaculty"));
404 | addFacultyButton.setName("addFacultyButton");
405 |
406 | // Actions to perform when "add faculty" button clicked
407 | addFacultyButton.addActionListener(new ActionListener() {
408 | public void actionPerformed(ActionEvent e) {
409 | String facultyName = "";
410 |
411 | facultyName = JOptionPane.showInputDialog(managementFrame, Translator.getValue("typeNameFaculty"));
412 |
413 | if (facultyName == null || facultyName.equals("")) {
414 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("emptyNameFaculty"),
415 | Translator.getValue("error"), JOptionPane.ERROR_MESSAGE);
416 | } else {
417 | if (DBHandler.checkIfElementExists(DBHandler.getFacultiesTable(), facultyName)) {
418 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("facultyAlreadyExists"),
419 | Translator.getValue("error"), JOptionPane.ERROR_MESSAGE);
420 | } else {
421 | if (DBHandler.addFaculty(facultyName)) {
422 | JOptionPane.showMessageDialog(managementFrame,
423 | Translator.getValue("facultySuccessfullyAdded"), Translator.getValue("success"),
424 | JOptionPane.INFORMATION_MESSAGE);
425 | } else {
426 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("facultyNotAdded"),
427 | Translator.getValue("success"), JOptionPane.ERROR_MESSAGE);
428 | }
429 | }
430 | }
431 | }
432 | });
433 |
434 | addFacultyButton.setFont(new Font("Tahoma", Font.PLAIN, 16));
435 | addFacultyButton.setBounds(10, 220, 220, 30);
436 | studentPanel.add(addFacultyButton);
437 |
438 | // Button that adds a new course
439 | JButton addCourseButton = new JButton(Translator.getValue("addCourse"));
440 | addCourseButton.setName("addCourseButton");
441 | addCourseButton.addActionListener(new ActionListener() {
442 |
443 | // Actions to perform when "add course" button clicked
444 | public void actionPerformed(ActionEvent e) {
445 | // If there are no faculties there is no way to add a course
446 | if (DBHandler.getFaculties().length == 0) {
447 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("cannotAddCourse"),
448 | Translator.getValue("error"), JOptionPane.ERROR_MESSAGE);
449 | return;
450 | }
451 |
452 | String courseName = "", faculty = "";
453 | int duration = 0;
454 |
455 | courseName = JOptionPane.showInputDialog(managementFrame, Translator.getValue("typeNameCourse"));
456 |
457 | // If no name has been written for the course
458 | if (courseName == null || courseName.equals("")) {
459 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("emptyNameCourse"),
460 | Translator.getValue("error"), JOptionPane.ERROR_MESSAGE);
461 | return;
462 | } else {
463 | String[] faculties = DBHandler.getFaculties();
464 | faculty = (String) JOptionPane.showInputDialog(null, Translator.getValue("chooseFaculty"),
465 | Translator.getValue("sms"), JOptionPane.QUESTION_MESSAGE, null, faculties, faculties[0]);
466 |
467 | // If no faculty has been selected for the course
468 | if (faculty == null || faculty.equals("")) {
469 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("courseNotAddedNoFaculty"),
470 | Translator.getValue("error"), JOptionPane.ERROR_MESSAGE);
471 | return;
472 | } else {
473 | // In case the user types letters for the duration
474 | try {
475 | duration = Integer.parseInt(JOptionPane.showInputDialog(managementFrame,
476 | Translator.getValue("courseTypeDuration")));
477 | } catch (NumberFormatException ex) {
478 | ex.printStackTrace();
479 |
480 | JOptionPane.showMessageDialog(managementFrame,
481 | Translator.getValue("courseNotAddedNoDuration"), Translator.getValue("error"),
482 | JOptionPane.ERROR_MESSAGE);
483 |
484 | return;
485 | }
486 |
487 | if (DBHandler.checkIfElementExists(DBHandler.getCoursesTable(), courseName)) {
488 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("courseAlreadyExists"),
489 | Translator.getValue("error"), JOptionPane.ERROR_MESSAGE);
490 | } else {
491 | if (DBHandler.addCourse(courseName, faculty, duration)) {
492 | JOptionPane.showMessageDialog(managementFrame,
493 | Translator.getValue("courseSuccessfullyAdded"), Translator.getValue("success"),
494 | JOptionPane.INFORMATION_MESSAGE);
495 |
496 | updateCourses();
497 | } else {
498 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("courseNotAdded"),
499 | Translator.getValue("error"), JOptionPane.ERROR_MESSAGE);
500 | }
501 | }
502 | }
503 | }
504 | }
505 | });
506 |
507 | addCourseButton.setFont(new Font("Tahoma", Font.PLAIN, 16));
508 | addCourseButton.setBounds(10, 260, 220, 30);
509 | studentPanel.add(addCourseButton);
510 |
511 | // Initializing the course selection box
512 | courseSelectionBox = new JComboBox();
513 | courseSelectionBox.setFont(new Font("Tahoma", Font.PLAIN, 16));
514 | courseSelectionBox.setBounds(85, 154, 143, 22);
515 | updateCourses();
516 | studentPanel.add(courseSelectionBox);
517 |
518 | // Button that allows to delete a faculty
519 | JButton deleteFacultyButton = new JButton(Translator.getValue("deleteFaculty"));
520 | deleteFacultyButton.setName("deleteFacultyButton");
521 |
522 | // Actions to perform when "Delete Faculty" button clicked
523 | deleteFacultyButton.addActionListener(new ActionListener() {
524 | public void actionPerformed(ActionEvent e) {
525 | table.clearSelection();
526 |
527 | String faculty = (String) JOptionPane.showInputDialog(null, Translator.getValue("sms"),
528 | Translator.getValue("chooseFacultyDelete"), JOptionPane.QUESTION_MESSAGE, null,
529 | DBHandler.getFaculties(), DBHandler.getFaculties()[0]);
530 |
531 | // If no faculty has been selected
532 | if (faculty == null) {
533 | return;
534 | }
535 |
536 | // If there are students attending the courses in this faculty
537 | if (DBHandler.getNumberOfCourses(faculty) > 0) {
538 | if (JOptionPane.showConfirmDialog(managementFrame, Translator.getValue("deleteFacultyWithCourses"),
539 | Translator.getValue("sms"), JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
540 | if (DBHandler.deleteFacultyCourses(faculty)) {
541 | JOptionPane.showMessageDialog(managementFrame,
542 | Translator.getValue("coursesFromFacultySuccessfullyDeleted"),
543 | Translator.getValue("success"), JOptionPane.INFORMATION_MESSAGE);
544 |
545 | if (DBHandler.deleteFaculty(faculty)) {
546 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("facultyDeleted"),
547 | Translator.getValue("success"), JOptionPane.INFORMATION_MESSAGE);
548 | } else {
549 | JOptionPane.showMessageDialog(managementFrame,
550 | Translator.getValue("somethingWrongTryAgain"), Translator.getValue("error"),
551 | JOptionPane.ERROR_MESSAGE);
552 | }
553 |
554 | } else {
555 | JOptionPane.showMessageDialog(managementFrame,
556 | Translator.getValue("somethingWrongTryAgain"), Translator.getValue("error"),
557 | JOptionPane.ERROR_MESSAGE);
558 | }
559 | }
560 | } else {
561 | if (DBHandler.deleteFaculty(faculty)) {
562 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("facultyDeleted"),
563 | Translator.getValue("success"), JOptionPane.INFORMATION_MESSAGE);
564 | } else {
565 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("somethingWrongTryAgain"),
566 | Translator.getValue("error"), JOptionPane.ERROR_MESSAGE);
567 | }
568 | }
569 | updateCourses();
570 | }
571 | });
572 |
573 | deleteFacultyButton.setFont(new Font("Tahoma", Font.PLAIN, 16));
574 | deleteFacultyButton.setBounds(10, 300, 220, 30);
575 | studentPanel.add(deleteFacultyButton);
576 |
577 | // Button that allows to delete a course
578 | JButton deleteCourseButton = new JButton(Translator.getValue("deleteCourse"));
579 | deleteCourseButton.setName("deleteCourseButton");
580 |
581 | // Actions to perform when "Delete Course" button clicked
582 | deleteCourseButton.addActionListener(new ActionListener() {
583 |
584 | public void actionPerformed(ActionEvent e) {
585 | table.clearSelection();
586 |
587 | String course = (String) JOptionPane.showInputDialog(null, Translator.getValue("sms"),
588 | Translator.getValue("chooseCourseDelete"), JOptionPane.QUESTION_MESSAGE, null,
589 | DBHandler.getCourses(), DBHandler.getCourses()[0]);
590 |
591 | // If no course has been selected
592 | if (course == null) {
593 | return;
594 | }
595 |
596 | // If there are students attending the course
597 | if (DBHandler.getNumberOfAttendees(DBHandler.getCoursesTable(), course) > 0) {
598 | if (JOptionPane.showConfirmDialog(managementFrame, Translator.getValue("deleteCourseWithStudents"),
599 | Translator.getValue("deleteCourse"), JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
600 | if (DBHandler.deleteCourseAttendees(course)) {
601 | JOptionPane.showMessageDialog(managementFrame,
602 | Translator.getValue("studentsAttendingSuccessfullyDeleted"),
603 | Translator.getValue("success"), JOptionPane.INFORMATION_MESSAGE);
604 |
605 | if (DBHandler.deleteCourse(course)) {
606 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("courseDeleted"),
607 | Translator.getValue("success"), JOptionPane.INFORMATION_MESSAGE);
608 | } else {
609 | JOptionPane.showMessageDialog(managementFrame,
610 | Translator.getValue("somethingWrongTryAgain"), "Error",
611 | JOptionPane.ERROR_MESSAGE);
612 | }
613 | } else {
614 | JOptionPane.showMessageDialog(managementFrame,
615 | Translator.getValue("somethingWrongTryAgain"), Translator.getValue("error"),
616 | JOptionPane.ERROR_MESSAGE);
617 | }
618 | }
619 | } else {
620 | if (DBHandler.deleteCourse(course)) {
621 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("courseDeleted"),
622 | Translator.getValue("success"), JOptionPane.INFORMATION_MESSAGE);
623 | } else {
624 | JOptionPane.showMessageDialog(managementFrame, Translator.getValue("somethingWrongTryAgain"),
625 | Translator.getValue("error"), JOptionPane.ERROR_MESSAGE);
626 | }
627 | }
628 | updateCourses();
629 | }
630 | });
631 |
632 | deleteCourseButton.setFont(new Font("Tahoma", Font.PLAIN, 16));
633 | deleteCourseButton.setBounds(10, 340, 220, 30);
634 | studentPanel.add(deleteCourseButton);
635 | }
636 | }
637 |
--------------------------------------------------------------------------------
/src/main/java/sms/DBHandler.java:
--------------------------------------------------------------------------------
1 | package sms;
2 |
3 | import java.sql.Connection;
4 | import java.sql.DatabaseMetaData;
5 | import java.sql.DriverManager;
6 | import java.sql.PreparedStatement;
7 | import java.sql.ResultSet;
8 | import java.sql.ResultSetMetaData;
9 | import java.sql.SQLException;
10 | import java.sql.Statement;
11 | import java.time.LocalDate;
12 | import java.util.HashMap;
13 | import java.util.Vector;
14 |
15 | import javax.swing.table.DefaultTableModel;
16 |
17 | /**
18 | * The class that allows access to a database for reading and writing data
19 | * purposes
20 | *
21 | * @author Artiom
22 | *
23 | */
24 | public class DBHandler {
25 | /**
26 | * Login to connect to the database
27 | */
28 | private static String login;
29 |
30 | /**
31 | * Password to connect to the database
32 | */
33 | private static String password;
34 |
35 | /**
36 | * Database URL
37 | */
38 | static String databaseUrl;
39 |
40 | /**
41 | * The var that stores students table's name
42 | */
43 | private final static String studentsTable;
44 |
45 | /**
46 | * The var that stores courses table's name
47 | */
48 | private final static String coursesTable;
49 |
50 | /**
51 | * The var that stores faculties table's name
52 | */
53 | private final static String facultiesTable;
54 |
55 | /**
56 | * Default constructor
57 | */
58 | public DBHandler() {
59 |
60 | }
61 |
62 | /**
63 | * Static initializers
64 | */
65 | static {
66 | login = "root";
67 | databaseUrl = "jdbc:mysql://localhost:3306/studentsdb";
68 |
69 | studentsTable = "students";
70 | coursesTable = "courses";
71 | facultiesTable = "faculties";
72 | }
73 |
74 | /**
75 | * @return The login to connect to the database
76 | */
77 | public static String getLogin() {
78 | return login;
79 | }
80 |
81 | /**
82 | * @param login - The login to set to connect to the database
83 | */
84 | public static void setLogin(final String login) {
85 | DBHandler.login = login;
86 | }
87 |
88 | /**
89 | * @return The password to connect to the database
90 | */
91 | public static String getPassword() {
92 | return password;
93 | }
94 |
95 | /**
96 | * @param password - The password to set to connect to the database
97 | */
98 | public static void setPassword(final String password) {
99 | DBHandler.password = password;
100 | }
101 |
102 | /**
103 | * @param databaseUrl - the database url to set
104 | */
105 | public static void setDatabaseUrl(final String databaseUrl) {
106 | DBHandler.databaseUrl = databaseUrl;
107 | }
108 |
109 | /**
110 | * @return The database URL
111 | */
112 | public static String getDatabaseUrl() {
113 | return databaseUrl;
114 | }
115 |
116 | /**
117 | * @return The students table's name
118 | */
119 | public static String getStudentsTable() {
120 | return studentsTable;
121 | }
122 |
123 | /**
124 | * @return The faculties table's name
125 | */
126 | public static String getFacultiesTable() {
127 | return facultiesTable;
128 | }
129 |
130 | /**
131 | * @return The courses table's name
132 | */
133 | public static String getCoursesTable() {
134 | return coursesTable;
135 | }
136 |
137 | /**
138 | * Checks if a certain table already exists in the database
139 | *
140 | * @param tableName - Table's name that is wanted to be checked
141 | * @return True if table exists, false otherwise
142 | */
143 | public static boolean checkIfTableExists(final String tableName) {
144 | try {
145 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
146 |
147 | // Check if a table with tableName name already exists
148 | DatabaseMetaData dbmData = connection.getMetaData();
149 | ResultSet resultSet = dbmData.getTables(null, null, tableName, null);
150 | while (resultSet.next()) {
151 | if (resultSet.getString(3).equals(tableName)) {
152 | // Return true if the table has been found
153 | return true;
154 | }
155 | }
156 |
157 | connection.close();
158 | resultSet.close();
159 |
160 | // Return false if no table has been found
161 | return false;
162 | } catch (SQLException e) {
163 | e.printStackTrace();
164 |
165 | // Return false if an exception has been thrown
166 | return false;
167 | }
168 | }
169 |
170 | /**
171 | * Creates a table of students, courses and faculties
172 | *
173 | * @return True if no exception has been thrown, false otherwise
174 | */
175 | public static boolean createTables() {
176 | try {
177 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
178 | Statement statement = connection.createStatement();
179 |
180 | if (!checkIfTableExists(studentsTable)) {
181 | // Creating a table of students
182 | statement.executeUpdate("create table " + studentsTable + "(ID INTEGER not NULL AUTO_INCREMENT, "
183 | + " Name varchar(50), " + "Surname varchar(50), " + "Age INTEGER, " + "Gender varchar(6), "
184 | + "Course varchar(50), " + "Started varchar(25), " + "Graduation varchar(25), "
185 | + "PRIMARY KEY ( id ))");
186 | }
187 |
188 | if (!checkIfTableExists(coursesTable)) {
189 | // Creating a table of courses
190 | statement.executeUpdate("create table " + coursesTable + "(ID INTEGER not NULL AUTO_INCREMENT, "
191 | + " Name varchar(50), " + "Faculty varchar(50), " + "Duration INTEGER, " + "Attendees INTEGER, "
192 | + "PRIMARY KEY ( id ))");
193 | }
194 |
195 | if (!checkIfTableExists(facultiesTable)) {
196 | // Creating a table of faculties
197 | statement.executeUpdate("create table " + facultiesTable + "(ID INTEGER not NULL AUTO_INCREMENT, "
198 | + " Name varchar(50), " + "Courses INTEGER, " + "Attendees INTEGER, " + "PRIMARY KEY ( id ))");
199 | }
200 |
201 | connection.close();
202 | statement.close();
203 |
204 | // Return true if no exception has been thrown
205 | return true;
206 |
207 | } catch (SQLException e) {
208 | e.printStackTrace();
209 |
210 | // Return false if an exception has been thrown
211 | return false;
212 | }
213 | }
214 |
215 | /**
216 | * Adds a new student to the table
217 | *
218 | * @return True if no exception has been thrown, false otherwise
219 | */
220 | public static boolean addStudent() {
221 | try {
222 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
223 | PreparedStatement preparedStatement = connection.prepareStatement("insert into " + studentsTable
224 | + " (Name, Surname, Age, Gender, Course, Started, Graduation) values " + "(?, ?, ?, ?, ?, ?, ?)");
225 |
226 | // Getting the duration of the course in order to calculate Graduation date
227 | // field
228 | PreparedStatement preparedStatement2 = connection
229 | .prepareStatement("select Duration from Courses where Name = " + "\""
230 | + ManagementView.courseSelectionBox.getSelectedItem().toString() + "\"");
231 | ResultSet resultSet = preparedStatement2.executeQuery();
232 | resultSet.next();
233 | final int courseDuration = resultSet.getInt("Duration");
234 |
235 | preparedStatement.setString(1, ManagementView.nameField.getText());
236 | preparedStatement.setString(2, ManagementView.surnameField.getText());
237 | preparedStatement.setInt(3, Integer.parseInt(ManagementView.ageField.getText()));
238 | preparedStatement.setString(4, ManagementView.genderSelectionBox.getSelectedItem().toString());
239 | preparedStatement.setString(5, ManagementView.courseSelectionBox.getSelectedItem().toString());
240 |
241 | final String inputDate = ManagementView.startedDateField.getText();
242 | LocalDate startedDate = LocalDate.of(Integer.parseInt(inputDate.substring(0, 4)),
243 | Integer.parseInt(inputDate.substring(5, 7)), Integer.parseInt(inputDate.substring(8, 10)));
244 | preparedStatement.setString(6, startedDate.toString());
245 |
246 | LocalDate graduationDate = startedDate.plusMonths(courseDuration);
247 | preparedStatement.setString(7, graduationDate.toString());
248 |
249 | preparedStatement.executeUpdate();
250 |
251 | connection.close();
252 | preparedStatement.close();
253 |
254 | updateStudents();
255 |
256 | // Return true if no exception has been thrown
257 | return true;
258 | } catch (SQLException e) {
259 | e.printStackTrace();
260 |
261 | // Return false if an exception has been thrown
262 | return false;
263 | } catch (Exception e) {
264 | e.printStackTrace();
265 |
266 | // Return false if an exception has been thrown
267 | return false;
268 | }
269 | }
270 |
271 | /**
272 | * Updates the contents of the table
273 | *
274 | * @return True if no exception has been thrown, false otherwise
275 | */
276 | public static boolean updateStudents() {
277 | int howManyColumns = 0, currentColumn = 0;
278 |
279 | try {
280 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
281 | PreparedStatement preparedStatement = connection.prepareStatement("select * from " + studentsTable);
282 |
283 | // Reading data from table
284 | ResultSet resultSet = preparedStatement.executeQuery();
285 | ResultSetMetaData rsmData = resultSet.getMetaData();
286 |
287 | howManyColumns = rsmData.getColumnCount();
288 |
289 | DefaultTableModel recordTable = (DefaultTableModel) ManagementView.table.getModel();
290 | recordTable.setRowCount(0);
291 |
292 | while (resultSet.next()) {
293 | Vector columnData = new Vector();
294 |
295 | for (currentColumn = 1; currentColumn <= howManyColumns; currentColumn++) {
296 | columnData.add(resultSet.getString("ID"));
297 | columnData.add(resultSet.getString("Name"));
298 | columnData.add(resultSet.getString("Surname"));
299 | columnData.add(resultSet.getString("Age"));
300 | columnData.add(resultSet.getString("Gender"));
301 | columnData.add(resultSet.getString("Course"));
302 | columnData.add(resultSet.getString("Started"));
303 | columnData.add(resultSet.getString("Graduation"));
304 | }
305 |
306 | recordTable.addRow(columnData);
307 | }
308 |
309 | updateAttendees();
310 |
311 | connection.close();
312 | preparedStatement.close();
313 | resultSet.close();
314 |
315 | // Return true if no exception has been thrown
316 | return true;
317 | } catch (SQLException e) {
318 | e.printStackTrace();
319 |
320 | // Return false if exception has been thrown
321 | return false;
322 | }
323 | }
324 |
325 | /**
326 | * Deletes the selected student from the table
327 | *
328 | * @return True if no exception has been thrown, false otherwise
329 | */
330 | public static boolean deleteStudent() {
331 | // Getting row that user selected
332 | DefaultTableModel recordTable = (DefaultTableModel) ManagementView.table.getModel();
333 | int selectedRow = ManagementView.table.getSelectedRow();
334 | ManagementView.table.clearSelection();
335 |
336 | try {
337 | // Geting the ID of the student in the selected row
338 | final int ID = Integer.parseInt(recordTable.getValueAt(selectedRow, 0).toString());
339 |
340 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
341 | PreparedStatement preparedStatement = connection
342 | .prepareStatement("delete from " + studentsTable + " where id = ?");
343 |
344 | preparedStatement.setInt(1, ID);
345 | preparedStatement.executeUpdate();
346 |
347 | connection.close();
348 | preparedStatement.close();
349 |
350 | updateStudents();
351 |
352 | // Return true if no exception has been thrown
353 | return true;
354 | } catch (SQLException e) {
355 | e.printStackTrace();
356 |
357 | // Return false if exception has been thrown
358 | return false;
359 | }
360 | }
361 |
362 | /**
363 | * Adds a faculty to the faculties table
364 | *
365 | * @return True if no exception has been thrown, false otherwise
366 | */
367 | public static boolean addFaculty(final String facultyName) {
368 | try {
369 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
370 | PreparedStatement preparedStatement = connection.prepareStatement(
371 | "insert into " + facultiesTable + " (Name, Courses, Attendees) values " + "(?, ?, ?)");
372 |
373 | preparedStatement.setString(1, facultyName);
374 | preparedStatement.setInt(2, 0);
375 | preparedStatement.setInt(3, 0);
376 |
377 | preparedStatement.executeUpdate();
378 |
379 | connection.close();
380 | preparedStatement.close();
381 |
382 | // Return true if no exception has been thrown
383 | return true;
384 | } catch (SQLException e) {
385 | e.printStackTrace();
386 |
387 | // Return false if exception has been thrown
388 | return false;
389 | }
390 | }
391 |
392 | /**
393 | * Adds a course to the courses table
394 | *
395 | * @return True if no exception has been thrown, false otherwise
396 | */
397 | public static boolean addCourse(final String courseName, final String faculty, final int duration) {
398 | try {
399 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
400 | PreparedStatement preparedStatement = connection.prepareStatement(
401 | "insert into " + coursesTable + " (Name, Faculty, Duration, Attendees) values " + "(?, ?, ?, ?)");
402 |
403 | preparedStatement.setString(1, courseName);
404 | preparedStatement.setString(2, faculty);
405 | preparedStatement.setInt(3, duration);
406 | preparedStatement.setInt(4, 0);
407 |
408 | preparedStatement.executeUpdate();
409 |
410 | connection.close();
411 | preparedStatement.close();
412 |
413 | updateAttendees();
414 |
415 | // Return true if no exception has been thrown
416 | return true;
417 | } catch (SQLException e) {
418 | e.printStackTrace();
419 |
420 | // Return false if exception has been thrown
421 | return false;
422 | }
423 | }
424 |
425 | /**
426 | * Gets all the faculties from the faculties table
427 | *
428 | * @return An array with all the faculties
429 | */
430 | public static String[] getFaculties() {
431 | Vector faculties = new Vector();
432 |
433 | try {
434 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
435 | PreparedStatement preparedStatement = connection.prepareStatement("select Name from faculties");
436 | ResultSet resultSet = preparedStatement.executeQuery();
437 |
438 | // Add every name of the faculty to the "faculties" vector
439 | while (resultSet.next()) {
440 | faculties.add(resultSet.getString("Name"));
441 | }
442 |
443 | connection.close();
444 | preparedStatement.close();
445 | resultSet.close();
446 |
447 | } catch (SQLException e) {
448 | e.printStackTrace();
449 | }
450 |
451 | // Convert "faculties" vector to String array and return it
452 | return faculties.toArray(new String[0]);
453 | }
454 |
455 | /**
456 | * Gets all the courses from the courses table
457 | *
458 | * @return An array with all the courses
459 | */
460 | public static String[] getCourses() {
461 | Vector courses = new Vector();
462 |
463 | try {
464 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
465 | PreparedStatement preparedStatement = connection.prepareStatement("select Name from courses");
466 | ResultSet resultSet = preparedStatement.executeQuery();
467 |
468 | // Add every name of the courses to the "courses" vector
469 | while (resultSet.next()) {
470 | courses.add(resultSet.getString("Name"));
471 | }
472 |
473 | connection.close();
474 | preparedStatement.close();
475 | resultSet.close();
476 |
477 | } catch (SQLException e) {
478 | e.printStackTrace();
479 | }
480 |
481 | // Convert "courses" vector to String array and return it
482 | return courses.toArray(new String[0]);
483 | }
484 |
485 | /**
486 | * Updates the number of attendees in faculties and courses tables
487 | */
488 | private static void updateAttendees() {
489 | updateCoursesAttendees();
490 | updateFacultiesAttendees();
491 | }
492 |
493 | /**
494 | * Updates the number of attendees in courses table
495 | *
496 | * @return True if no exception has been thrown, false otherwise
497 | */
498 | private static boolean updateCoursesAttendees() {
499 | try {
500 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
501 | PreparedStatement preparedStatement = connection.prepareStatement("select Course from " + studentsTable);
502 | Statement statement = connection.createStatement();
503 |
504 | // Setting number of courses and attendees to 0 initially, in order to avoid
505 | // wrong calculations
506 | statement.executeUpdate("update " + getCoursesTable() + " set Attendees = 0");
507 |
508 | // Reading courses that students attend from the table
509 | ResultSet resultSet = preparedStatement.executeQuery();
510 | HashMap coursesAttendees = new HashMap();
511 |
512 | // Calculating the number of attendees to the courses
513 | MAINLOOP: while (resultSet.next()) {
514 | String currentCourse = resultSet.getString("Course");
515 |
516 | for (String key : coursesAttendees.keySet()) {
517 | // If currentCourse is already in the HashMap, increment the value of attendees
518 | if (currentCourse.equals(key)) {
519 | coursesAttendees.put(key, coursesAttendees.get(key) + 1);
520 | continue MAINLOOP;
521 | }
522 | }
523 |
524 | coursesAttendees.put(currentCourse, 1);
525 | }
526 |
527 | // Update the number of attendees to the courses in the courses table
528 | for (String key : coursesAttendees.keySet()) {
529 | statement.executeUpdate("update " + coursesTable + " set Attendees = " + coursesAttendees.get(key)
530 | + " where Name = " + "\"" + key + "\"");
531 | }
532 |
533 | connection.close();
534 | preparedStatement.close();
535 | statement.close();
536 | resultSet.close();
537 |
538 | // Return true if no exception has been thrown
539 | return true;
540 | } catch (SQLException e) {
541 | e.printStackTrace();
542 |
543 | // Return false if exception has been thrown
544 | return false;
545 | }
546 | }
547 |
548 | /**
549 | * Updates the number of attendees in faculties table
550 | *
551 | * @return True if no exception has been thrown, false otherwise
552 | */
553 | private static boolean updateFacultiesAttendees() {
554 | try {
555 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
556 | PreparedStatement preparedStatement = null, preparedStatement2 = null;
557 | Statement statement = connection.createStatement();
558 | ResultSet resultSet = null, resultSet2 = null;
559 |
560 | // Setting number of courses and attendees to 0 initially, in order to avoid
561 | // wrong calculations
562 | statement.executeUpdate("update " + facultiesTable + " set Attendees = 0, Courses = 0");
563 |
564 | // Getting the faculties of courses and number of attendees
565 | preparedStatement = connection.prepareStatement("select Faculty, Attendees from " + coursesTable);
566 | resultSet = preparedStatement.executeQuery();
567 |
568 | while (resultSet.next()) {
569 | final String faculty = resultSet.getString("Faculty");
570 | final int courseAttendees = resultSet.getInt("Attendees");
571 |
572 | preparedStatement2 = connection.prepareStatement(
573 | "select Attendees, Courses from " + facultiesTable + " where Name = " + "\"" + faculty + "\"");
574 | resultSet2 = preparedStatement2.executeQuery();
575 |
576 | resultSet2.next();
577 | final int currentNumberOfAttendees = resultSet2.getInt("Attendees");
578 | final int currentNumberOfCourses = resultSet2.getInt("Courses");
579 |
580 | statement.executeUpdate("update " + facultiesTable + " set Attendees = "
581 | + (courseAttendees + currentNumberOfAttendees) + " where Name = " + "\"" + faculty + "\"");
582 |
583 | statement.executeUpdate("update " + facultiesTable + " set Courses = " + (currentNumberOfCourses + 1)
584 | + " where Name = " + "\"" + faculty + "\"");
585 | }
586 |
587 | connection.close();
588 | preparedStatement.close();
589 | if (preparedStatement2 != null)
590 | preparedStatement2.close();
591 | resultSet.close();
592 | if (resultSet2 != null)
593 | resultSet2.close();
594 | statement.close();
595 |
596 | // Return true if no exception has been thrown
597 | return true;
598 | } catch (SQLException e) {
599 | e.printStackTrace();
600 |
601 | // Return false if exception has been thrown
602 | return false;
603 | } catch (Exception e) {
604 | e.printStackTrace();
605 |
606 | return false;
607 | }
608 | }
609 |
610 | /**
611 | * Searches if there is already an element with a certain name in a certain table
612 | *
613 | * @param tableName - The table in which user wants to check if element already
614 | * exists
615 | * @param name - The name of the element user wants to check
616 | * @return true if the element has been found, false otherwise
617 | */
618 | public static boolean checkIfElementExists(final String tableName, final String name) {
619 | try {
620 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
621 | PreparedStatement preparedStatement = connection.prepareStatement("select Name from " + tableName);
622 |
623 | // Get all the elements' name
624 | ResultSet resultSet = preparedStatement.executeQuery();
625 | while (resultSet.next()) {
626 | if (resultSet.getString("Name").equals(name)) {
627 | // Return true if an element has been found
628 | return true;
629 | }
630 | }
631 |
632 | connection.close();
633 | preparedStatement.close();
634 | resultSet.close();
635 |
636 | // Return false if no element has been found in the table
637 | return false;
638 | } catch (SQLException e) {
639 | e.printStackTrace();
640 |
641 | // Return false if an exception has been thrown
642 | return false;
643 | }
644 | }
645 |
646 | /**
647 | * Gets the number of attendees in a course or faculty
648 | *
649 | * @param tableName - The table in which user wants to check the number of
650 | * attendees(Faculties/Courses table)
651 | * @param element - The course/faculty name in which user wants to check the
652 | * number of attendees
653 | * @return The number of attendees in a faculty/course.
654 | */
655 | public static int getNumberOfAttendees(final String tableName, final String element) {
656 | try {
657 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
658 | PreparedStatement preparedStatement = connection
659 | .prepareStatement("select Attendees from " + tableName + " where Name = " + "\"" + element + "\"");
660 |
661 | // Get all the elements' name
662 | ResultSet resultSet = preparedStatement.executeQuery();
663 | resultSet.next();
664 | int attendees = resultSet.getInt("Attendees");
665 |
666 | connection.close();
667 | preparedStatement.close();
668 | resultSet.close();
669 |
670 | return attendees;
671 |
672 | } catch (SQLException e) {
673 | e.printStackTrace();
674 | return 0;
675 | }
676 | }
677 |
678 | /**
679 | * Deletes the students that attend a certain course
680 | *
681 | * @param course - The course's name which attendees should be deleted
682 | * @return True if no exception has been thrown, false otherwise
683 | */
684 | public static boolean deleteCourseAttendees(final String course) {
685 | try {
686 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
687 | Statement statement = connection.createStatement();
688 |
689 | statement.executeUpdate("delete from " + getStudentsTable() + " where Course = " + "\"" + course + "\"");
690 |
691 | updateStudents();
692 |
693 | connection.close();
694 | statement.close();
695 |
696 | return true;
697 |
698 | } catch (SQLException e) {
699 | e.printStackTrace();
700 |
701 | return false;
702 | }
703 | }
704 |
705 | /**
706 | * Deletes a course from the courses table
707 | *
708 | * @param course - The course's name which should be deleted
709 | * @return True if no exception has been thrown, false otherwise
710 | */
711 | public static boolean deleteCourse(final String course) {
712 | try {
713 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
714 | Statement statement = connection.createStatement();
715 |
716 | statement.executeUpdate("delete from " + getCoursesTable() + " where Name = " + "\"" + course + "\"");
717 |
718 | updateStudents();
719 |
720 | connection.close();
721 | statement.close();
722 |
723 | return true;
724 |
725 | } catch (SQLException e) {
726 | e.printStackTrace();
727 |
728 | return false;
729 | }
730 | }
731 |
732 | /**
733 | * Deletes a faculty from the faculties table
734 | *
735 | * @param faculty - The faculty name which should be deleted
736 | * @return True if no exception has been thrown, false otherwise
737 | */
738 | public static boolean deleteFaculty(final String faculty) {
739 | try {
740 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
741 | Statement statement = connection.createStatement();
742 |
743 | statement.executeUpdate("delete from " + getFacultiesTable() + " where Name = " + "\"" + faculty + "\"");
744 |
745 | updateStudents();
746 |
747 | connection.close();
748 | statement.close();
749 |
750 | return true;
751 |
752 | } catch (SQLException e) {
753 | e.printStackTrace();
754 |
755 | return false;
756 | }
757 | }
758 |
759 | /**
760 | * Deletes all the courses in a certain faculty
761 | *
762 | * @param faculty - The faculty whose courses should be deleted
763 | * @return True if no exception has been thrown, false otherwise
764 | */
765 | public static boolean deleteFacultyCourses(final String faculty) {
766 | try {
767 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
768 | Statement statement = connection.createStatement();
769 |
770 | // Getting the courses in that faculty, in order to delete students attending
771 | // them
772 | PreparedStatement preparedStatement = connection.prepareStatement(
773 | "select Name from " + getCoursesTable() + " where Faculty = " + "\"" + faculty + "\"");
774 | ResultSet resultSet = preparedStatement.executeQuery();
775 |
776 | while (resultSet.next()) {
777 | deleteCourseAttendees(resultSet.getString("Name"));
778 | }
779 |
780 | // Deleting the course
781 | statement.executeUpdate("delete from " + getCoursesTable() + " where Faculty = " + "\"" + faculty + "\"");
782 |
783 | updateStudents();
784 |
785 | connection.close();
786 | statement.close();
787 | preparedStatement.close();
788 | resultSet.close();
789 |
790 | return true;
791 |
792 | } catch (SQLException e) {
793 | e.printStackTrace();
794 |
795 | return false;
796 | }
797 | }
798 |
799 | /**
800 | * Gets the number of courses in a faculty
801 | *
802 | * @param faculty - The faculty's name whose number of courses should be read
803 | * @return The number of courses in a faculty
804 | */
805 | public static int getNumberOfCourses(final String faculty) {
806 | try {
807 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
808 | PreparedStatement preparedStatement = connection.prepareStatement(
809 | "select Courses from " + getFacultiesTable() + " where Name = " + "\"" + faculty + "\"");
810 |
811 | // Get Courses field's value
812 | ResultSet resultSet = preparedStatement.executeQuery();
813 | resultSet.next();
814 | int courses = resultSet.getInt("Courses");
815 |
816 | connection.close();
817 | preparedStatement.close();
818 |
819 | return courses;
820 |
821 | } catch (SQLException e) {
822 | e.printStackTrace();
823 | return 0;
824 | }
825 | }
826 |
827 | /**
828 | * Updates the contents of the database, taking into account changes from table
829 | *
830 | * @return True if no exception has been thrown, false otherwise
831 | */
832 | public static boolean updateDatabase() {
833 | // Getting row and column that user selected
834 | int selectedRow = ManagementView.table.getSelectedRow();
835 | int selectedColumn = ManagementView.table.getSelectedColumn();
836 |
837 | try {
838 | Connection connection = DriverManager.getConnection(databaseUrl, login, password);
839 | Statement statement = connection.createStatement();
840 |
841 | // If a cell has been selected
842 | if (selectedRow > -1 && selectedColumn > -1) {
843 | // Geting the selected field of the selected student and changing it in database
844 | if (selectedColumn == 1) {
845 | statement.executeUpdate("update " + studentsTable + " set Name = " + "\""
846 | + ManagementView.table.getValueAt(selectedRow, selectedColumn).toString() + "\""
847 | + " where id = "
848 | + Integer.parseInt(ManagementView.table.getValueAt(selectedRow, 0).toString()));
849 | } else if (selectedColumn == 2) {
850 | statement.executeUpdate("update " + studentsTable + " set Surname = " + "\""
851 | + ManagementView.table.getValueAt(selectedRow, selectedColumn).toString() + "\""
852 | + " where id = "
853 | + Integer.parseInt(ManagementView.table.getValueAt(selectedRow, 0).toString()));
854 | } else if (selectedColumn == 3) {
855 | statement.executeUpdate("update " + studentsTable + " set Age = "
856 | + Integer.parseInt(ManagementView.table.getValueAt(selectedRow, selectedColumn).toString())
857 | + " where id = "
858 | + Integer.parseInt(ManagementView.table.getValueAt(selectedRow, 0).toString()));
859 | } else if (selectedColumn == 4) {
860 | statement.executeUpdate("update " + studentsTable + " set Gender = " + "\""
861 | + ManagementView.table.getValueAt(selectedRow, selectedColumn).toString() + "\""
862 | + " where id = "
863 | + Integer.parseInt(ManagementView.table.getValueAt(selectedRow, 0).toString()));
864 | }
865 | }
866 |
867 | connection.close();
868 | statement.close();
869 |
870 | // Return true if no exception has been thrown
871 | return true;
872 | } catch (SQLException e) {
873 | e.printStackTrace();
874 |
875 | // Return false if exception has been thrown
876 | return false;
877 | } catch (Exception ex) {
878 | ex.printStackTrace();
879 |
880 | return false;
881 | }
882 | }
883 | }
884 |
--------------------------------------------------------------------------------