-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSchedulingGUI.java
More file actions
713 lines (618 loc) · 23.2 KB
/
Copy pathSchedulingGUI.java
File metadata and controls
713 lines (618 loc) · 23.2 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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
package algorithms;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class SchedulingGUI extends JFrame {
private ArrayList<Process> processList = new ArrayList<>();
private DefaultTableModel inputTableModel;
private DefaultTableModel resultTableModel;
private JTable inputTable;
private JTable resultTable;
private JComboBox<String> algorithmComboBox;
private JTextField processIdField, burstTimeField, priorityField,
arrivalTimeField, quantumField;
private JButton addButton, calculateButton, clearButton;
private JLabel avgWaitTimeLabel, avgTurnaroundTimeLabel;
private JPanel ganttChartPanel;
private Color[] processColors;
private JCheckBox priorityCheckBox, arrivalCheckBox;
// Simplified color scheme
private final Color PRIMARY_COLOR = new Color(100, 149, 237); // Cornflower
private final Color BACKGROUND_COLOR = new Color(240, 240, 240); // blue
private final Color TEXT_COLOR = new Color(50, 50, 50);
private final Color BUTTON_COLOR = new Color(100, 149, 237);
// Simplified fonts
private final Font HEADER_FONT = new Font("Arial", Font.BOLD, 14);
private final Font REGULAR_FONT = new Font("Arial", Font.PLAIN, 12);
private final Font BUTTON_FONT = new Font("Arial", Font.BOLD, 12);
// Scheduling algorithm instances
private FCFSScheduling fcfsScheduler;
private SJFScheduling sjfScheduler;
private PriorityScheduling priorityScheduler;
private RoundRobinScheduling rrScheduler;
public SchedulingGUI() {
setTitle("CPU Scheduling Simulator");
setSize(800, 700); // Increased height for algorithm buttons
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
getContentPane().setBackground(BACKGROUND_COLOR);
// Initialize schedulers
fcfsScheduler = new FCFSScheduling();
sjfScheduler = new SJFScheduling();
priorityScheduler = new PriorityScheduling();
rrScheduler = new RoundRobinScheduling();
// Initialize process colors
processColors = new Color[]{new Color(66, 165, 245), // blue
new Color(236, 64, 122), // pink
new Color(255, 167, 38), // orange
new Color(102, 187, 106), // green
new Color(171, 71, 188), // purple
new Color(41, 182, 246), // light blue
new Color(255, 112, 67), // deep orange
new Color(92, 107, 192), // indigo
new Color(229, 115, 115), // red
new Color(120, 144, 156) // blue grey
};
initComponents();
// Set default quantum value
quantumField.setText("2");
}
private void initComponents() {
// Main layout
setLayout(new BorderLayout(10, 10));
// Controls Panel
JPanel controlsPanel = new JPanel(new GridLayout(2, 1, 5, 5));
controlsPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 5, 10));
// Process Options Panel
JPanel processOptionsPanel = new JPanel(
new FlowLayout(FlowLayout.LEFT, 5, 0));
// Process ID field
JLabel processIdLabel = new JLabel("Process ID:");
processIdField = new JTextField(5);
processOptionsPanel.add(processIdLabel);
processOptionsPanel.add(processIdField);
// Burst Time field
JLabel burstTimeLabel = new JLabel("Burst Time:");
burstTimeField = new JTextField(5);
processOptionsPanel.add(burstTimeLabel);
processOptionsPanel.add(burstTimeField);
// Priority field with checkbox
JLabel priorityLabel = new JLabel("Priority:");
priorityField = new JTextField(5);
priorityField.setEnabled(false);
priorityCheckBox = new JCheckBox("Use Priority");
priorityCheckBox.addActionListener(e -> {
boolean selected = priorityCheckBox.isSelected();
priorityField.setEnabled(selected);
});
processOptionsPanel.add(priorityLabel);
processOptionsPanel.add(priorityField);
processOptionsPanel.add(priorityCheckBox);
// Arrival Time field with checkbox
JLabel arrivalTimeLabel = new JLabel("Arrival Time:");
arrivalTimeField = new JTextField(5);
arrivalTimeField.setEnabled(false);
arrivalCheckBox = new JCheckBox("Use Arrival Time");
arrivalCheckBox.addActionListener(e -> {
boolean selected = arrivalCheckBox.isSelected();
arrivalTimeField.setEnabled(selected);
});
processOptionsPanel.add(arrivalTimeLabel);
processOptionsPanel.add(arrivalTimeField);
processOptionsPanel.add(arrivalCheckBox);
// Add Process button
addButton = createButton("Add Process");
processOptionsPanel.add(addButton);
controlsPanel.add(processOptionsPanel);
// Algorithm Options Panel
JPanel algorithmOptionsPanel = new JPanel(
new FlowLayout(FlowLayout.LEFT, 5, 0));
// Algorithm ComboBox
JLabel algorithmLabel = new JLabel("Algorithm:");
algorithmComboBox = new JComboBox<>(
new String[]{"First Come First Serve", "Priority Scheduling",
"Shortest Job First", "Round Robin"});
algorithmOptionsPanel.add(algorithmLabel);
algorithmOptionsPanel.add(algorithmComboBox);
// Quantum field for Round Robin
JLabel quantumLabel = new JLabel("Time Quantum (RR):");
quantumField = new JTextField(5);
quantumField.setEnabled(false);
algorithmOptionsPanel.add(quantumLabel);
algorithmOptionsPanel.add(quantumField);
// Action buttons
calculateButton = createButton("Calculate");
clearButton = createButton("Clear");
algorithmOptionsPanel.add(calculateButton);
algorithmOptionsPanel.add(clearButton);
controlsPanel.add(algorithmOptionsPanel);
// Algorithm selection listener
algorithmComboBox.addActionListener(e -> {
boolean isRR = algorithmComboBox.getSelectedItem()
.equals("Round Robin");
quantumField.setEnabled(isRR);
});
// Content Panels (Tables and Chart)
JPanel contentPanel = new JPanel(new BorderLayout(10, 10));
contentPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 5, 10));
// Tables Panel (Input and Results side by side)
JPanel tablesPanel = new JPanel(new GridLayout(1, 2, 10, 0));
// Input Table
JPanel inputPanel = new JPanel(new BorderLayout());
inputPanel
.setBorder(BorderFactory.createTitledBorder("Input Processes"));
String[] inputColumnNames = {"Process", "Arrival Time", "Burst Time",
"Priority"};
inputTableModel = new DefaultTableModel(inputColumnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
inputTable = new JTable(inputTableModel);
inputTable.setFillsViewportHeight(true);
JScrollPane inputScrollPane = new JScrollPane(inputTable);
inputPanel.add(inputScrollPane, BorderLayout.CENTER);
tablesPanel.add(inputPanel);
// Results Table
JPanel resultPanel = new JPanel(new BorderLayout());
resultPanel.setBorder(BorderFactory.createTitledBorder("Results"));
String[] resultColumnNames = {"Process", "Arrival Time", "Burst Time",
"Start Time", "Completion Time", "Turnaround Time",
"Waiting Time"};
resultTableModel = new DefaultTableModel(resultColumnNames, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
resultTable = new JTable(resultTableModel);
resultTable.setFillsViewportHeight(true);
resultTable.setDefaultRenderer(Object.class, new TableCellRenderer() {
private final TableCellRenderer defaultRenderer = resultTable
.getDefaultRenderer(Object.class);
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
Component c = defaultRenderer.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
if (column == 0 && c instanceof JLabel) {
// Color the process ID cell with process color
int processId = Integer
.parseInt(((JLabel) c).getText().replace("P", ""));
c.setBackground(
processColors[processId % processColors.length]);
c.setForeground(Color.WHITE);
} else {
if (!isSelected) {
c.setBackground(row % 2 == 0
? Color.WHITE
: new Color(245, 245, 245));
c.setForeground(TEXT_COLOR);
}
}
return c;
}
});
JScrollPane resultScrollPane = new JScrollPane(resultTable);
resultPanel.add(resultScrollPane, BorderLayout.CENTER);
tablesPanel.add(resultPanel);
contentPanel.add(tablesPanel, BorderLayout.CENTER);
// Gantt Chart Panel
JPanel chartContainer = new JPanel(new BorderLayout());
chartContainer
.setBorder(BorderFactory.createTitledBorder("Gantt Chart"));
ganttChartPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Fix: Call drawGanttChart method properly
if (processList.isEmpty()) {
return;
}
Process[] processes = processList.toArray(new Process[0]);
String selectedAlgorithm = (String) algorithmComboBox
.getSelectedItem();
// Use Graphics2D for better rendering
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int width = getWidth();
int height = getHeight();
int padding = 20;
int chartHeight = 40;
int y = (height - chartHeight) / 2 - 10;
// Find total time
int totalTime = 0;
for (Process p : processes) {
totalTime = Math.max(totalTime, p.completionTime);
}
if (totalTime == 0) {
g2d.setFont(new Font("Arial", Font.ITALIC, 14));
g2d.setColor(Color.GRAY);
String msg = "No processes scheduled";
int msgWidth = g2d.getFontMetrics().stringWidth(msg);
g2d.drawString(msg, (width - msgWidth) / 2, height / 2);
return;
}
// Calculate scale factor
float scale = (float) (width - 2 * padding) / totalTime;
// Special handling for Round Robin
if (selectedAlgorithm.equals("Round Robin")
&& processes.length > 0
&& processes[0].ganttData != null) {
drawRoundRobinGantt(g2d, processes[0], width, height,
padding, chartHeight, y, scale);
} else {
// Draw standard Gantt chart for other algorithms
drawStandardGantt(g2d, processes, width, height, padding,
chartHeight, y, scale);
}
// Draw timeline
int timelineY = y + chartHeight + 10;
g2d.setColor(Color.BLACK);
g2d.drawLine(padding, timelineY, width - padding, timelineY);
// Draw time markers
g2d.setFont(new Font("Arial", Font.PLAIN, 10));
for (int i = 0; i <= totalTime; i++) {
if (i % 1 == 0 || i == totalTime) { // Draw fewer markers
// for readability
int x = padding + (int) (i * scale);
g2d.drawLine(x, timelineY, x, timelineY + 5);
String timeLabel = Integer.toString(i);
int labelWidth = g2d.getFontMetrics()
.stringWidth(timeLabel);
g2d.drawString(timeLabel, x - labelWidth / 2,
timelineY + 15);
}
}
}
};
ganttChartPanel.setPreferredSize(new Dimension(0, 100));
ganttChartPanel.setBackground(Color.WHITE);
chartContainer.add(ganttChartPanel, BorderLayout.CENTER);
// Average time labels
JPanel statsPanel = new JPanel(
new FlowLayout(FlowLayout.CENTER, 20, 5));
avgWaitTimeLabel = new JLabel("Average Waiting Time: 0.0");
avgTurnaroundTimeLabel = new JLabel("Average Turnaround Time: 0.0");
avgWaitTimeLabel.setFont(HEADER_FONT);
avgTurnaroundTimeLabel.setFont(HEADER_FONT);
statsPanel.add(avgWaitTimeLabel);
statsPanel.add(avgTurnaroundTimeLabel);
chartContainer.add(statsPanel, BorderLayout.SOUTH);
contentPanel.add(chartContainer, BorderLayout.SOUTH);
// Add components to main frame
add(controlsPanel, BorderLayout.NORTH);
add(contentPanel, BorderLayout.CENTER);
// Add event listeners
addEventListeners();
// Setup keyboard shortcuts
setupKeyboardShortcuts();
}
private JButton createButton(String text) {
JButton button = new JButton(text);
button.setFont(BUTTON_FONT);
button.setBackground(BUTTON_COLOR);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
return button;
}
private void addEventListeners() {
// Add process button
addButton.addActionListener(e -> {
try {
if (processIdField.getText().isEmpty()
|| burstTimeField.getText().isEmpty()) {
JOptionPane.showMessageDialog(this,
"Process ID and Burst Time are required!",
"Input Error", JOptionPane.ERROR_MESSAGE);
return;
}
int processId = Integer.parseInt(processIdField.getText());
int burstTime = Integer.parseInt(burstTimeField.getText());
int priority = priorityCheckBox.isSelected()
? Integer.parseInt(priorityField.getText())
: 0;
int arrivalTime = arrivalCheckBox.isSelected()
? Integer.parseInt(arrivalTimeField.getText())
: 0;
// Check if process ID already exists
for (Process p : processList) {
if (p.id == processId) {
JOptionPane.showMessageDialog(this,
"Process ID already exists!", "Input Error",
JOptionPane.ERROR_MESSAGE);
return;
}
}
// Add process to list
Process process = new Process(processId, burstTime, priority,
arrivalTime);
processList.add(process);
// Add to input table
inputTableModel.addRow(new Object[]{"P" + processId,
arrivalTime, burstTime,
priorityCheckBox.isSelected() ? priority : "-"});
// Clear input fields
processIdField.setText("");
burstTimeField.setText("");
priorityField.setText("");
arrivalTimeField.setText("");
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this,
"Please enter valid numeric values!", "Input Error",
JOptionPane.ERROR_MESSAGE);
}
});
// Calculate button
calculateButton.addActionListener(e -> {
if (processList.isEmpty()) {
JOptionPane.showMessageDialog(this,
"Please add at least one process!", "Input Error",
JOptionPane.ERROR_MESSAGE);
return;
}
// Convert ArrayList to array for scheduling
Process[] processes = processList.toArray(new Process[0]);
String selectedAlgorithm = (String) algorithmComboBox
.getSelectedItem();
// Apply selected algorithm
switch (selectedAlgorithm) {
case "First Come First Serve" :
fcfsScheduler.schedule(processes);
break;
case "Shortest Job First" :
sjfScheduler.schedule(processes);
break;
case "Priority Scheduling" :
priorityScheduler.schedule(processes);
break;
case "Round Robin" :
try {
int quantum = Integer.parseInt(quantumField.getText());
if (quantum <= 0) {
JOptionPane.showMessageDialog(this,
"Time quantum must be greater than zero!",
"Input Error", JOptionPane.ERROR_MESSAGE);
return;
}
rrScheduler.schedule(processes, quantum);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this,
"Please enter a valid time quantum!",
"Input Error", JOptionPane.ERROR_MESSAGE);
return;
}
break;
}
// Calculate average times
double avgWaitTime = 0;
double avgTurnaroundTime = 0;
switch (selectedAlgorithm) {
case "First Come First Serve" :
avgWaitTime = fcfsScheduler
.getAverageWaitingTime(processes);
avgTurnaroundTime = fcfsScheduler
.getAverageTurnaroundTime(processes);
break;
case "Shortest Job First" :
avgWaitTime = sjfScheduler.getAverageWaitingTime(processes);
avgTurnaroundTime = sjfScheduler
.getAverageTurnaroundTime(processes);
break;
case "Priority Scheduling" :
avgWaitTime = priorityScheduler
.getAverageWaitingTime(processes);
avgTurnaroundTime = priorityScheduler
.getAverageTurnaroundTime(processes);
break;
case "Round Robin" :
avgWaitTime = rrScheduler.getAverageWaitingTime(processes);
avgTurnaroundTime = rrScheduler
.getAverageTurnaroundTime(processes);
break;
}
// Update result table
updateResultTable(processes);
// Update average time labels
avgWaitTimeLabel.setText(
String.format("Average Waiting Time: %.2f", avgWaitTime));
avgTurnaroundTimeLabel.setText(String.format(
"Average Turnaround Time: %.2f", avgTurnaroundTime));
// Repaint Gantt chart
ganttChartPanel.repaint();
});
// Clear button
clearButton.addActionListener(e -> {
processList.clear();
inputTableModel.setRowCount(0);
resultTableModel.setRowCount(0);
avgWaitTimeLabel.setText("Average Waiting Time: 0.0");
avgTurnaroundTimeLabel.setText("Average Turnaround Time: 0.0");
ganttChartPanel.repaint();
});
}
private void updateResultTable(Process[] processes) {
// Clear result table
resultTableModel.setRowCount(0);
// Sort processes by ID for display
Arrays.sort(processes, Comparator.comparingInt(p -> p.id));
// Add processes to result table
for (Process p : processes) {
resultTableModel.addRow(new Object[]{"P" + p.id, p.arrivalTime,
p.burstTime, p.startTime, p.completionTime,
p.turnAroundTime, p.waitingTime});
}
}
private void drawStandardGantt(Graphics2D g2d, Process[] processes,
int width, int height, int padding, int chartHeight, int y,
float scale) {
// Reduce chart height slightly
int adjustedChartHeight = chartHeight - 5;
// Sort processes by start time for drawing
Arrays.sort(processes, Comparator.comparingInt(p -> p.startTime));
for (int i = 0; i < processes.length; i++) {
Process p = processes[i];
// Calculate position and width
int x = padding + (int) (p.startTime * scale);
int blockWidth = Math.max(1, (int) (p.burstTime * scale));
// Draw process block
Color processColor = processColors[p.id % processColors.length];
g2d.setColor(processColor);
g2d.fillRect(x, y, blockWidth, adjustedChartHeight);
g2d.setColor(Color.BLACK);
g2d.drawRect(x, y, blockWidth, adjustedChartHeight);
// Draw process label
g2d.setColor(Color.BLACK);
g2d.setFont(new Font("Arial", Font.BOLD, 12));
String label = "P" + p.id;
int labelWidth = g2d.getFontMetrics().stringWidth(label);
int labelHeight = g2d.getFontMetrics().getHeight();
// Better center the label within the block (both horizontally and
// vertically)
if (labelWidth < blockWidth - 4) {
int textX = x + (blockWidth - labelWidth) / 2;
int textY = y + (adjustedChartHeight + labelHeight) / 2 - 2;
g2d.drawString(label, textX, textY);
}
// Draw time at start of block
g2d.setFont(new Font("Arial", Font.PLAIN, 10));
String startTime = Integer.toString(p.startTime);
labelWidth = g2d.getFontMetrics().stringWidth(startTime);
g2d.drawString(startTime, x - labelWidth / 2, y - 2);
}
}
private void drawRoundRobinGantt(Graphics2D g2d, Process process, int width,
int height, int padding, int chartHeight, int y, float scale) {
ArrayList<Integer> executionOrder = process.ganttData;
ArrayList<Integer> executionTimes = process.ganttTimes;
if (executionOrder == null || executionTimes == null
|| executionOrder.size() == 0
|| executionTimes.size() != executionOrder.size() + 1) {
return;
}
for (int i = 0; i < executionOrder.size(); i++) {
int processId = executionOrder.get(i);
int startTime = executionTimes.get(i);
int endTime = executionTimes.get(i + 1);
int duration = endTime - startTime;
// Calculate position and width
int x = padding + (int) (startTime * scale);
int blockWidth = Math.max(1, (int) (duration * scale));
// Draw process block
Color processColor = processColors[processId
% processColors.length];
g2d.setColor(processColor);
g2d.fillRect(x, y, blockWidth, chartHeight);
g2d.setColor(Color.BLACK);
g2d.drawRect(x, y, blockWidth, chartHeight);
// Draw process label
g2d.setColor(Color.BLACK);
g2d.setFont(new Font("Arial", Font.BOLD, 12));
String label = "P" + processId;
int labelWidth = g2d.getFontMetrics().stringWidth(label);
// Center the label within the block
if (labelWidth < blockWidth - 4) {
g2d.drawString(label, x + (blockWidth - labelWidth) / 2,
y + chartHeight / 2 + 5);
}
// Draw time at block boundaries
g2d.setFont(new Font("Arial", Font.PLAIN, 10));
String time = Integer.toString(startTime);
labelWidth = g2d.getFontMetrics().stringWidth(time);
g2d.drawString(time, x - labelWidth / 2, y - 2);
}
// Draw final time
if (!executionTimes.isEmpty()) {
int finalTime = executionTimes.get(executionTimes.size() - 1);
int x = padding + (int) (finalTime * scale);
g2d.setFont(new Font("Arial", Font.PLAIN, 10));
String time = Integer.toString(finalTime);
int labelWidth = g2d.getFontMetrics().stringWidth(time);
g2d.drawString(time, x - labelWidth / 2, y - 2);
}
}
private void setupKeyboardShortcuts() {
// Add process with Enter key in process fields
ActionMap actionMap = getRootPane().getActionMap();
InputMap inputMap = getRootPane()
.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
String addProcessKey = "addProcess";
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
addProcessKey);
actionMap.put(addProcessKey, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (processIdField.hasFocus() || burstTimeField.hasFocus()
|| priorityField.hasFocus()
|| arrivalTimeField.hasFocus()) {
addButton.doClick();
}
}
});
// Calculate with Ctrl+Enter
String calculateKey = "calculate";
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,
KeyEvent.CTRL_DOWN_MASK), calculateKey);
actionMap.put(calculateKey, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
calculateButton.doClick();
}
});
// Clear with Escape
String clearKey = "clear";
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), clearKey);
actionMap.put(clearKey, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
clearButton.doClick();
}
});
}
public static void main(String[] args) {
try {
// Set System look and feel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(() -> {
new SchedulingGUI().setVisible(true);
});
}
}