-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstudent-grading-system-java.java
More file actions
432 lines (391 loc) · 20.9 KB
/
student-grading-system-java.java
File metadata and controls
432 lines (391 loc) · 20.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.List;
import java.util.regex.Pattern;
public class StudentGradingSystem {
public static void main(String[] args) {
try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ignored) {}
EventQueue.invokeLater(RoleSelector::new);
}
}
/* Role selector window */
class RoleSelector extends JFrame {
RoleSelector() {
setTitle("Institution Portal");
setSize(420, 280);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JLabel hdr = new JLabel("Academic Portal", SwingConstants.LEFT);
hdr.setOpaque(true);
hdr.setBackground(new Color(12,97,33));
hdr.setForeground(Color.WHITE);
hdr.setBorder(new EmptyBorder(14,16,14,16));
hdr.setFont(hdr.getFont().deriveFont(Font.BOLD, 18f));
add(hdr, BorderLayout.NORTH);
JPanel center = new JPanel(new GridBagLayout());
center.setBackground(Color.WHITE);
GridBagConstraints g = new GridBagConstraints();
g.insets = new Insets(12,0,12,0);
JButton teacher = colored("Teacher Dashboard", new Color(33,150,243));
JButton student = colored("Student Dashboard", new Color(46,125,50));
teacher.setPreferredSize(new Dimension(320,52));
student.setPreferredSize(new Dimension(320,52));
teacher.addActionListener(e -> { new DashboardFrame(true); dispose(); });
student.addActionListener(e -> { new DashboardFrame(false); dispose(); });
g.gridy = 0; center.add(teacher, g);
g.gridy = 1; center.add(student, g);
add(center, BorderLayout.CENTER);
JLabel foot = new JLabel(" Version 1.1 • CSV backend");
foot.setBorder(new EmptyBorder(8,10,8,10));
add(foot, BorderLayout.SOUTH);
setVisible(true);
}
private JButton colored(String text, Color bg){
JButton b = new JButton(text);
// ensure background color is painted across LAFs
b.setOpaque(true);
b.setContentAreaFilled(true);
b.setBorderPainted(false);
b.setBackground(bg);
b.setForeground(Color.WHITE);
b.setFocusPainted(false);
return b;
}
}
/* Main dashboard window */
class DashboardFrame extends JFrame {
private final boolean isTeacher;
// Override DefaultTableModel so we can provide proper column classes (important for sorting)
private final DefaultTableModel model = new DefaultTableModel(new Object[]{"ID","Name","Marks","Grade","Status"}, 0) {
@Override public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 2: return Integer.class; // Marks -> numeric
default: return String.class;
}
}
@Override public boolean isCellEditable(int row, int column) { return false; }
};
private final JTable table = new JTable(model);
private TableRowSorter<TableModel> sorter;
private JTextField txtSearch, txtId, txtName, txtMarks;
private JComboBox<String> filterBox;
private JLabel lblGrade;
private final String FILE = "students.csv";
DashboardFrame(boolean isTeacher) {
this.isTeacher = isTeacher;
setTitle(isTeacher ? "Teacher Dashboard" : "Student Dashboard");
setSize(1100, 720);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel root = new JPanel(new BorderLayout());
root.setBackground(Color.WHITE);
root.add(headerPanel(), BorderLayout.NORTH);
root.add(createMain(), BorderLayout.CENTER);
setContentPane(root);
loadCSV();
setVisible(true);
}
private JComponent headerPanel() {
JLabel header = new JLabel(" " + (isTeacher ? "TEACHER DASHBOARD" : "STUDENT DASHBOARD"));
header.setOpaque(true);
header.setBackground(isTeacher ? new Color(44,62,80) : new Color(39,174,96));
header.setForeground(Color.WHITE);
header.setFont(header.getFont().deriveFont(Font.BOLD, 18f));
header.setBorder(new EmptyBorder(12,12,12,12));
return header;
}
private Component createMain() {
JPanel main = new JPanel(new BorderLayout(12,12));
main.setBorder(new EmptyBorder(12,12,12,12));
main.setBackground(Color.WHITE);
main.add(toolbar(), BorderLayout.NORTH);
JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, tableCard(), detailCard());
split.setResizeWeight(0.65);
split.setBorder(null);
main.add(split, BorderLayout.CENTER);
JPanel bottom = new JPanel(new FlowLayout(FlowLayout.CENTER, 12, 12));
bottom.setBackground(Color.WHITE);
if (isTeacher) {
bottom.add(actionButton("Add", new Color(52,152,219), e -> openAddDialog()));
bottom.add(actionButton("Edit", new Color(241,196,15), e -> openEditDialog()));
bottom.add(actionButton("Delete", new Color(231,76,60), e -> deleteSelected()));
}
main.add(bottom, BorderLayout.SOUTH);
return main;
}
private JPanel toolbar() {
JPanel t = new JPanel(new BorderLayout(8,8));
t.setBackground(Color.WHITE);
JPanel c = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 6));
c.setBackground(Color.WHITE);
txtSearch = new JTextField(24);
txtSearch.getDocument().addDocumentListener(new SimpleDoc(this::applyFilter));
filterBox = new JComboBox<>(new String[]{"All","PASS","FAIL"});
filterBox.addActionListener(e -> applyFilter());
c.add(txtSearch); c.add(filterBox);
t.add(c, BorderLayout.CENTER);
JPanel right = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 6));
right.setBackground(Color.WHITE);
JButton reload = new JButton("Reload");
styleButton(reload, new Color(67,160,71));
reload.addActionListener(e -> { loadCSV(); txtSearch.setText(""); filterBox.setSelectedIndex(0); });
JButton save = new JButton("Save");
styleButton(save, new Color(102,51,153));
save.addActionListener(e -> saveCSV());
right.add(reload); right.add(save);
t.add(right, BorderLayout.EAST);
return t;
}
private JPanel tableCard() {
JPanel card = new JPanel(new BorderLayout(8,8));
card.setBackground(Color.WHITE);
card.setBorder(new CompoundBorder(new LineBorder(new Color(230,230,230)), new EmptyBorder(10,10,10,10)));
table.setRowHeight(26);
table.getTableHeader().setBackground(new Color(240,240,240));
table.setDefaultRenderer(Object.class, new AltRenderer());
sorter = new TableRowSorter<>(model);
// ensure numeric comparator for marks column
sorter.setComparator(2, Comparator.comparingInt(o -> ((Integer)o)));
table.setRowSorter(sorter);
card.add(new JScrollPane(table), BorderLayout.CENTER);
if (isTeacher) {
JPanel bottom = new JPanel(new FlowLayout(FlowLayout.RIGHT));
bottom.setBackground(Color.WHITE);
bottom.add(actionButton("Add Student", new Color(33,150,243), e -> openAddDialog()));
bottom.add(actionButton("Edit Selected", new Color(255,193,7), e -> openEditDialog()));
bottom.add(actionButton("Delete Selected", new Color(233,30,99), e -> deleteSelected()));
card.add(bottom, BorderLayout.SOUTH);
}
return card;
}
private JPanel detailCard() {
JPanel card = new JPanel(new BorderLayout(8,8));
card.setBackground(Color.WHITE);
card.setBorder(new CompoundBorder(new LineBorder(new Color(230,230,230)), new EmptyBorder(10,10,10,10)));
JPanel info = new JPanel(new GridLayout(4,1,6,6));
info.setBackground(Color.WHITE);
txtId = new JTextField(); txtName = new JTextField(); txtMarks = new JTextField();
txtId.setEditable(false); txtName.setEditable(false); txtMarks.setEditable(false);
lblGrade = new JLabel("-", SwingConstants.CENTER); lblGrade.setFont(lblGrade.getFont().deriveFont(Font.BOLD, 16f));
info.add(field("Student ID", txtId)); info.add(field("Student Name", txtName)); info.add(field("Marks", txtMarks)); info.add(field("Grade", lblGrade));
card.add(info, BorderLayout.NORTH);
GradePanel chart = new GradePanel();
card.add(chart, BorderLayout.CENTER);
table.getSelectionModel().addListSelectionListener(e -> { if (!e.getValueIsAdjusting()) { displaySelection(); chart.repaint(); }});
return card;
}
private JPanel field(String label, JComponent comp) {
JPanel p = new JPanel(new BorderLayout(6,6));
p.setBackground(Color.WHITE);
p.add(new JLabel(label), BorderLayout.WEST);
p.add(comp, BorderLayout.CENTER);
return p;
}
private JButton actionButton(String text, Color bg, ActionListener a) {
JButton b = new JButton(text);
styleButton(b, bg);
b.addActionListener(a);
return b;
}
// central styling for colored buttons to ensure visibility
private void styleButton(JButton b, Color bg) {
b.setOpaque(true);
b.setContentAreaFilled(true);
b.setBorderPainted(false);
b.setBackground(bg);
b.setForeground(Color.WHITE);
b.setFocusPainted(false);
}
private void openAddDialog() {
JDialog d = new JDialog(this, "Add Student", true);
d.setSize(420, 300); d.setLocationRelativeTo(this);
JPanel p = new JPanel(null); p.setBackground(Color.WHITE);
JTextField f1 = new JTextField(), f2 = new JTextField(), f3 = new JTextField();
place(p, new JLabel("ID:"), 20,20,80,24); place(p, f1, 110,20,270,28);
place(p, new JLabel("Name:"), 20,60,80,24); place(p, f2, 110,60,270,28);
place(p, new JLabel("Marks:"), 20,100,80,24); place(p, f3, 110,100,120,28);
JButton ok = new JButton("Add"); styleButton(ok, new Color(33,150,243)); ok.setBounds(110,160,120,36);
ok.addActionListener(e -> {
String id = f1.getText().trim(), name = f2.getText().trim(), mk = f3.getText().trim();
if (id.isEmpty() || name.isEmpty() || mk.isEmpty()) { JOptionPane.showMessageDialog(d, "All fields required"); return; }
// duplicate ID check
for (int i = 0; i < model.getRowCount(); i++) {
if (String.valueOf(model.getValueAt(i,0)).equals(id)) {
JOptionPane.showMessageDialog(d, "Student ID already exists");
return;
}
}
try {
int m = Integer.parseInt(mk); if (m < 0 || m > 100) throw new NumberFormatException();
model.addRow(new Object[]{id, name.replace(",", ";"), m, gradeFor(m), m >= 50 ? "PASS" : "FAIL"});
d.dispose();
} catch (NumberFormatException ex) { JOptionPane.showMessageDialog(d, "Marks must be 0-100"); }
});
JButton cancel = new JButton("Cancel"); styleButton(cancel, new Color(158,158,158)); cancel.setBounds(250,160,120,36); cancel.addActionListener(e -> d.dispose());
p.add(ok); p.add(cancel); d.setContentPane(p); d.setVisible(true);
}
private void openEditDialog() {
int r = table.getSelectedRow(); if (r < 0) { JOptionPane.showMessageDialog(this, "Select a record to edit"); return; }
int mr = table.convertRowIndexToModel(r);
JDialog d = new JDialog(this, "Edit Student", true);
d.setSize(420, 300); d.setLocationRelativeTo(this);
JPanel p = new JPanel(null); p.setBackground(Color.WHITE);
JTextField f1 = new JTextField(String.valueOf(model.getValueAt(mr,0))), f2 = new JTextField(String.valueOf(model.getValueAt(mr,1))), f3 = new JTextField(String.valueOf(model.getValueAt(mr,2)));
place(p, new JLabel("ID:"), 20,20,80,24); place(p, f1, 110,20,270,28);
place(p, new JLabel("Name:"), 20,60,80,24); place(p, f2, 110,60,270,28);
place(p, new JLabel("Marks:"), 20,100,80,24); place(p, f3, 110,100,120,28);
JButton ok = new JButton("Update"); styleButton(ok, new Color(241,196,15)); ok.setBounds(110,160,120,36);
ok.addActionListener(e -> {
String id = f1.getText().trim(), name = f2.getText().trim(), mk = f3.getText().trim();
if (id.isEmpty() || name.isEmpty() || mk.isEmpty()) { JOptionPane.showMessageDialog(d, "All fields required"); return; }
try {
int m = Integer.parseInt(mk); if (m < 0 || m > 100) throw new NumberFormatException();
model.setValueAt(id, mr, 0); model.setValueAt(name.replace(",", ";"), mr, 1); model.setValueAt(m, mr, 2); model.setValueAt(gradeFor(m), mr, 3);
model.setValueAt(m >= 50 ? "PASS" : "FAIL", mr, 4);
d.dispose();
} catch (NumberFormatException ex) { JOptionPane.showMessageDialog(d, "Marks must be 0-100"); }
});
JButton cancel = new JButton("Cancel"); styleButton(cancel, new Color(158,158,158)); cancel.setBounds(250,160,120,36); cancel.addActionListener(e -> d.dispose());
p.add(ok); p.add(cancel); d.setContentPane(p); d.setVisible(true);
}
private void deleteSelected() {
int r = table.getSelectedRow(); if (r < 0) { JOptionPane.showMessageDialog(this, "Select a record to delete"); return; }
if (JOptionPane.showConfirmDialog(this, "Delete selected record?", "Confirm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
model.removeRow(table.convertRowIndexToModel(r));
}
}
private void displaySelection() {
int r = table.getSelectedRow(); if (r < 0) { txtId.setText(""); txtName.setText(""); txtMarks.setText(""); lblGrade.setText("-"); return; }
int mr = table.convertRowIndexToModel(r);
txtId.setText(String.valueOf(model.getValueAt(mr,0)));
txtName.setText(String.valueOf(model.getValueAt(mr,1)).replace(";", ",")); // show commas back
txtMarks.setText(String.valueOf(model.getValueAt(mr,2)));
lblGrade.setText(String.valueOf(model.getValueAt(mr,3)));
}
private void applyFilter() {
if (sorter == null) return;
String txt = txtSearch.getText().trim();
String status = String.valueOf(filterBox.getSelectedItem());
List<RowFilter<Object,Object>> filters = new ArrayList<>();
if (!txt.isEmpty()) {
// case-insensitive substring search on ID or Name
String regex = "(?i)." + Pattern.quote(txt) + ".";
filters.add(RowFilter.regexFilter(regex, 0, 1));
}
if (!"All".equals(status)) filters.add(RowFilter.regexFilter(status, 4));
sorter.setRowFilter(filters.isEmpty() ? null : RowFilter.andFilter(filters));
}
private void saveCSV() {
try (PrintWriter pw = new PrintWriter(new FileWriter(FILE))) {
for (int i = 0; i < model.getRowCount(); i++) {
String id = String.valueOf(model.getValueAt(i,0));
String name = String.valueOf(model.getValueAt(i,1)).replace(",", ";");
String marks = String.valueOf(model.getValueAt(i,2));
String grade = String.valueOf(model.getValueAt(i,3));
String status = String.valueOf(model.getValueAt(i,4));
pw.println(String.join(",", id, name, marks, grade, status));
}
JOptionPane.showMessageDialog(this, "Saved to " + FILE);
} catch (IOException ex) { JOptionPane.showMessageDialog(this, "Save failed: " + ex.getMessage()); }
}
private void loadCSV() {
model.setRowCount(0);
File f = new File(FILE);
if (!f.exists()) return;
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) continue;
String[] p = line.split(",", -1);
if (p.length >= 5) {
try {
String id = p[0];
String name = p[1].replace(";", ",");
int marks = Integer.parseInt(p[2]);
String grade = p[3];
String status = p[4];
model.addRow(new Object[]{id, name, marks, grade, status});
} catch (NumberFormatException nfe) {
// skip malformed mark
}
}
}
} catch (Exception ex) { JOptionPane.showMessageDialog(this, "Load failed: " + ex.getMessage()); }
}
private int gradeForInt(String g) {
switch (g) {
case "A+": return 95; case "A": return 85; case "B": return 75; case "C": return 65; case "D": return 55;
default: return 30;
}
}
private String gradeFor(int m) {
if (m >= 90) return "A+"; if (m >= 80) return "A"; if (m >= 70) return "B"; if (m >= 60) return "C";
if (m >= 50) return "D"; return "F";
}
private void place(JPanel p, Component c, int x, int y, int w, int h) { c.setBounds(x,y,w,h); p.add(c); }
/* small renderer for table rows */
private class AltRenderer extends DefaultTableCellRenderer {
@Override public Component getTableCellRendererComponent(JTable t, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
Component c = super.getTableCellRendererComponent(t, value, isSelected, hasFocus, row, col);
if (isSelected) c.setBackground(new Color(200,230,255)); else c.setBackground(row % 2 == 0 ? Color.WHITE : new Color(250,250,250));
setBorder(new EmptyBorder(4,8,4,8));
return c;
}
}
/* compact grade chart panel */
class GradePanel extends JPanel {
GradePanel() { setPreferredSize(new Dimension(360,320)); setBackground(Color.WHITE); setBorder(new EmptyBorder(10,10,10,10)); }
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Count grades in a clear, maintainable way
Map<String,Integer> counts = new LinkedHashMap<>();
counts.put("A+",0); counts.put("A",0); counts.put("B",0); counts.put("C",0); counts.put("D/F",0);
for (int i = 0; i < model.getRowCount(); i++) {
String gr = String.valueOf(model.getValueAt(i,3));
if ("A+".equals(gr) || "A".equals(gr) || "B".equals(gr) || "C".equals(gr)) {
counts.put(gr, counts.get(gr) + 1);
} else {
// group D and F and any unexpected grades into D/F
counts.put("D/F", counts.get("D/F") + 1);
}
}
int max = counts.values().stream().mapToInt(x->x).max().orElse(1);
int w = getWidth(), h = getHeight(), base = h - 60;
Color[] pal = { new Color(30,136,229), new Color(67,160,71), new Color(253,216,53), new Color(156,39,176), new Color(244,67,54) };
int x = 28, bw = 40, gap = 18, idx = 0;
g2.setColor(new Color(40,40,40)); g2.setFont(getFont().deriveFont(Font.BOLD, 14f)); g2.drawString("Grade Distribution", 12, 18);
for (Map.Entry<String,Integer> e : counts.entrySet()) {
int v = e.getValue();
double ratio = max == 0 ? 0 : ((double)v)/max;
int bh = (int)((h-140) * ratio);
int y = base - bh;
g2.setPaint(new GradientPaint(x,y,pal[idx],x,y+bh,pal[idx].darker()));
g2.fill(new RoundRectangle2D.Double(x,y,bw,Math.max(6,bh),8,8));
g2.setColor(Color.DARK_GRAY);
g2.setFont(getFont().deriveFont(12f));
g2.drawString(e.getKey(), x, base + 22);
g2.drawString(String.valueOf(v), x + 12, Math.max(12, y - 8));
x += bw + gap; idx++;
}
g2.setColor(new Color(110,110,110));
g2.drawString("Total: " + model.getRowCount(), 12, h - 12);
g2.dispose();
}
}
/* Simple DocumentListener wrapper */
static class SimpleDoc implements DocumentListener {
private final Runnable r; SimpleDoc(Runnable r) { this.r = r; }
public void insertUpdate(DocumentEvent e) { r.run(); } public void removeUpdate(DocumentEvent e) { r.run(); } public void changedUpdate(DocumentEvent e) { r.run(); }
}
}