-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicsLearningGUI.java
More file actions
1365 lines (1135 loc) · 53.6 KB
/
Copy pathBasicsLearningGUI.java
File metadata and controls
1365 lines (1135 loc) · 53.6 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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package basics;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;
/**
* BasicsLearningGUI - Interactive Learning Platform for Java Basics
*
* EDUCATIONAL PURPOSE:
* This GUI provides an interactive environment to learn and experiment with:
* - Variables and Data Types
* - Control Structures (if/else, loops)
* - Methods and Parameters
* - Arrays and Basic Collections
* - String Manipulation
* - Basic I/O Operations
*
* LEARNING APPROACH:
* - Visual demonstrations of concepts
* - Interactive code execution
* - Real-time feedback
* - Step-by-step explanations
* - Hands-on experimentation
*
* GUI COMPONENTS:
* - Code demonstration panels
* - Interactive input areas
* - Output displays
* - Progress tracking
* - Educational tooltips
*
* @author Java Examples Project
* @version 1.0
*/
public class BasicsLearningGUI extends JFrame {
private JTabbedPane tabbedPane;
private JTextArea outputArea;
private JTextField inputField;
private JLabel statusLabel;
private int completedLessons = 0;
private final int totalLessons = 6;
public BasicsLearningGUI() {
initializeGUI();
setupEventHandlers();
}
/**
* Initialize the main GUI components
*/
private void initializeGUI() {
setTitle("🎓 Java Basics Learning Platform");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Create main tabbed pane
tabbedPane = new JTabbedPane();
// Add lesson tabs
tabbedPane.addTab("📚 Variables", createVariablesPanel());
tabbedPane.addTab("🔀 Control Flow", createControlFlowPanel());
tabbedPane.addTab("⚙️ Methods", createMethodsPanel());
tabbedPane.addTab("📊 Arrays", createArraysPanel());
tabbedPane.addTab("📝 Strings", createStringsPanel());
tabbedPane.addTab("💾 Collections", createCollectionsPanel());
add(tabbedPane, BorderLayout.CENTER);
// Create output panel
JPanel outputPanel = createOutputPanel();
add(outputPanel, BorderLayout.SOUTH);
// Create status panel
JPanel statusPanel = createStatusPanel();
add(statusPanel, BorderLayout.NORTH);
// Window setup
setSize(1000, 700);
setLocationRelativeTo(null);
setResizable(true);
// Initial message
appendOutput("🎉 Welcome to Java Basics Learning Platform!");
appendOutput("👆 Click on tabs above to start learning different concepts.");
appendOutput("💡 Each tab contains interactive examples and exercises.\n");
}
/**
* Create Variables and Data Types panel
*/
private JPanel createVariablesPanel() {
JPanel panel = new JPanel(new BorderLayout());
// Theory panel
JPanel theoryPanel = new JPanel(new GridLayout(2, 1));
theoryPanel.setBorder(new TitledBorder("📖 Theory: Variables and Data Types"));
JTextArea theoryText = new JTextArea(
"VARIABLES IN JAVA:\n" +
"• Variables are containers for storing data values\n" +
"• Java is strongly typed - each variable has a specific type\n" +
"• Primitive types: int, double, boolean, char, byte, short, long, float\n" +
"• Reference types: String, Arrays, Objects\n\n" +
"VARIABLE DECLARATION:\n" +
"• Syntax: dataType variableName = value;\n" +
"• Example: int age = 25;\n" +
"• Variables must be declared before use\n" +
"• Good naming: use camelCase, descriptive names"
);
theoryText.setEditable(false);
theoryText.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
theoryText.setBackground(new Color(248, 248, 255));
theoryPanel.add(new JScrollPane(theoryText));
// Interactive panel
JPanel interactivePanel = new JPanel(new GridBagLayout());
interactivePanel.setBorder(new TitledBorder("🧪 Interactive Demo"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
// Variable creation demo
gbc.gridx = 0; gbc.gridy = 0;
interactivePanel.add(new JLabel("Enter your name:"), gbc);
JTextField nameField = new JTextField(15);
gbc.gridx = 1;
interactivePanel.add(nameField, gbc);
gbc.gridx = 0; gbc.gridy = 1;
interactivePanel.add(new JLabel("Enter your age:"), gbc);
JTextField ageField = new JTextField(15);
gbc.gridx = 1;
interactivePanel.add(ageField, gbc);
gbc.gridx = 0; gbc.gridy = 2;
interactivePanel.add(new JLabel("Enter height (meters):"), gbc);
JTextField heightField = new JTextField(15);
gbc.gridx = 1;
interactivePanel.add(heightField, gbc);
JButton demonstrateBtn = new JButton("🔍 Demonstrate Variables");
gbc.gridx = 0; gbc.gridy = 3; gbc.gridwidth = 2;
interactivePanel.add(demonstrateBtn, gbc);
// Event handler for demonstration
demonstrateBtn.addActionListener(e -> {
try {
String name = nameField.getText().trim();
String ageText = ageField.getText().trim();
String heightText = heightField.getText().trim();
if (name.isEmpty() || ageText.isEmpty() || heightText.isEmpty()) {
appendOutput("❌ Please fill in all fields!");
return;
}
int age = Integer.parseInt(ageText);
double height = Double.parseDouble(heightText);
appendOutput("=== VARIABLE DEMONSTRATION ===");
appendOutput("// Creating variables with different data types:");
appendOutput("String name = \"" + name + "\"; // String (reference type)");
appendOutput("int age = " + age + "; // int (primitive type)");
appendOutput("double height = " + height + "; // double (primitive type)");
appendOutput("boolean isAdult = " + (age >= 18) + "; // boolean (calculated)");
appendOutput("");
appendOutput("📊 Variable Analysis:");
appendOutput("• Name type: " + name.getClass().getSimpleName());
appendOutput("• Age type: int (32-bit integer)");
appendOutput("• Height type: double (64-bit floating point)");
appendOutput("• Is Adult: boolean (true/false)");
appendOutput("• Memory usage: ~" + (name.length() * 2 + 4 + 8 + 1) + " bytes");
appendOutput("");
completedLessons = Math.max(completedLessons, 1);
updateProgress();
} catch (NumberFormatException ex) {
appendOutput("❌ Error: Please enter valid numbers for age and height!");
}
});
panel.add(theoryPanel, BorderLayout.NORTH);
panel.add(interactivePanel, BorderLayout.CENTER);
return panel;
}
/**
* Create Control Flow panel
*/
private JPanel createControlFlowPanel() {
JPanel panel = new JPanel(new BorderLayout());
// Theory panel
JPanel theoryPanel = new JPanel();
theoryPanel.setBorder(new TitledBorder("📖 Theory: Control Flow Structures"));
JTextArea theoryText = new JTextArea(
"CONTROL FLOW IN JAVA:\n" +
"• Controls the order in which statements are executed\n" +
"• Decision structures: if, else if, else, switch\n" +
"• Loop structures: for, while, do-while, enhanced for\n" +
"• Jump statements: break, continue, return\n\n" +
"IF-ELSE STATEMENTS:\n" +
"• if (condition) { statements }\n" +
"• Used for decision making based on conditions\n" +
"• Can chain with else if for multiple conditions\n\n" +
"LOOPS:\n" +
"• for: when you know iteration count\n" +
"• while: when condition is checked before execution\n" +
"• do-while: when you want at least one execution"
);
theoryText.setEditable(false);
theoryText.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
theoryText.setBackground(new Color(248, 255, 248));
theoryPanel.add(new JScrollPane(theoryText));
// Interactive panel
JPanel interactivePanel = new JPanel(new GridBagLayout());
interactivePanel.setBorder(new TitledBorder("🧪 Interactive Demo"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.gridx = 0; gbc.gridy = 0;
interactivePanel.add(new JLabel("Enter a number (1-100):"), gbc);
JTextField numberField = new JTextField(15);
gbc.gridx = 1;
interactivePanel.add(numberField, gbc);
JButton ifElseBtn = new JButton("🔀 Test If-Else");
gbc.gridx = 0; gbc.gridy = 1;
interactivePanel.add(ifElseBtn, gbc);
JButton loopBtn = new JButton("🔄 Demonstrate Loops");
gbc.gridx = 1;
interactivePanel.add(loopBtn, gbc);
// If-Else demonstration
ifElseBtn.addActionListener(e -> {
try {
int number = Integer.parseInt(numberField.getText().trim());
appendOutput("=== IF-ELSE DEMONSTRATION ===");
appendOutput("Testing number: " + number);
appendOutput("");
appendOutput("// If-else logic:");
appendOutput("if (number > 50) {");
if (number > 50) {
appendOutput(" System.out.println(\"Large number!\");");
appendOutput("} // This block executed ✅");
} else {
appendOutput(" System.out.println(\"Large number!\");");
appendOutput("} // This block skipped ❌");
}
appendOutput("else if (number > 25) {");
if (number <= 50 && number > 25) {
appendOutput(" System.out.println(\"Medium number!\");");
appendOutput("} // This block executed ✅");
} else {
appendOutput(" System.out.println(\"Medium number!\");");
appendOutput("} // This block skipped ❌");
}
appendOutput("else {");
if (number <= 25) {
appendOutput(" System.out.println(\"Small number!\");");
appendOutput("} // This block executed ✅");
} else {
appendOutput(" System.out.println(\"Small number!\");");
appendOutput("} // This block skipped ❌");
}
appendOutput("");
appendOutput("🎯 Result: " + (number > 50 ? "Large" : number > 25 ? "Medium" : "Small") + " number!");
appendOutput("");
completedLessons = Math.max(completedLessons, 2);
updateProgress();
} catch (NumberFormatException ex) {
appendOutput("❌ Error: Please enter a valid number!");
}
});
// Loop demonstration
loopBtn.addActionListener(e -> {
try {
int number = Integer.parseInt(numberField.getText().trim());
if (number < 1 || number > 10) {
appendOutput("❌ Please enter a number between 1 and 10 for loop demo!");
return;
}
appendOutput("=== LOOP DEMONSTRATION ===");
appendOutput("Creating multiplication table for: " + number);
appendOutput("");
appendOutput("// For loop:");
appendOutput("for (int i = 1; i <= 10; i++) {");
appendOutput(" System.out.println(\"" + number + " x \" + i + \" = \" + (" + number + " * i));");
appendOutput("}");
appendOutput("");
appendOutput("📊 Output:");
for (int i = 1; i <= 10; i++) {
appendOutput(number + " x " + i + " = " + (number * i));
}
appendOutput("");
completedLessons = Math.max(completedLessons, 2);
updateProgress();
} catch (NumberFormatException ex) {
appendOutput("❌ Error: Please enter a valid number!");
}
});
panel.add(theoryPanel, BorderLayout.NORTH);
panel.add(interactivePanel, BorderLayout.CENTER);
return panel;
}
/**
* Create Methods panel
*/
private JPanel createMethodsPanel() {
JPanel panel = new JPanel(new BorderLayout());
// Theory panel
JPanel theoryPanel = new JPanel();
theoryPanel.setBorder(new TitledBorder("📖 Theory: Methods"));
JTextArea theoryText = new JTextArea(
"METHODS IN JAVA:\n" +
"• Methods are blocks of code that perform specific tasks\n" +
"• Enable code reuse and organization\n" +
"• Can accept parameters and return values\n" +
"• Method signature: access modifier + return type + name + parameters\n\n" +
"METHOD SYNTAX:\n" +
"• public static returnType methodName(parameters) { body }\n" +
"• public: access modifier (who can call it)\n" +
"• static: belongs to class, not instance\n" +
"• returnType: what the method gives back (void for nothing)\n" +
"• parameters: input values the method needs\n\n" +
"BENEFITS:\n" +
"• Code reusability • Better organization • Easier testing\n" +
"• Modularity • Easier maintenance"
);
theoryText.setEditable(false);
theoryText.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
theoryText.setBackground(new Color(255, 248, 248));
theoryPanel.add(new JScrollPane(theoryText));
// Interactive panel
JPanel interactivePanel = new JPanel(new GridBagLayout());
interactivePanel.setBorder(new TitledBorder("🧪 Interactive Demo"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.gridx = 0; gbc.gridy = 0;
interactivePanel.add(new JLabel("First Number:"), gbc);
JTextField num1Field = new JTextField(10);
gbc.gridx = 1;
interactivePanel.add(num1Field, gbc);
gbc.gridx = 0; gbc.gridy = 1;
interactivePanel.add(new JLabel("Second Number:"), gbc);
JTextField num2Field = new JTextField(10);
gbc.gridx = 1;
interactivePanel.add(num2Field, gbc);
JButton addBtn = new JButton("➕ Add");
gbc.gridx = 0; gbc.gridy = 2;
interactivePanel.add(addBtn, gbc);
JButton multiplyBtn = new JButton("✖️ Multiply");
gbc.gridx = 1;
interactivePanel.add(multiplyBtn, gbc);
JButton powBtn = new JButton("⬆️ Power");
gbc.gridx = 0; gbc.gridy = 3;
interactivePanel.add(powBtn, gbc);
JButton factorialBtn = new JButton("❗ Factorial");
gbc.gridx = 1;
interactivePanel.add(factorialBtn, gbc);
// Method demonstrations
addBtn.addActionListener(e -> demonstrateAddMethod(num1Field, num2Field));
multiplyBtn.addActionListener(e -> demonstrateMultiplyMethod(num1Field, num2Field));
powBtn.addActionListener(e -> demonstratePowerMethod(num1Field, num2Field));
factorialBtn.addActionListener(e -> demonstrateFactorialMethod(num1Field));
panel.add(theoryPanel, BorderLayout.NORTH);
panel.add(interactivePanel, BorderLayout.CENTER);
return panel;
}
/**
* Demonstrate addition method
*/
private void demonstrateAddMethod(JTextField num1Field, JTextField num2Field) {
try {
double num1 = Double.parseDouble(num1Field.getText().trim());
double num2 = Double.parseDouble(num2Field.getText().trim());
appendOutput("=== ADD METHOD DEMONSTRATION ===");
appendOutput("// Method definition:");
appendOutput("public static double add(double a, double b) {");
appendOutput(" double result = a + b;");
appendOutput(" return result;");
appendOutput("}");
appendOutput("");
appendOutput("// Method call:");
appendOutput("double result = add(" + num1 + ", " + num2 + ");");
appendOutput("");
appendOutput("🔢 Step-by-step execution:");
appendOutput("1. Method called with parameters: a=" + num1 + ", b=" + num2);
appendOutput("2. Calculate: " + num1 + " + " + num2 + " = " + (num1 + num2));
appendOutput("3. Return result: " + (num1 + num2));
appendOutput("");
appendOutput("✅ Final result: " + add(num1, num2));
appendOutput("");
completedLessons = Math.max(completedLessons, 3);
updateProgress();
} catch (NumberFormatException ex) {
appendOutput("❌ Error: Please enter valid numbers!");
}
}
/**
* Demonstrate factorial method
*/
private void demonstrateFactorialMethod(JTextField numField) {
try {
int num = Integer.parseInt(numField.getText().trim());
if (num < 0 || num > 10) {
appendOutput("❌ Please enter a number between 0 and 10!");
return;
}
appendOutput("=== FACTORIAL METHOD DEMONSTRATION ===");
appendOutput("// Recursive method definition:");
appendOutput("public static long factorial(int n) {");
appendOutput(" if (n <= 1) {");
appendOutput(" return 1; // Base case");
appendOutput(" }");
appendOutput(" return n * factorial(n - 1); // Recursive call");
appendOutput("}");
appendOutput("");
appendOutput("// Method call:");
appendOutput("long result = factorial(" + num + ");");
appendOutput("");
appendOutput("🔄 Recursive execution trace:");
long result = demonstrateFactorial(num, 1);
appendOutput("");
appendOutput("✅ Final result: " + num + "! = " + result);
appendOutput("");
} catch (NumberFormatException ex) {
appendOutput("❌ Error: Please enter a valid integer!");
}
}
/**
* Helper method for factorial demonstration
*/
private long demonstrateFactorial(int n, int depth) {
String indent = " ".repeat(depth);
if (n <= 1) {
appendOutput(indent + "factorial(" + n + ") = 1 (base case)");
return 1;
}
appendOutput(indent + "factorial(" + n + ") = " + n + " * factorial(" + (n-1) + ")");
long subResult = demonstrateFactorial(n - 1, depth + 1);
long result = n * subResult;
appendOutput(indent + "factorial(" + n + ") = " + n + " * " + subResult + " = " + result);
return result;
}
// Helper methods for demonstrations
private double add(double a, double b) { return a + b; }
private double multiply(double a, double b) { return a * b; }
private double power(double base, double exponent) { return Math.pow(base, exponent); }
private void demonstrateMultiplyMethod(JTextField num1Field, JTextField num2Field) {
try {
double num1 = Double.parseDouble(num1Field.getText().trim());
double num2 = Double.parseDouble(num2Field.getText().trim());
double result = multiply(num1, num2);
appendOutput("=== MULTIPLY METHOD DEMONSTRATION ===");
appendOutput("// Method: public static double multiply(double a, double b)");
appendOutput("Result: " + num1 + " × " + num2 + " = " + result);
appendOutput("");
} catch (NumberFormatException ex) {
appendOutput("❌ Error: Please enter valid numbers!");
}
}
private void demonstratePowerMethod(JTextField num1Field, JTextField num2Field) {
try {
double base = Double.parseDouble(num1Field.getText().trim());
double exponent = Double.parseDouble(num2Field.getText().trim());
double result = power(base, exponent);
appendOutput("=== POWER METHOD DEMONSTRATION ===");
appendOutput("// Method: public static double power(double base, double exponent)");
appendOutput("Result: " + base + "^" + exponent + " = " + result);
appendOutput("");
} catch (NumberFormatException ex) {
appendOutput("❌ Error: Please enter valid numbers!");
}
}
/**
* Create Arrays panel
*/
private JPanel createArraysPanel() {
JPanel panel = new JPanel(new BorderLayout());
// Theory panel
JPanel theoryPanel = new JPanel();
theoryPanel.setBorder(new TitledBorder("📖 Theory: Arrays"));
JTextArea theoryText = new JTextArea(
"ARRAYS IN JAVA:\n" +
"• Arrays store multiple values of the same type\n" +
"• Fixed size once created\n" +
"• Elements accessed by index (0-based)\n" +
"• Declaration: dataType[] arrayName = new dataType[size];\n\n" +
"ARRAY OPERATIONS:\n" +
"• Access: array[index]\n" +
"• Length: array.length\n" +
"• Initialization: {value1, value2, value3}\n" +
"• Iteration: for loops or enhanced for loops\n\n" +
"COMMON USES:\n" +
"• Storing lists of data • Mathematical operations\n" +
"• Lookup tables • Temporary storage"
);
theoryText.setEditable(false);
theoryText.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
theoryText.setBackground(new Color(255, 255, 248));
theoryPanel.add(new JScrollPane(theoryText));
// Interactive panel
JPanel interactivePanel = new JPanel(new GridBagLayout());
interactivePanel.setBorder(new TitledBorder("🧪 Interactive Demo"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.gridx = 0; gbc.gridy = 0;
interactivePanel.add(new JLabel("Enter numbers (comma-separated):"), gbc);
JTextField arrayField = new JTextField(20);
gbc.gridx = 1;
interactivePanel.add(arrayField, gbc);
JButton createBtn = new JButton("📊 Create Array");
gbc.gridx = 0; gbc.gridy = 1;
interactivePanel.add(createBtn, gbc);
JButton analyzeBtn = new JButton("🔍 Analyze Array");
gbc.gridx = 1;
interactivePanel.add(analyzeBtn, gbc);
JButton sortBtn = new JButton("📈 Sort Array");
gbc.gridx = 0; gbc.gridy = 2;
interactivePanel.add(sortBtn, gbc);
JButton searchBtn = new JButton("🔎 Search Array");
gbc.gridx = 1;
interactivePanel.add(searchBtn, gbc);
// Array operations
createBtn.addActionListener(e -> demonstrateArrayCreation(arrayField));
analyzeBtn.addActionListener(e -> demonstrateArrayAnalysis(arrayField));
sortBtn.addActionListener(e -> demonstrateArraySorting(arrayField));
searchBtn.addActionListener(e -> demonstrateArraySearch(arrayField));
panel.add(theoryPanel, BorderLayout.NORTH);
panel.add(interactivePanel, BorderLayout.CENTER);
return panel;
}
private void demonstrateArrayCreation(JTextField arrayField) {
try {
String input = arrayField.getText().trim();
String[] stringNumbers = input.split(",");
int[] numbers = new int[stringNumbers.length];
for (int i = 0; i < stringNumbers.length; i++) {
numbers[i] = Integer.parseInt(stringNumbers[i].trim());
}
appendOutput("=== ARRAY CREATION DEMONSTRATION ===");
appendOutput("// Step 1: Declare array");
appendOutput("int[] numbers = new int[" + numbers.length + "];");
appendOutput("");
appendOutput("// Step 2: Initialize with values");
for (int i = 0; i < numbers.length; i++) {
appendOutput("numbers[" + i + "] = " + numbers[i] + ";");
}
appendOutput("");
appendOutput("// Alternative: Array literal");
appendOutput("int[] numbers = {" + String.join(", ", input.split(",")) + "};");
appendOutput("");
appendOutput("📊 Array created successfully!");
appendOutput("• Length: " + numbers.length);
appendOutput("• Type: int[]");
appendOutput("• Memory: ~" + (numbers.length * 4) + " bytes");
appendOutput("");
completedLessons = Math.max(completedLessons, 4);
updateProgress();
} catch (NumberFormatException ex) {
appendOutput("❌ Error: Please enter valid integers separated by commas!");
}
}
private void demonstrateArrayAnalysis(JTextField arrayField) {
try {
String input = arrayField.getText().trim();
String[] stringNumbers = input.split(",");
int[] numbers = new int[stringNumbers.length];
for (int i = 0; i < stringNumbers.length; i++) {
numbers[i] = Integer.parseInt(stringNumbers[i].trim());
}
appendOutput("=== ARRAY ANALYSIS DEMONSTRATION ===");
appendOutput("// Iterating through array");
appendOutput("for (int i = 0; i < numbers.length; i++) {");
appendOutput(" System.out.println(\"Element \" + i + \": \" + numbers[i]);");
appendOutput("}");
appendOutput("");
appendOutput("📊 Array contents:");
int sum = 0;
int min = numbers[0];
int max = numbers[0];
for (int i = 0; i < numbers.length; i++) {
appendOutput("Element " + i + ": " + numbers[i]);
sum += numbers[i];
if (numbers[i] < min) min = numbers[i];
if (numbers[i] > max) max = numbers[i];
}
appendOutput("");
appendOutput("🔢 Statistics:");
appendOutput("• Sum: " + sum);
appendOutput("• Average: " + (double)sum / numbers.length);
appendOutput("• Minimum: " + min);
appendOutput("• Maximum: " + max);
appendOutput("");
} catch (NumberFormatException ex) {
appendOutput("❌ Error: Please enter valid integers!");
}
}
private void demonstrateArraySorting(JTextField arrayField) {
try {
String input = arrayField.getText().trim();
String[] stringNumbers = input.split(",");
int[] numbers = new int[stringNumbers.length];
for (int i = 0; i < stringNumbers.length; i++) {
numbers[i] = Integer.parseInt(stringNumbers[i].trim());
}
appendOutput("=== ARRAY SORTING DEMONSTRATION ===");
appendOutput("Original array: " + Arrays.toString(numbers));
appendOutput("");
// Bubble sort with steps
int[] sortedArray = numbers.clone();
appendOutput("// Bubble sort algorithm:");
appendOutput("for (int i = 0; i < array.length - 1; i++) {");
appendOutput(" for (int j = 0; j < array.length - i - 1; j++) {");
appendOutput(" if (array[j] > array[j + 1]) {");
appendOutput(" // Swap elements");
appendOutput(" int temp = array[j];");
appendOutput(" array[j] = array[j + 1];");
appendOutput(" array[j + 1] = temp;");
appendOutput(" }");
appendOutput(" }");
appendOutput("}");
appendOutput("");
for (int i = 0; i < sortedArray.length - 1; i++) {
for (int j = 0; j < sortedArray.length - i - 1; j++) {
if (sortedArray[j] > sortedArray[j + 1]) {
int temp = sortedArray[j];
sortedArray[j] = sortedArray[j + 1];
sortedArray[j + 1] = temp;
appendOutput("Swap: " + Arrays.toString(sortedArray));
}
}
}
appendOutput("");
appendOutput("✅ Sorted array: " + Arrays.toString(sortedArray));
appendOutput("");
} catch (NumberFormatException ex) {
appendOutput("❌ Error: Please enter valid integers!");
}
}
private void demonstrateArraySearch(JTextField arrayField) {
try {
String input = arrayField.getText().trim();
String[] stringNumbers = input.split(",");
int[] numbers = new int[stringNumbers.length];
for (int i = 0; i < stringNumbers.length; i++) {
numbers[i] = Integer.parseInt(stringNumbers[i].trim());
}
String searchValue = JOptionPane.showInputDialog(this, "Enter value to search:");
if (searchValue == null) return;
int target = Integer.parseInt(searchValue.trim());
appendOutput("=== ARRAY SEARCH DEMONSTRATION ===");
appendOutput("Searching for: " + target);
appendOutput("In array: " + Arrays.toString(numbers));
appendOutput("");
appendOutput("// Linear search algorithm:");
appendOutput("for (int i = 0; i < array.length; i++) {");
appendOutput(" if (array[i] == target) {");
appendOutput(" return i; // Found at index i");
appendOutput(" }");
appendOutput("}");
appendOutput("return -1; // Not found");
appendOutput("");
appendOutput("🔎 Search steps:");
int foundIndex = -1;
for (int i = 0; i < numbers.length; i++) {
appendOutput("Check index " + i + ": " + numbers[i] + " == " + target + " ? " + (numbers[i] == target));
if (numbers[i] == target) {
foundIndex = i;
break;
}
}
appendOutput("");
if (foundIndex != -1) {
appendOutput("✅ Found at index: " + foundIndex);
} else {
appendOutput("❌ Value not found in array");
}
appendOutput("");
} catch (NumberFormatException ex) {
appendOutput("❌ Error: Please enter valid integers!");
}
}
/**
* Create Strings panel
*/
private JPanel createStringsPanel() {
JPanel panel = new JPanel(new BorderLayout());
// Theory panel
JPanel theoryPanel = new JPanel();
theoryPanel.setBorder(new TitledBorder("📖 Theory: Strings"));
JTextArea theoryText = new JTextArea(
"STRINGS IN JAVA:\n" +
"• Strings are objects that represent text\n" +
"• Immutable - cannot be changed once created\n" +
"• String literal: \"Hello World\"\n" +
"• String object: new String(\"Hello\")\n\n" +
"COMMON STRING METHODS:\n" +
"• length() - get string length\n" +
"• charAt(index) - get character at position\n" +
"• substring(start, end) - extract part of string\n" +
"• toUpperCase(), toLowerCase() - change case\n" +
"• contains(text) - check if contains substring\n" +
"• split(delimiter) - split into array\n\n" +
"STRING CONCATENATION:\n" +
"• Using +: \"Hello\" + \" World\"\n" +
"• Using StringBuilder for efficiency"
);
theoryText.setEditable(false);
theoryText.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
theoryText.setBackground(new Color(248, 255, 255));
theoryPanel.add(new JScrollPane(theoryText));
// Interactive panel
JPanel interactivePanel = new JPanel(new GridBagLayout());
interactivePanel.setBorder(new TitledBorder("🧪 Interactive Demo"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.gridx = 0; gbc.gridy = 0;
interactivePanel.add(new JLabel("Enter text:"), gbc);
JTextField textField = new JTextField(20);
gbc.gridx = 1;
interactivePanel.add(textField, gbc);
JButton analyzeBtn = new JButton("🔍 Analyze String");
gbc.gridx = 0; gbc.gridy = 1;
interactivePanel.add(analyzeBtn, gbc);
JButton manipulateBtn = new JButton("✂️ Manipulate String");
gbc.gridx = 1;
interactivePanel.add(manipulateBtn, gbc);
JButton searchBtn = new JButton("🔎 Search & Replace");
gbc.gridx = 0; gbc.gridy = 2;
interactivePanel.add(searchBtn, gbc);
JButton builderBtn = new JButton("🏗️ StringBuilder Demo");
gbc.gridx = 1;
interactivePanel.add(builderBtn, gbc);
// String operations
analyzeBtn.addActionListener(e -> demonstrateStringAnalysis(textField));
manipulateBtn.addActionListener(e -> demonstrateStringManipulation(textField));
searchBtn.addActionListener(e -> demonstrateStringSearch(textField));
builderBtn.addActionListener(e -> demonstrateStringBuilder(textField));
panel.add(theoryPanel, BorderLayout.NORTH);
panel.add(interactivePanel, BorderLayout.CENTER);
return panel;
}
private void demonstrateStringAnalysis(JTextField textField) {
String text = textField.getText();
if (text.isEmpty()) {
appendOutput("❌ Please enter some text!");
return;
}
appendOutput("=== STRING ANALYSIS DEMONSTRATION ===");
appendOutput("Analyzing text: \"" + text + "\"");
appendOutput("");
appendOutput("// String methods:");
appendOutput("String text = \"" + text + "\";");
appendOutput("text.length() = " + text.length());
appendOutput("text.charAt(0) = '" + (text.length() > 0 ? text.charAt(0) : "N/A") + "'");
appendOutput("text.toUpperCase() = \"" + text.toUpperCase() + "\"");
appendOutput("text.toLowerCase() = \"" + text.toLowerCase() + "\"");
appendOutput("");
// Character analysis
int vowels = 0, consonants = 0, digits = 0, spaces = 0;
for (char c : text.toCharArray()) {
if (Character.isLetter(c)) {
if ("aeiouAEIOU".indexOf(c) >= 0) vowels++;
else consonants++;
} else if (Character.isDigit(c)) {
digits++;
} else if (Character.isWhitespace(c)) {
spaces++;
}
}
appendOutput("📊 Character analysis:");
appendOutput("• Total characters: " + text.length());
appendOutput("• Vowels: " + vowels);
appendOutput("• Consonants: " + consonants);
appendOutput("• Digits: " + digits);
appendOutput("• Spaces: " + spaces);
appendOutput("");
completedLessons = Math.max(completedLessons, 5);
updateProgress();
}
private void demonstrateStringManipulation(JTextField textField) {
String text = textField.getText();
if (text.isEmpty()) {
appendOutput("❌ Please enter some text!");
return;
}
appendOutput("=== STRING MANIPULATION DEMONSTRATION ===");
appendOutput("Original: \"" + text + "\"");
appendOutput("");
if (text.length() >= 3) {
String substring = text.substring(0, Math.min(3, text.length()));
appendOutput("text.substring(0, 3) = \"" + substring + "\"");
}
String reversed = new StringBuilder(text).reverse().toString();
appendOutput("Reversed = \"" + reversed + "\"");
String[] words = text.split("\\s+");
appendOutput("text.split(\" \") = " + Arrays.toString(words));
appendOutput("Word count: " + words.length);
String trimmed = text.trim();
appendOutput("text.trim() = \"" + trimmed + "\"");
appendOutput("");
}
private void demonstrateStringSearch(JTextField textField) {
String text = textField.getText();
if (text.isEmpty()) {
appendOutput("❌ Please enter some text!");
return;
}
String searchTerm = JOptionPane.showInputDialog(this, "Enter text to search for:");
if (searchTerm == null || searchTerm.isEmpty()) return;
appendOutput("=== STRING SEARCH DEMONSTRATION ===");
appendOutput("Text: \"" + text + "\"");
appendOutput("Searching for: \"" + searchTerm + "\"");
appendOutput("");
boolean contains = text.contains(searchTerm);
int indexOf = text.indexOf(searchTerm);
int lastIndexOf = text.lastIndexOf(searchTerm);
appendOutput("text.contains(\"" + searchTerm + "\") = " + contains);
appendOutput("text.indexOf(\"" + searchTerm + "\") = " + indexOf);
appendOutput("text.lastIndexOf(\"" + searchTerm + "\") = " + lastIndexOf);
if (contains) {
String replacement = JOptionPane.showInputDialog(this, "Enter replacement text:");
if (replacement != null) {
String replaced = text.replace(searchTerm, replacement);
appendOutput("text.replace(\"" + searchTerm + "\", \"" + replacement + "\") = \"" + replaced + "\"");
}
}
appendOutput("");
}
private void demonstrateStringBuilder(JTextField textField) {
String text = textField.getText();
appendOutput("=== STRINGBUILDER DEMONSTRATION ===");
appendOutput("// StringBuilder is mutable and efficient for concatenation");
appendOutput("StringBuilder sb = new StringBuilder();");
appendOutput("");
StringBuilder sb = new StringBuilder();
appendOutput("sb.append(\"" + text + "\");");
sb.append(text);
appendOutput("sb.append(\" - Added text\");");
sb.append(" - Added text");