forked from Salmaazoz22/parallel-processing-java-fcai
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPiDashboard.java
More file actions
715 lines (576 loc) · 25.4 KB
/
PiDashboard.java
File metadata and controls
715 lines (576 loc) · 25.4 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
714
715
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Arc2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
@SuppressWarnings("ALL")
public class PiDashboard extends JFrame {
// --- Components ---
private JTextField pointsField;
private JSpinner threadSpinner;
private JSpinner trialsSpinner;
// Buttons
private JButton startButton;
private JButton batchButton;
private JButton compareSeqButton;
private JButton benchmarkThreadsButton;
private JButton resetButton;
private JProgressBar progressBar;
private JLabel piLabel;
private JLabel errorLabel;
private JLabel timeLabel;
private final CanvasPanel canvasPanel;
private final ConvergenceGraphPanel graphPanel;
private final PieChartPanel pieChartPanel;
// --- Simulation State ---
private volatile boolean isRunning = false;
private ExecutorService executor;
// --- Thread Stats for Pie Chart ---
private AtomicLong[] threadHitsCounters;
public PiDashboard() {
super("Monte Carlo Pi Simulator - Project 3");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1100, 900);
setLayout(new BorderLayout(10, 10));
// 1. West: Control Panel
JPanel controlPanel = createControlPanel();
add(controlPanel, BorderLayout.WEST);
// 2. Center: Split Pane (Top: Dots, Bottom: Graphs)
canvasPanel = new CanvasPanel();
// Create Tabs for Graphs
graphPanel = new ConvergenceGraphPanel();
pieChartPanel = new PieChartPanel();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Convergence Graph", graphPanel);
tabbedPane.addTab("Thread Load (Pie)", pieChartPanel);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, canvasPanel, tabbedPane);
splitPane.setResizeWeight(0.65);
splitPane.setDividerLocation(550);
add(splitPane, BorderLayout.CENTER);
// Center on screen
setLocationRelativeTo(null);
}
private JPanel createControlPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
panel.setPreferredSize(new Dimension(280, 0));
panel.setBackground(new Color(240, 240, 240));
// -- Inputs --
panel.add(createHeader("Configuration"));
panel.add(new JLabel("Total Points:"));
pointsField = new JTextField("100000");
pointsField.setMaximumSize(new Dimension(Integer.MAX_VALUE, 30));
panel.add(pointsField);
panel.add(Box.createVerticalStrut(10));
panel.add(new JLabel("Threads:"));
threadSpinner = new JSpinner(new SpinnerNumberModel(4, 1, 32, 1));
threadSpinner.setMaximumSize(new Dimension(Integer.MAX_VALUE, 30));
panel.add(threadSpinner);
panel.add(Box.createVerticalStrut(10));
panel.add(new JLabel("Batch Trials:"));
trialsSpinner = new JSpinner(new SpinnerNumberModel(10, 1, 100, 1));
trialsSpinner.setMaximumSize(new Dimension(Integer.MAX_VALUE, 30));
panel.add(trialsSpinner);
panel.add(Box.createVerticalStrut(20));
// -- Buttons --
startButton = new JButton("Run Visual (Single)");
startButton.setAlignmentX(Component.CENTER_ALIGNMENT);
startButton.setFont(new Font("SansSerif", Font.BOLD, 12));
startButton.addActionListener(_ -> startVisualSimulation());
panel.add(startButton);
panel.add(Box.createVerticalStrut(10));
batchButton = new JButton("Run Batch (Fast)");
batchButton.setAlignmentX(Component.CENTER_ALIGNMENT);
batchButton.setFont(new Font("SansSerif", Font.BOLD, 12));
batchButton.setForeground(new Color(0, 100, 0));
batchButton.addActionListener(_ -> startBatchSimulation());
panel.add(batchButton);
panel.add(Box.createVerticalStrut(10));
compareSeqButton = new JButton("Compare (Seq vs Par)");
compareSeqButton.setAlignmentX(Component.CENTER_ALIGNMENT);
compareSeqButton.setForeground(new Color(0, 0, 150));
compareSeqButton.addActionListener(_ -> startComparisonBenchmark());
panel.add(compareSeqButton);
panel.add(Box.createVerticalStrut(5));
benchmarkThreadsButton = new JButton("Benchmark Threads");
benchmarkThreadsButton.setAlignmentX(Component.CENTER_ALIGNMENT);
benchmarkThreadsButton.setForeground(new Color(100, 0, 100));
benchmarkThreadsButton.addActionListener(_ -> startThreadScalabilityBenchmark());
panel.add(benchmarkThreadsButton);
panel.add(Box.createVerticalStrut(10));
resetButton = new JButton("Reset Board");
resetButton.setAlignmentX(Component.CENTER_ALIGNMENT);
resetButton.addActionListener(_ -> resetSimulation());
panel.add(resetButton);
panel.add(Box.createVerticalStrut(20));
panel.add(new JSeparator());
panel.add(Box.createVerticalStrut(20));
// -- Stats --
panel.add(createHeader("Results"));
piLabel = createStatLabel("Pi: Waiting...");
panel.add(piLabel);
errorLabel = createStatLabel("Err: --");
panel.add(errorLabel);
timeLabel = createStatLabel("Time: 0 ms");
panel.add(timeLabel);
panel.add(Box.createVerticalGlue());
// -- Progress --
progressBar = new JProgressBar(0, 100);
progressBar.setStringPainted(true);
panel.add(progressBar);
return panel;
}
private JLabel createHeader(String text) {
JLabel label = new JLabel(text);
label.setFont(new Font("SansSerif", Font.BOLD, 18));
label.setAlignmentX(Component.LEFT_ALIGNMENT);
return label;
}
private JLabel createStatLabel(String text) {
JLabel label = new JLabel(text);
label.setFont(new Font("Monospaced", Font.BOLD, 14));
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
return label;
}
// --- MODE 1: VISUAL SIMULATION ---
private void startVisualSimulation() {
if (isRunning) return;
long totalPoints = parsePoints();
if (totalPoints == -1) return;
int threads = (Integer) threadSpinner.getValue();
setupUIForRun();
graphPanel.reset();
// Reset Pie Chart Stats
threadHitsCounters = new AtomicLong[threads];
for (int i = 0; i < threads; i++) threadHitsCounters[i] = new AtomicLong(0);
pieChartPanel.setThreadData(threadHitsCounters);
new Thread(() -> runVisualLogic(totalPoints, threads)).start();
}
private void runVisualLogic(long totalPoints, int numThreads) {
executor = Executors.newFixedThreadPool(numThreads);
AtomicLong totalHits = new AtomicLong(0);
AtomicLong processed = new AtomicLong(0);
long startTime = System.currentTimeMillis();
long pointsPerThread = totalPoints / numThreads;
long remainder = totalPoints % numThreads;
for (int i = 0; i < numThreads; i++) {
final int threadId = i;
long actualPoints = (i == numThreads - 1) ? pointsPerThread + remainder : pointsPerThread;
executor.submit(() -> {
ThreadLocalRandom random = ThreadLocalRandom.current();
AtomicLong myCounter = threadHitsCounters[threadId];
for (long j = 0; j < actualPoints; j++) {
if (!isRunning) break;
double x = random.nextDouble() * 2 - 1;
double y = random.nextDouble() * 2 - 1;
boolean hit = (x * x + y * y) <= 1.0;
if (hit) {
totalHits.incrementAndGet();
myCounter.incrementAndGet();
}
processed.incrementAndGet();
if (totalPoints < 500_000 || j % 100 == 0) {
canvasPanel.drawPoint(x, y, hit);
}
}
});
}
Timer timer = new Timer(50, e -> {
long p = processed.get();
long h = totalHits.get();
long now = System.currentTimeMillis();
if (p > 0) {
double currentPi = 4.0 * h / p;
graphPanel.addValue(currentPi);
pieChartPanel.repaint();
updateLabelsPure(currentPi, now - startTime, false);
}
if (p >= totalPoints || !isRunning) {
((Timer)e.getSource()).stop();
finishRun();
}
});
timer.start();
executor.shutdown();
}
// --- MODE 2: BATCH SIMULATION ---
private void startBatchSimulation() {
if (isRunning) return;
long totalPoints = parsePoints();
if (totalPoints == -1) return;
int threads = (Integer) threadSpinner.getValue();
int trials = (Integer) trialsSpinner.getValue();
setupUIForRun();
canvasPanel.clear();
graphPanel.reset();
piLabel.setText("Running Batch...");
new Thread(() -> {
double totalPi = 0;
long totalTime = 0;
for (int i = 0; i < trials; i++) {
if (!isRunning) break;
final int currentTrial = i + 1;
long start = System.currentTimeMillis();
double result = computePiParallel(totalPoints, threads);
long time = System.currentTimeMillis() - start;
totalPi += result;
totalTime += time;
double currentAvgPi = totalPi / currentTrial;
SwingUtilities.invokeLater(() -> {
progressBar.setValue((currentTrial * 100) / trials);
piLabel.setText("Trial " + currentTrial + "/" + trials);
graphPanel.addValue(currentAvgPi);
});
}
double avgPi = totalPi / trials;
double avgTime = (double) totalTime / trials;
SwingUtilities.invokeLater(() -> {
updateLabelsPure(avgPi, avgTime, true);
finishRun();
});
}).start();
}
// --- MODE 3: COMPARISON (Seq vs Par) ---
private void startComparisonBenchmark() {
if (isRunning) return;
long totalPoints = parsePoints();
if (totalPoints == -1) return;
int threads = (Integer) threadSpinner.getValue();
setupUIForRun();
canvasPanel.clear();
graphPanel.reset();
new Thread(() -> {
// 1. Sequential
SwingUtilities.invokeLater(() -> {
progressBar.setValue(10);
piLabel.setText("Running Sequential...");
});
PiEstimator seqEstimator = new SequentialPiEstimator();
SimulationConfig seqConfig = new SimulationConfig(totalPoints, 1, 1);
long startSeq = System.currentTimeMillis();
double seqPi = seqEstimator.estimatePi(seqConfig);
long timeSeq = System.currentTimeMillis() - startSeq;
double seqError = Math.abs(seqPi - Math.PI);
// 2. Parallel
SwingUtilities.invokeLater(() -> {
progressBar.setValue(50);
piLabel.setText("Running Parallel...");
graphPanel.addValue(seqPi);
});
PiEstimator parEstimator = new ParallelPiEstimator();
SimulationConfig parConfig = new SimulationConfig(totalPoints, 100, threads);
long startPar = System.currentTimeMillis();
double parPi = parEstimator.estimatePi(parConfig);
long timePar = System.currentTimeMillis() - startPar;
double parError = Math.abs(parPi - Math.PI);
double speedup = (double) timeSeq / Math.max(timePar, 1);
SwingUtilities.invokeLater(() -> {
progressBar.setValue(100);
finishRun();
// Detailed Popup
String message = String.format("<html><body><h2>Sequential vs Parallel</h2>" +
"<b>Points:</b> %,d | <b>Threads:</b> %d<hr>" +
"<table border='1' cellpadding='5'>" +
"<tr><th>Type</th><th>Time (ms)</th><th>Pi Est.</th><th>Error</th></tr>" +
"<tr><td><b>Sequential</b></td><td>%d</td><td>%.6f</td><td>%.6f</td></tr>" +
"<tr><td><b>Parallel</b></td><td>%d</td><td>%.6f</td><td>%.6f</td></tr>" +
"</table>" +
"<br><h3 style='color:blue'>Speedup: %.2fx</h3></body></html>",
totalPoints, threads, timeSeq, seqPi, seqError, timePar, parPi, parError, speedup);
JOptionPane.showMessageDialog(this, message, "Comparison Result", JOptionPane.INFORMATION_MESSAGE);
});
}).start();
}
// --- MODE 4: THREAD SCALABILITY BENCHMARK ---
private void startThreadScalabilityBenchmark() {
if (isRunning) return;
long totalPoints = parsePoints();
if (totalPoints == -1) return;
setupUIForRun();
canvasPanel.clear();
graphPanel.reset();
int[] threadCounts = {1, 2, 4, 8, 16};
StringBuilder resultHtml = new StringBuilder("<html><body><h2>Thread Scalability</h2>" +
"<table border='1' cellpadding='5'><tr><th>Threads</th><th>Time (ms)</th><th>Speedup</th><th>Pi Est.</th><th>Error</th></tr>");
new Thread(() -> {
PiEstimator estimator = new ParallelPiEstimator();
long baseTime = 0;
for (int i = 0; i < threadCounts.length; i++) {
int t = threadCounts[i];
final int progress = i;
SwingUtilities.invokeLater(() -> {
piLabel.setText("Testing " + t + " threads...");
progressBar.setValue((progress * 100) / threadCounts.length);
});
SimulationConfig config = new SimulationConfig(totalPoints, 100, t);
long start = System.currentTimeMillis();
double val = estimator.estimatePi(config);
long time = System.currentTimeMillis() - start;
double error = Math.abs(val - Math.PI);
if (i == 0) baseTime = time;
double speedup = (double) baseTime / Math.max(time, 1);
resultHtml.append(String.format("<tr><td>%d</td><td>%d</td><td>%.2fx</td><td>%.6f</td><td>%.6f</td></tr>",
t, time, speedup, val, error));
}
resultHtml.append("</table></body></html>");
SwingUtilities.invokeLater(() -> {
progressBar.setValue(100);
finishRun();
piLabel.setText("Benchmark Done");
JOptionPane.showMessageDialog(this, resultHtml.toString(), "Scalability Results", JOptionPane.PLAIN_MESSAGE);
});
}).start();
}
// --- Core Logic ---
private double computePiParallel(long totalPoints, int numThreads) {
ExecutorService batchExecutor = Executors.newFixedThreadPool(numThreads);
List<Future<Long>> results = new ArrayList<>();
long pointsPerThread = totalPoints / numThreads;
long remainder = totalPoints % numThreads;
for (int i = 0; i < numThreads; i++) {
long actualPoints = (i == numThreads - 1) ? pointsPerThread + remainder : pointsPerThread;
results.add(batchExecutor.submit(() -> {
long hits = 0;
ThreadLocalRandom random = ThreadLocalRandom.current();
for (long j = 0; j < actualPoints; j++) {
double x = random.nextDouble() * 2 - 1;
double y = random.nextDouble() * 2 - 1;
if ((x * x + y * y) <= 1.0) hits++;
}
return hits;
}));
}
long totalHits = 0;
try {
for (Future<Long> f : results) totalHits += f.get();
} catch (Exception e) { e.printStackTrace(); }
batchExecutor.shutdown();
return 4.0 * totalHits / totalPoints;
}
// --- Helpers ---
private long parsePoints() {
try {
return Long.parseLong(pointsField.getText());
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "Invalid number of points!");
return -1;
}
}
private void setupUIForRun() {
isRunning = true;
startButton.setEnabled(false);
batchButton.setEnabled(false);
compareSeqButton.setEnabled(false);
benchmarkThreadsButton.setEnabled(false);
resetButton.setEnabled(false);
pointsField.setEnabled(false);
trialsSpinner.setEnabled(false);
}
private void finishRun() {
isRunning = false;
startButton.setEnabled(true);
batchButton.setEnabled(true);
compareSeqButton.setEnabled(true);
benchmarkThreadsButton.setEnabled(true);
resetButton.setEnabled(true);
pointsField.setEnabled(true);
trialsSpinner.setEnabled(true);
}
private void resetSimulation() {
isRunning = false;
if (executor != null) executor.shutdownNow();
canvasPanel.clear();
graphPanel.reset();
progressBar.setValue(0);
piLabel.setText("Pi: Waiting...");
errorLabel.setText("Err: --");
timeLabel.setText("Time: 0 ms");
}
private void updateLabelsPure(double pi, double timeMs, boolean isAvg) {
double error = Math.abs(pi - Math.PI);
String prefix = isAvg ? "Avg " : "";
piLabel.setText(String.format("%sPi: %.6f", prefix, pi));
errorLabel.setText(String.format("%sErr: %.6f", prefix, error));
timeLabel.setText(String.format("%sTime: %.0f ms", prefix, timeMs));
}
// --- Inner Class: Dots Canvas ---
private static class CanvasPanel extends JPanel {
private final BufferedImage image;
private final int SIZE = 600;
public CanvasPanel() {
setBackground(Color.DARK_GRAY);
image = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_ARGB);
clear();
}
public void clear() {
Graphics2D g2d = image.createGraphics();
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, SIZE, SIZE);
g2d.setColor(Color.WHITE);
g2d.drawOval(0, 0, SIZE - 1, SIZE - 1);
g2d.dispose();
repaint();
}
public void drawPoint(double x, double y, boolean hit) {
int px = (int) ((x + 1) / 2.0 * (SIZE - 1));
int py = (int) ((1.0 - y) / 2.0 * (SIZE - 1));
int color = hit ? 0xFF00FF00 : 0xFFFF0000;
if (px >= 0 && px < SIZE && py >= 0 && py < SIZE) {
image.setRGB(px, py, color);
image.setRGB(px + 1, py, color);
image.setRGB(px, py + 1, color);
image.setRGB(px + 1, py + 1, color);
}
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = (getWidth() - SIZE) / 2;
int y = (getHeight() - SIZE) / 2;
g.drawImage(image, x, y, null);
}
}
// --- Inner Class: Convergence Graph ---
private static class ConvergenceGraphPanel extends JPanel {
private final List<Double> history = Collections.synchronizedList(new ArrayList<>());
private final int MAX_HISTORY = 500;
public ConvergenceGraphPanel() {
setBackground(new Color(30, 30, 30));
setPreferredSize(new Dimension(0, 200));
}
public void addValue(double val) {
history.add(val);
if (history.size() > MAX_HISTORY) {
history.remove(0);
}
repaint();
}
public void reset() {
history.clear();
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
int h = getHeight();
// Legend
g2.setFont(new Font("SansSerif", Font.PLAIN, 12));
g2.setColor(new Color(0, 200, 255));
g2.drawString("— Current Est. (Blue)", 10, 20);
double minVal = Math.PI;
double maxVal = Math.PI;
synchronized (history) {
if (history.isEmpty()) {
minVal = Math.PI - 0.02;
maxVal = Math.PI + 0.02;
} else {
for (Double val : history) {
if (val < minVal) minVal = val;
if (val > maxVal) maxVal = val;
}
}
}
double spread = maxVal - minVal;
if (spread < 0.000001) spread = 0.000001;
double padding = spread * 0.1;
double yMin = minVal - padding;
double yMax = maxVal + padding;
g2.setColor(new Color(255, 50, 50));
int yTarget = (int) (h - ((Math.PI - yMin) / (yMax - yMin)) * h);
if (yTarget >= -10 && yTarget <= h + 10) {
g2.drawLine(0, yTarget, w, yTarget);
g2.drawString(String.format("Target (%.5f)", Math.PI), 150, 20);
}
if (history.isEmpty()) return;
g2.setColor(new Color(0, 200, 255));
g2.setStroke(new BasicStroke(2));
if (history.size() == 1) {
double val = history.get(0);
int y = (int) (h - ((val - yMin) / (yMax - yMin)) * h);
g2.drawLine(0, y, w, y);
return;
}
synchronized (history) {
double xScale = (double) w / (Math.max(history.size(), 1) - 1);
for (int i = 1; i < history.size(); i++) {
double val1 = history.get(i - 1);
double val2 = history.get(i);
int x1 = (int) ((i - 1) * xScale);
int x2 = (int) (i * xScale);
int y1 = (int) (h - ((val1 - yMin) / (yMax - yMin)) * h);
int y2 = (int) (h - ((val2 - yMin) / (yMax - yMin)) * h);
y1 = Math.max(-50, Math.min(h + 50, y1));
y2 = Math.max(-50, Math.min(h + 50, y2));
g2.drawLine(x1, y1, x2, y2);
}
}
}
}
// --- Inner Class: Pie Chart Panel ---
private static class PieChartPanel extends JPanel {
private AtomicLong[] threadData;
private final Color[] colors = {
new Color(220, 50, 50), new Color(50, 220, 50), new Color(50, 50, 220),
new Color(220, 220, 50), new Color(50, 220, 220), new Color(220, 50, 220),
new Color(100, 100, 100), new Color(255, 140, 0), new Color(140, 0, 255),
new Color(0, 100, 0), new Color(0, 0, 100), new Color(100, 0, 0)
};
public PieChartPanel() {
setBackground(new Color(40, 40, 40));
setPreferredSize(new Dimension(0, 200));
}
public void setThreadData(AtomicLong[] data) {
this.threadData = data;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (threadData == null || threadData.length == 0) return;
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
long totalHits = 0;
for (AtomicLong count : threadData) totalHits += count.get();
if (totalHits == 0) return;
int w = getWidth();
int h = getHeight();
int diameter = Math.min(w, h) - 40;
int x = (w - diameter) / 2;
int y = (h - diameter) / 2;
double startAngle = 0;
for (int i = 0; i < threadData.length; i++) {
double amount = threadData[i].get();
double angle = (amount / totalHits) * 360.0;
g2.setColor(colors[i % colors.length]);
g2.fill(new Arc2D.Double(x, y, diameter, diameter, startAngle, angle, Arc2D.PIE));
startAngle += angle;
}
// Legend
int lx = 10;
int ly = 20;
for (int i = 0; i < threadData.length; i++) {
g2.setColor(colors[i % colors.length]);
g2.fillRect(lx, ly, 10, 10);
g2.setColor(Color.WHITE);
g2.drawString("Thread " + (i+1) + ": " + threadData[i].get(), lx + 15, ly + 10);
ly += 20;
if (ly > h - 10) { ly = 20; lx += 120; }
}
}
}
static void main(String[] args) {
try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }
catch (Exception ignored) {}
SwingUtilities.invokeLater(() -> new PiDashboard().setVisible(true));
}
}