J'obtiens les erreurs suivantes à la compilation de mon projet java avec netbeans 12.2:
Voici le code du fichier Database.javaSEVERE: null
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:606)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:168)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:377)
at donnees.Database.<init>(Database.java:25)
at presentation.LoginForm.<init>(LoginForm.java:31)
at presentation.Main.main(Main.java:13)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "java.sql.Connection.prepareStatement(String)" because "this.connexion" is null
at presentation.LoginForm.checkLogin(LoginForm.java:244)BUILD SUCCESSFUL (total time: 22 seconds)
at presentation.LoginForm.btnConnecterActionPerformed(LoginForm.java:189)
at presentation.LoginForm.access$100(LoginForm.java:22)
at presentation.LoginForm$2.actionPerformed(LoginForm.java:108)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
at java.desktop/java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:297)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6614)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
at java.desktop/java.awt.Component.processEvent(Component.java:6379)
at java.desktop/java.awt.Container.processEvent(Container.java:2263)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4990)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2321)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4822)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4919)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4548)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4489)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2307)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2769)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4822)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Le code de mon fichier LoginForm.java
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 package donnees; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /** * * @author Mamy Sitraka */ public class Database { private Connection connection = null; public Database() { try { //Class.forName("com.mysql.jdbc.Driver"); Class.forName("com.mysql.cj.jdbc.Driver"); //connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/facturation?autoReconnect=true&useSSL=false","root",""); connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/facturation?serverTimezone=UTC","root",""); } catch (ClassNotFoundException ex) { Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { //a pop-up box JOptionPane.showMessageDialog(null, "Erreur de connexion à la base de données !","Erreur", JOptionPane.ERROR_MESSAGE); } } public Connection getConnetion() { return connection; } }
Le code de mon fichier EventQueue.java
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 package presentation; import donnees.Database; import java.awt.Toolkit; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.xml.bind.DatatypeConverter; import metier.Profil; import metier.Utilisateur; /** * * @author Mamy Sitraka */ public class LoginForm extends javax.swing.JFrame { private final Database db; private final Connection connexion; private Utilisateur utilisateur; private Profil profil; public LoginForm() { initComponents(); db = new Database(); connexion = db.getConnetion(); setIcon(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jPanel3 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); txtNomUtilisateur = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); txtMdp = new javax.swing.JPasswordField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); btnConnecter = new javax.swing.JButton(); btnQuitter = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Se connecter"); setBackground(new java.awt.Color(255, 255, 255)); setResizable(false); jPanel3.setBackground(new java.awt.Color(0, 170, 245)); jLabel5.setFont(new java.awt.Font("Arial", 0, 24)); // NOI18N jLabel5.setForeground(new java.awt.Color(0, 170, 245)); jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/icons8_businessman_100px.png"))); // NOI18N jLabel5.setText("Connectez-vous"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap(137, Short.MAX_VALUE) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(126, 126, 126)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(87, 87, 87) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); txtNomUtilisateur.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N txtNomUtilisateur.setBorder(javax.swing.BorderFactory.createMatteBorder(0, 0, 1, 0, new java.awt.Color(0, 170, 245))); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/icons8_user_filled_30px.png"))); // NOI18N jLabel1.setText(" "); txtMdp.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N txtMdp.setBorder(javax.swing.BorderFactory.createMatteBorder(0, 0, 1, 0, new java.awt.Color(0, 170, 245))); jLabel3.setFont(new java.awt.Font("Arial", 0, 24)); // NOI18N jLabel3.setForeground(new java.awt.Color(0, 170, 245)); jLabel3.setText("Connectez-vous"); jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/icons8_password_30px.png"))); // NOI18N jLabel4.setText(" "); btnConnecter.setBackground(new java.awt.Color(0, 170, 245)); btnConnecter.setForeground(new java.awt.Color(255, 255, 255)); btnConnecter.setText("Se connecter"); btnConnecter.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { btnConnecterMouseEntered(evt); } }); btnConnecter.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnConnecterActionPerformed(evt); } }); btnQuitter.setBackground(new java.awt.Color(0, 170, 245)); btnQuitter.setForeground(new java.awt.Color(255, 255, 255)); btnQuitter.setText("Quitter"); btnQuitter.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnQuitterActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(94, 94, 94) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btnConnecter, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnQuitter, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel4) .addGap(314, 314, 314))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtMdp, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtNomUtilisateur, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(123, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3) .addGap(191, 191, 191)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(38, 38, 38) .addComponent(jLabel3) .addGap(51, 51, 51) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtNomUtilisateur, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtMdp, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addGap(53, 53, 53) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnConnecter, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnQuitter, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(67, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold> private void btnConnecterActionPerformed(java.awt.event.ActionEvent evt) { try { if (checkLogin()) { MainFrame fenetrePrincipale = new MainFrame(utilisateur); fenetrePrincipale.setVisible(true); fenetrePrincipale.setLocationRelativeTo(null); this.dispose(); } else { JOptionPane.showMessageDialog(null, "Nom d'utilisateur ou mot de passe incorrect !", "Erreur", JOptionPane.ERROR_MESSAGE); } } catch (NoSuchAlgorithmException | SQLException ex) { Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex); } } private void btnConnecterMouseEntered(java.awt.event.MouseEvent evt) { // TODO add your handling code here: } private void btnQuitterActionPerformed(java.awt.event.ActionEvent evt) { this.dispose(); } public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new LoginForm().setVisible(true); } }); } private boolean checkLogin() throws NoSuchAlgorithmException, SQLException { PreparedStatement preparedStat = null; ResultSet res; String nomUtilisateur = txtNomUtilisateur.getText(); String motDePasse = String.valueOf(txtMdp.getPassword()); //Creer un hash en md5 MessageDigest md = MessageDigest.getInstance("MD5"); //on creer une instance d'objet MessageDigest md.update(motDePasse.getBytes()); byte[] digest = md.digest(); String motDePasseCrypte = DatatypeConverter.printHexBinary(digest); //requete preparee pour verifier l'authenticite de l'utilisateur preparedStat = connexion.prepareStatement("select * from utilisateur as u join profil as p on u.profil_id = p.id_profil where login=? and password=?"); preparedStat.setString(1, nomUtilisateur); preparedStat.setString(2, motDePasseCrypte); res = preparedStat.executeQuery(); if (res.next()) { //Creation de l'objet utilisateur et profil profil = new Profil(res.getInt("profil_id"), res.getString("designation_profil"), res.getString("commentaire")); utilisateur = new Utilisateur(res.getInt("id_utilisateur"), res.getString("nom"), res.getString("prenom"), profil, res.getString("login")); return true; } else { return false; } } private void setIcon() { setIconImage(Toolkit.getDefaultToolkit().getImage("icons8_bullish_filled_75px.png")); } // Variables declaration - do not modify private javax.swing.JButton btnConnecter; private javax.swing.JButton btnQuitter; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel3; private javax.swing.JPasswordField txtMdp; private javax.swing.JTextField txtNomUtilisateur; // End of variables declaration }
Et enfin mon Main.java
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387 package java.awt; import java.awt.event.*; import java.awt.peer.ComponentPeer; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.EmptyStackException; import sun.awt.*; import sun.awt.dnd.SunDropTargetEvent; import sun.util.logging.PlatformLogger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.atomic.AtomicInteger; import java.security.AccessControlContext; import jdk.internal.access.SharedSecrets; import jdk.internal.access.JavaSecurityAccess; /** * {@code EventQueue} is a platform-independent class * that queues events, both from the underlying peer classes * and from trusted application classes. * <p> * It encapsulates asynchronous event dispatch machinery which * extracts events from the queue and dispatches them by calling * {@link #dispatchEvent(AWTEvent) dispatchEvent(AWTEvent)} method * on this {@code EventQueue} with the event to be dispatched * as an argument. The particular behavior of this machinery is * implementation-dependent. The only requirements are that events * which were actually enqueued to this queue (note that events * being posted to the {@code EventQueue} can be coalesced) * are dispatched: * <dl> * <dt> Sequentially. * <dd> That is, it is not permitted that several events from * this queue are dispatched simultaneously. * <dt> In the same order as they are enqueued. * <dd> That is, if {@code AWTEvent} A is enqueued * to the {@code EventQueue} before * {@code AWTEvent} B then event B will not be * dispatched before event A. * </dl> * <p> * Some browsers partition applets in different code bases into * separate contexts, and establish walls between these contexts. * In such a scenario, there will be one {@code EventQueue} * per context. Other browsers place all applets into the same * context, implying that there will be only a single, global * {@code EventQueue} for all applets. This behavior is * implementation-dependent. Consult your browser's documentation * for more information. * <p> * For information on the threading issues of the event dispatch * machinery, see <a href="doc-files/AWTThreadIssues.html#Autoshutdown" * >AWT Threading Issues</a>. * * @author Thomas Ball * @author Fred Ecks * @author David Mendenhall * * @since 1.1 */ public class EventQueue { private static final AtomicInteger threadInitNumber = new AtomicInteger(0); private static final int LOW_PRIORITY = 0; private static final int NORM_PRIORITY = 1; private static final int HIGH_PRIORITY = 2; private static final int ULTIMATE_PRIORITY = 3; private static final int NUM_PRIORITIES = ULTIMATE_PRIORITY + 1; /* * We maintain one Queue for each priority that the EventQueue supports. * That is, the EventQueue object is actually implemented as * NUM_PRIORITIES queues and all Events on a particular internal Queue * have identical priority. Events are pulled off the EventQueue starting * with the Queue of highest priority. We progress in decreasing order * across all Queues. */ private Queue[] queues = new Queue[NUM_PRIORITIES]; /* * The next EventQueue on the stack, or null if this EventQueue is * on the top of the stack. If nextQueue is non-null, requests to post * an event are forwarded to nextQueue. */ private EventQueue nextQueue; /* * The previous EventQueue on the stack, or null if this is the * "base" EventQueue. */ private EventQueue previousQueue; /* * A single lock to synchronize the push()/pop() and related operations with * all the EventQueues from the AppContext. Synchronization on any particular * event queue(s) is not enough: we should lock the whole stack. */ private final Lock pushPopLock; private final Condition pushPopCond; /* * Dummy runnable to wake up EDT from getNextEvent() after push/pop is performed */ private static final Runnable dummyRunnable = new Runnable() { public void run() { } }; private EventDispatchThread dispatchThread; private final ThreadGroup threadGroup = Thread.currentThread().getThreadGroup(); private final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); /* * The time stamp of the last dispatched InputEvent or ActionEvent. */ private long mostRecentEventTime = System.currentTimeMillis(); /* * The time stamp of the last KeyEvent . */ private long mostRecentKeyEventTime = System.currentTimeMillis(); /** * The modifiers field of the current event, if the current event is an * InputEvent or ActionEvent. */ private WeakReference<AWTEvent> currentEvent; /* * Non-zero if a thread is waiting in getNextEvent(int) for an event of * a particular ID to be posted to the queue. */ private volatile int waitForID; /* * AppContext corresponding to the queue. */ private final AppContext appContext; private final String name = "AWT-EventQueue-" + threadInitNumber.getAndIncrement(); private FwDispatcher fwDispatcher; private static volatile PlatformLogger eventLog; private static final PlatformLogger getEventLog() { if(eventLog == null) { eventLog = PlatformLogger.getLogger("java.awt.event.EventQueue"); } return eventLog; } private static boolean fxAppThreadIsDispatchThread; static { AWTAccessor.setEventQueueAccessor( new AWTAccessor.EventQueueAccessor() { public Thread getDispatchThread(EventQueue eventQueue) { return eventQueue.getDispatchThread(); } public boolean isDispatchThreadImpl(EventQueue eventQueue) { return eventQueue.isDispatchThreadImpl(); } public void removeSourceEvents(EventQueue eventQueue, Object source, boolean removeAllEvents) { eventQueue.removeSourceEvents(source, removeAllEvents); } public boolean noEvents(EventQueue eventQueue) { return eventQueue.noEvents(); } public void wakeup(EventQueue eventQueue, boolean isShutdown) { eventQueue.wakeup(isShutdown); } public void invokeAndWait(Object source, Runnable r) throws InterruptedException, InvocationTargetException { EventQueue.invokeAndWait(source, r); } public void setFwDispatcher(EventQueue eventQueue, FwDispatcher dispatcher) { eventQueue.setFwDispatcher(dispatcher); } @Override public long getMostRecentEventTime(EventQueue eventQueue) { return eventQueue.getMostRecentEventTimeImpl(); } }); AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { fxAppThreadIsDispatchThread = "true".equals(System.getProperty("javafx.embed.singleThread")); return null; } }); } /** * Initializes a new instance of {@code EventQueue}. */ public EventQueue() { for (int i = 0; i < NUM_PRIORITIES; i++) { queues[i] = new Queue(); } /* * NOTE: if you ever have to start the associated event dispatch * thread at this point, be aware of the following problem: * If this EventQueue instance is created in * SunToolkit.createNewAppContext() the started dispatch thread * may call AppContext.getAppContext() before createNewAppContext() * completes thus causing mess in thread group to appcontext mapping. */ appContext = AppContext.getAppContext(); pushPopLock = (Lock)appContext.get(AppContext.EVENT_QUEUE_LOCK_KEY); pushPopCond = (Condition)appContext.get(AppContext.EVENT_QUEUE_COND_KEY); } /** * Posts a 1.1-style event to the {@code EventQueue}. * If there is an existing event on the queue with the same ID * and event source, the source {@code Component}'s * {@code coalesceEvents} method will be called. * * @param theEvent an instance of {@code java.awt.AWTEvent}, * or a subclass of it * @throws NullPointerException if {@code theEvent} is {@code null} */ public void postEvent(AWTEvent theEvent) { SunToolkit.flushPendingEvents(appContext); postEventPrivate(theEvent); } /** * Posts a 1.1-style event to the {@code EventQueue}. * If there is an existing event on the queue with the same ID * and event source, the source {@code Component}'s * {@code coalesceEvents} method will be called. * * @param theEvent an instance of {@code java.awt.AWTEvent}, * or a subclass of it */ private void postEventPrivate(AWTEvent theEvent) { theEvent.isPosted = true; pushPopLock.lock(); try { if (nextQueue != null) { // Forward the event to the top of EventQueue stack nextQueue.postEventPrivate(theEvent); return; } if (dispatchThread == null) { if (theEvent.getSource() == AWTAutoShutdown.getInstance()) { return; } else { initDispatchThread(); } } postEvent(theEvent, getPriority(theEvent)); } finally { pushPopLock.unlock(); } } private static int getPriority(AWTEvent theEvent) { if (theEvent instanceof PeerEvent) { PeerEvent peerEvent = (PeerEvent)theEvent; if ((peerEvent.getFlags() & PeerEvent.ULTIMATE_PRIORITY_EVENT) != 0) { return ULTIMATE_PRIORITY; } if ((peerEvent.getFlags() & PeerEvent.PRIORITY_EVENT) != 0) { return HIGH_PRIORITY; } if ((peerEvent.getFlags() & PeerEvent.LOW_PRIORITY_EVENT) != 0) { return LOW_PRIORITY; } } int id = theEvent.getID(); if ((id >= PaintEvent.PAINT_FIRST) && (id <= PaintEvent.PAINT_LAST)) { return LOW_PRIORITY; } return NORM_PRIORITY; } /** * Posts the event to the internal Queue of specified priority, * coalescing as appropriate. * * @param theEvent an instance of {@code java.awt.AWTEvent}, * or a subclass of it * @param priority the desired priority of the event */ private void postEvent(AWTEvent theEvent, int priority) { if (coalesceEvent(theEvent, priority)) { return; } EventQueueItem newItem = new EventQueueItem(theEvent); cacheEQItem(newItem); boolean notifyID = (theEvent.getID() == this.waitForID); if (queues[priority].head == null) { boolean shouldNotify = noEvents(); queues[priority].head = queues[priority].tail = newItem; if (shouldNotify) { if (theEvent.getSource() != AWTAutoShutdown.getInstance()) { AWTAutoShutdown.getInstance().notifyThreadBusy(dispatchThread); } pushPopCond.signalAll(); } else if (notifyID) { pushPopCond.signalAll(); } } else { // The event was not coalesced or has non-Component source. // Insert it at the end of the appropriate Queue. queues[priority].tail.next = newItem; queues[priority].tail = newItem; if (notifyID) { pushPopCond.signalAll(); } } } private boolean coalescePaintEvent(PaintEvent e) { ComponentPeer sourcePeer = ((Component)e.getSource()).peer; if (sourcePeer != null) { sourcePeer.coalescePaintEvent(e); } EventQueueItem[] cache = ((Component)e.getSource()).eventCache; if (cache == null) { return false; } int index = eventToCacheIndex(e); if (index != -1 && cache[index] != null) { PaintEvent merged = mergePaintEvents(e, (PaintEvent)cache[index].event); if (merged != null) { cache[index].event = merged; return true; } } return false; } private PaintEvent mergePaintEvents(PaintEvent a, PaintEvent b) { Rectangle aRect = a.getUpdateRect(); Rectangle bRect = b.getUpdateRect(); if (bRect.contains(aRect)) { return b; } if (aRect.contains(bRect)) { return a; } return null; } private boolean coalesceMouseEvent(MouseEvent e) { EventQueueItem[] cache = ((Component)e.getSource()).eventCache; if (cache == null) { return false; } int index = eventToCacheIndex(e); if (index != -1 && cache[index] != null) { cache[index].event = e; return true; } return false; } private boolean coalescePeerEvent(PeerEvent e) { EventQueueItem[] cache = ((Component)e.getSource()).eventCache; if (cache == null) { return false; } int index = eventToCacheIndex(e); if (index != -1 && cache[index] != null) { e = e.coalesceEvents((PeerEvent)cache[index].event); if (e != null) { cache[index].event = e; return true; } else { cache[index] = null; } } return false; } /* * Should avoid of calling this method by any means * as it's working time is dependent on EQ length. * In the worst case this method alone can slow down the entire application * 10 times by stalling the Event processing. * Only here by backward compatibility reasons. */ private boolean coalesceOtherEvent(AWTEvent e, int priority) { int id = e.getID(); Component source = (Component)e.getSource(); for (EventQueueItem entry = queues[priority].head; entry != null; entry = entry.next) { // Give Component.coalesceEvents a chance if (entry.event.getSource() == source && entry.event.getID() == id) { AWTEvent coalescedEvent = source.coalesceEvents( entry.event, e); if (coalescedEvent != null) { entry.event = coalescedEvent; return true; } } } return false; } private boolean coalesceEvent(AWTEvent e, int priority) { if (!(e.getSource() instanceof Component)) { return false; } if (e instanceof PeerEvent) { return coalescePeerEvent((PeerEvent)e); } // The worst case if (((Component)e.getSource()).isCoalescingEnabled() && coalesceOtherEvent(e, priority)) { return true; } if (e instanceof PaintEvent) { return coalescePaintEvent((PaintEvent)e); } if (e instanceof MouseEvent) { return coalesceMouseEvent((MouseEvent)e); } return false; } private void cacheEQItem(EventQueueItem entry) { int index = eventToCacheIndex(entry.event); if (index != -1 && entry.event.getSource() instanceof Component) { Component source = (Component)entry.event.getSource(); if (source.eventCache == null) { source.eventCache = new EventQueueItem[CACHE_LENGTH]; } source.eventCache[index] = entry; } } private void uncacheEQItem(EventQueueItem entry) { int index = eventToCacheIndex(entry.event); if (index != -1 && entry.event.getSource() instanceof Component) { Component source = (Component)entry.event.getSource(); if (source.eventCache == null) { return; } source.eventCache[index] = null; } } private static final int PAINT = 0; private static final int UPDATE = 1; private static final int MOVE = 2; private static final int DRAG = 3; private static final int PEER = 4; private static final int CACHE_LENGTH = 5; private static int eventToCacheIndex(AWTEvent e) { switch(e.getID()) { case PaintEvent.PAINT: return PAINT; case PaintEvent.UPDATE: return UPDATE; case MouseEvent.MOUSE_MOVED: return MOVE; case MouseEvent.MOUSE_DRAGGED: // Return -1 for SunDropTargetEvent since they are usually synchronous // and we don't want to skip them by coalescing with MouseEvent or other drag events return e instanceof SunDropTargetEvent ? -1 : DRAG; default: return e instanceof PeerEvent ? PEER : -1; } } /** * Returns whether an event is pending on any of the separate * Queues. * @return whether an event is pending on any of the separate Queues */ private boolean noEvents() { for (int i = 0; i < NUM_PRIORITIES; i++) { if (queues[i].head != null) { return false; } } return true; } /** * Removes an event from the {@code EventQueue} and * returns it. This method will block until an event has * been posted by another thread. * @return the next {@code AWTEvent} * @exception InterruptedException * if any thread has interrupted this thread */ public AWTEvent getNextEvent() throws InterruptedException { do { /* * SunToolkit.flushPendingEvents must be called outside * of the synchronized block to avoid deadlock when * event queues are nested with push()/pop(). */ SunToolkit.flushPendingEvents(appContext); pushPopLock.lock(); try { AWTEvent event = getNextEventPrivate(); if (event != null) { return event; } AWTAutoShutdown.getInstance().notifyThreadFree(dispatchThread); pushPopCond.await(); } finally { pushPopLock.unlock(); } } while(true); } /* * Must be called under the lock. Doesn't call flushPendingEvents() */ AWTEvent getNextEventPrivate() throws InterruptedException { for (int i = NUM_PRIORITIES - 1; i >= 0; i--) { if (queues[i].head != null) { EventQueueItem entry = queues[i].head; queues[i].head = entry.next; if (entry.next == null) { queues[i].tail = null; } uncacheEQItem(entry); return entry.event; } } return null; } AWTEvent getNextEvent(int id) throws InterruptedException { do { /* * SunToolkit.flushPendingEvents must be called outside * of the synchronized block to avoid deadlock when * event queues are nested with push()/pop(). */ SunToolkit.flushPendingEvents(appContext); pushPopLock.lock(); try { for (int i = 0; i < NUM_PRIORITIES; i++) { for (EventQueueItem entry = queues[i].head, prev = null; entry != null; prev = entry, entry = entry.next) { if (entry.event.getID() == id) { if (prev == null) { queues[i].head = entry.next; } else { prev.next = entry.next; } if (queues[i].tail == entry) { queues[i].tail = prev; } uncacheEQItem(entry); return entry.event; } } } waitForID = id; pushPopCond.await(); waitForID = 0; } finally { pushPopLock.unlock(); } } while(true); } /** * Returns the first event on the {@code EventQueue} * without removing it. * @return the first event */ public AWTEvent peekEvent() { pushPopLock.lock(); try { for (int i = NUM_PRIORITIES - 1; i >= 0; i--) { if (queues[i].head != null) { return queues[i].head.event; } } } finally { pushPopLock.unlock(); } return null; } /** * Returns the first event with the specified id, if any. * @param id the id of the type of event desired * @return the first event of the specified id or {@code null} * if there is no such event */ public AWTEvent peekEvent(int id) { pushPopLock.lock(); try { for (int i = NUM_PRIORITIES - 1; i >= 0; i--) { EventQueueItem q = queues[i].head; for (; q != null; q = q.next) { if (q.event.getID() == id) { return q.event; } } } } finally { pushPopLock.unlock(); } return null; } private static final JavaSecurityAccess javaSecurityAccess = SharedSecrets.getJavaSecurityAccess(); /** * Dispatches an event. The manner in which the event is * dispatched depends upon the type of the event and the * type of the event's source object: * * <table class="striped"> * <caption>Event types, source types, and dispatch methods</caption> * <thead> * <tr> * <th scope="col">Event Type * <th scope="col">Source Type * <th scope="col">Dispatched To * </thead> * <tbody> * <tr> * <th scope="row">ActiveEvent * <td>Any * <td>event.dispatch() * <tr> * <th scope="row">Other * <td>Component * <td>source.dispatchEvent(AWTEvent) * <tr> * <th scope="row">Other * <td>MenuComponent * <td>source.dispatchEvent(AWTEvent) * <tr> * <th scope="row">Other * <td>Other * <td>No action (ignored) * </tbody> * </table> * * @param event an instance of {@code java.awt.AWTEvent}, * or a subclass of it * @throws NullPointerException if {@code event} is {@code null} * @since 1.2 */ protected void dispatchEvent(final AWTEvent event) { final Object src = event.getSource(); final PrivilegedAction<Void> action = new PrivilegedAction<Void>() { public Void run() { // In case fwDispatcher is installed and we're already on the // dispatch thread (e.g. performing DefaultKeyboardFocusManager.sendMessage), // dispatch the event straight away. if (fwDispatcher == null || isDispatchThreadImpl()) { dispatchEventImpl(event, src); } else { fwDispatcher.scheduleDispatch(new Runnable() { @Override public void run() { if (dispatchThread.filterAndCheckEvent(event)) { dispatchEventImpl(event, src); } } }); } return null; } }; final AccessControlContext stack = AccessController.getContext(); final AccessControlContext srcAcc = getAccessControlContextFrom(src); final AccessControlContext eventAcc = event.getAccessControlContext(); if (srcAcc == null) { javaSecurityAccess.doIntersectionPrivilege(action, stack, eventAcc); } else { javaSecurityAccess.doIntersectionPrivilege( new PrivilegedAction<Void>() { public Void run() { javaSecurityAccess.doIntersectionPrivilege(action, eventAcc); return null; } }, stack, srcAcc); } } private static AccessControlContext getAccessControlContextFrom(Object src) { return src instanceof Component ? ((Component)src).getAccessControlContext() : src instanceof MenuComponent ? ((MenuComponent)src).getAccessControlContext() : src instanceof TrayIcon ? ((TrayIcon)src).getAccessControlContext() : null; } /** * Called from dispatchEvent() under a correct AccessControlContext */ private void dispatchEventImpl(final AWTEvent event, final Object src) { event.isPosted = true; if (event instanceof ActiveEvent) { // This could become the sole method of dispatching in time. setCurrentEventAndMostRecentTimeImpl(event); ((ActiveEvent)event).dispatch(); } else if (src instanceof Component) { ((Component)src).dispatchEvent(event); event.dispatched(); } else if (src instanceof MenuComponent) { ((MenuComponent)src).dispatchEvent(event); } else if (src instanceof TrayIcon) { ((TrayIcon)src).dispatchEvent(event); } else if (src instanceof AWTAutoShutdown) { if (noEvents()) { dispatchThread.stopDispatching(); } } else { if (getEventLog().isLoggable(PlatformLogger.Level.FINE)) { getEventLog().fine("Unable to dispatch event: " + event); } } } /** * Returns the timestamp of the most recent event that had a timestamp, and * that was dispatched from the {@code EventQueue} associated with the * calling thread. If an event with a timestamp is currently being * dispatched, its timestamp will be returned. If no events have yet * been dispatched, the EventQueue's initialization time will be * returned instead.In the current version of * the JDK, only {@code InputEvent}s, * {@code ActionEvent}s, and {@code InvocationEvent}s have * timestamps; however, future versions of the JDK may add timestamps to * additional event types. Note that this method should only be invoked * from an application's {@link #isDispatchThread event dispatching thread}. * If this method is * invoked from another thread, the current system time (as reported by * {@code System.currentTimeMillis()}) will be returned instead. * * @return the timestamp of the last {@code InputEvent}, * {@code ActionEvent}, or {@code InvocationEvent} to be * dispatched, or {@code System.currentTimeMillis()} if this * method is invoked on a thread other than an event dispatching * thread * @see java.awt.event.InputEvent#getWhen * @see java.awt.event.ActionEvent#getWhen * @see java.awt.event.InvocationEvent#getWhen * @see #isDispatchThread * * @since 1.4 */ public static long getMostRecentEventTime() { return Toolkit.getEventQueue().getMostRecentEventTimeImpl(); } private long getMostRecentEventTimeImpl() { pushPopLock.lock(); try { return (Thread.currentThread() == dispatchThread) ? mostRecentEventTime : System.currentTimeMillis(); } finally { pushPopLock.unlock(); } } /** * @return most recent event time on all threads. */ long getMostRecentEventTimeEx() { pushPopLock.lock(); try { return mostRecentEventTime; } finally { pushPopLock.unlock(); } } /** * Returns the event currently being dispatched by the * {@code EventQueue} associated with the calling thread. This is * useful if a method needs access to the event, but was not designed to * receive a reference to it as an argument. Note that this method should * only be invoked from an application's event dispatching thread. If this * method is invoked from another thread, null will be returned. * * @return the event currently being dispatched, or null if this method is * invoked on a thread other than an event dispatching thread * @since 1.4 */ public static AWTEvent getCurrentEvent() { return Toolkit.getEventQueue().getCurrentEventImpl(); } private AWTEvent getCurrentEventImpl() { pushPopLock.lock(); try { if (Thread.currentThread() == dispatchThread || fxAppThreadIsDispatchThread) { return (currentEvent != null) ? currentEvent.get() : null; } return null; } finally { pushPopLock.unlock(); } } /** * Replaces the existing {@code EventQueue} with the specified one. * Any pending events are transferred to the new {@code EventQueue} * for processing by it. * * @param newEventQueue an {@code EventQueue} * (or subclass thereof) instance to be use * @see java.awt.EventQueue#pop * @throws NullPointerException if {@code newEventQueue} is {@code null} * @since 1.2 */ public void push(EventQueue newEventQueue) { if (getEventLog().isLoggable(PlatformLogger.Level.FINE)) { getEventLog().fine("EventQueue.push(" + newEventQueue + ")"); } pushPopLock.lock(); try { EventQueue topQueue = this; while (topQueue.nextQueue != null) { topQueue = topQueue.nextQueue; } if (topQueue.fwDispatcher != null) { throw new RuntimeException("push() to queue with fwDispatcher"); } if ((topQueue.dispatchThread != null) && (topQueue.dispatchThread.getEventQueue() == this)) { newEventQueue.dispatchThread = topQueue.dispatchThread; topQueue.dispatchThread.setEventQueue(newEventQueue); } // Transfer all events forward to new EventQueue. while (topQueue.peekEvent() != null) { try { // Use getNextEventPrivate() as it doesn't call flushPendingEvents() newEventQueue.postEventPrivate(topQueue.getNextEventPrivate()); } catch (InterruptedException ie) { if (getEventLog().isLoggable(PlatformLogger.Level.FINE)) { getEventLog().fine("Interrupted push", ie); } } } if (topQueue.dispatchThread != null) { // Wake up EDT waiting in getNextEvent(), so it can // pick up a new EventQueue. Post the waking event before // topQueue.nextQueue is assigned, otherwise the event would // go newEventQueue topQueue.postEventPrivate(new InvocationEvent(topQueue, dummyRunnable)); } newEventQueue.previousQueue = topQueue; topQueue.nextQueue = newEventQueue; if (appContext.get(AppContext.EVENT_QUEUE_KEY) == topQueue) { appContext.put(AppContext.EVENT_QUEUE_KEY, newEventQueue); } pushPopCond.signalAll(); } finally { pushPopLock.unlock(); } } /** * Stops dispatching events using this {@code EventQueue}. * Any pending events are transferred to the previous * {@code EventQueue} for processing. * <p> * Warning: To avoid deadlock, do not declare this method * synchronized in a subclass. * * @exception EmptyStackException if no previous push was made * on this {@code EventQueue} * @see java.awt.EventQueue#push * @since 1.2 */ protected void pop() throws EmptyStackException { if (getEventLog().isLoggable(PlatformLogger.Level.FINE)) { getEventLog().fine("EventQueue.pop(" + this + ")"); } pushPopLock.lock(); try { EventQueue topQueue = this; while (topQueue.nextQueue != null) { topQueue = topQueue.nextQueue; } EventQueue prevQueue = topQueue.previousQueue; if (prevQueue == null) { throw new EmptyStackException(); } topQueue.previousQueue = null; prevQueue.nextQueue = null; // Transfer all events back to previous EventQueue. while (topQueue.peekEvent() != null) { try { prevQueue.postEventPrivate(topQueue.getNextEventPrivate()); } catch (InterruptedException ie) { if (getEventLog().isLoggable(PlatformLogger.Level.FINE)) { getEventLog().fine("Interrupted pop", ie); } } } if ((topQueue.dispatchThread != null) && (topQueue.dispatchThread.getEventQueue() == this)) { prevQueue.dispatchThread = topQueue.dispatchThread; topQueue.dispatchThread.setEventQueue(prevQueue); } if (appContext.get(AppContext.EVENT_QUEUE_KEY) == this) { appContext.put(AppContext.EVENT_QUEUE_KEY, prevQueue); } // Wake up EDT waiting in getNextEvent(), so it can // pick up a new EventQueue topQueue.postEventPrivate(new InvocationEvent(topQueue, dummyRunnable)); pushPopCond.signalAll(); } finally { pushPopLock.unlock(); } } /** * Creates a new {@code secondary loop} associated with this * event queue. Use the {@link SecondaryLoop#enter} and * {@link SecondaryLoop#exit} methods to start and stop the * event loop and dispatch the events from this queue. * * @return secondaryLoop A new secondary loop object, which can * be used to launch a new nested event * loop and dispatch events from this queue * * @see SecondaryLoop#enter * @see SecondaryLoop#exit * * @since 1.7 */ public SecondaryLoop createSecondaryLoop() { return createSecondaryLoop(null, null, 0); } private class FwSecondaryLoopWrapper implements SecondaryLoop { final private SecondaryLoop loop; final private EventFilter filter; public FwSecondaryLoopWrapper(SecondaryLoop loop, EventFilter filter) { this.loop = loop; this.filter = filter; } @Override public boolean enter() { if (filter != null) { dispatchThread.addEventFilter(filter); } return loop.enter(); } @Override public boolean exit() { if (filter != null) { dispatchThread.removeEventFilter(filter); } return loop.exit(); } } SecondaryLoop createSecondaryLoop(Conditional cond, EventFilter filter, long interval) { pushPopLock.lock(); try { if (nextQueue != null) { // Forward the request to the top of EventQueue stack return nextQueue.createSecondaryLoop(cond, filter, interval); } if (fwDispatcher != null) { return new FwSecondaryLoopWrapper(fwDispatcher.createSecondaryLoop(), filter); } if (dispatchThread == null) { initDispatchThread(); } return new WaitDispatchSupport(dispatchThread, cond, filter, interval); } finally { pushPopLock.unlock(); } } /** * Returns true if the calling thread is * {@link Toolkit#getSystemEventQueue the current AWT EventQueue}'s * dispatch thread. Use this method to ensure that a particular * task is being executed (or not being) there. * <p> * Note: use the {@link #invokeLater} or {@link #invokeAndWait} * methods to execute a task in * {@link Toolkit#getSystemEventQueue the current AWT EventQueue}'s * dispatch thread. * * @return true if running in * {@link Toolkit#getSystemEventQueue the current AWT EventQueue}'s * dispatch thread * @see #invokeLater * @see #invokeAndWait * @see Toolkit#getSystemEventQueue * @since 1.2 */ public static boolean isDispatchThread() { EventQueue eq = Toolkit.getEventQueue(); return eq.isDispatchThreadImpl(); } final boolean isDispatchThreadImpl() { EventQueue eq = this; pushPopLock.lock(); try { EventQueue next = eq.nextQueue; while (next != null) { eq = next; next = eq.nextQueue; } if (eq.fwDispatcher != null) { return eq.fwDispatcher.isDispatchThread(); } return (Thread.currentThread() == eq.dispatchThread); } finally { pushPopLock.unlock(); } } final void initDispatchThread() { pushPopLock.lock(); try { if (dispatchThread == null && !threadGroup.isDestroyed() && !appContext.isDisposed()) { dispatchThread = AccessController.doPrivileged( new PrivilegedAction<EventDispatchThread>() { public EventDispatchThread run() { EventDispatchThread t = new EventDispatchThread(threadGroup, name, EventQueue.this); t.setContextClassLoader(classLoader); t.setPriority(Thread.NORM_PRIORITY + 1); t.setDaemon(false); AWTAutoShutdown.getInstance().notifyThreadBusy(t); return t; } } ); dispatchThread.start(); } } finally { pushPopLock.unlock(); } } final void detachDispatchThread(EventDispatchThread edt) { /* * Minimize discard possibility for non-posted events */ SunToolkit.flushPendingEvents(appContext); /* * This synchronized block is to secure that the event dispatch * thread won't die in the middle of posting a new event to the * associated event queue. It is important because we notify * that the event dispatch thread is busy after posting a new event * to its queue, so the EventQueue.dispatchThread reference must * be valid at that point. */ pushPopLock.lock(); try { if (edt == dispatchThread) { dispatchThread = null; } AWTAutoShutdown.getInstance().notifyThreadFree(edt); /* * Event was posted after EDT events pumping had stopped, so start * another EDT to handle this event */ if (peekEvent() != null) { initDispatchThread(); } } finally { pushPopLock.unlock(); } } /* * Gets the {@code EventDispatchThread} for this * {@code EventQueue}. * @return the event dispatch thread associated with this event queue * or {@code null} if this event queue doesn't have a * working thread associated with it * @see java.awt.EventQueue#initDispatchThread * @see java.awt.EventQueue#detachDispatchThread */ final EventDispatchThread getDispatchThread() { pushPopLock.lock(); try { return dispatchThread; } finally { pushPopLock.unlock(); } } /* * Removes any pending events for the specified source object. * If removeAllEvents parameter is {@code true} then all * events for the specified source object are removed, if it * is {@code false} then {@code SequencedEvent}, {@code SentEvent}, * {@code FocusEvent}, {@code WindowEvent}, {@code KeyEvent}, * and {@code InputMethodEvent} are kept in the queue, but all other * events are removed. * * This method is normally called by the source's * {@code removeNotify} method. */ final void removeSourceEvents(Object source, boolean removeAllEvents) { SunToolkit.flushPendingEvents(appContext); pushPopLock.lock(); try { for (int i = 0; i < NUM_PRIORITIES; i++) { EventQueueItem entry = queues[i].head; EventQueueItem prev = null; while (entry != null) { if ((entry.event.getSource() == source) && (removeAllEvents || ! (entry.event instanceof SequencedEvent || entry.event instanceof SentEvent || entry.event instanceof FocusEvent || entry.event instanceof WindowEvent || entry.event instanceof KeyEvent || entry.event instanceof InputMethodEvent))) { if (entry.event instanceof SequencedEvent) { ((SequencedEvent)entry.event).dispose(); } if (entry.event instanceof SentEvent) { ((SentEvent)entry.event).dispose(); } if (entry.event instanceof InvocationEvent) { AWTAccessor.getInvocationEventAccessor() .dispose((InvocationEvent)entry.event); } if (entry.event instanceof SunDropTargetEvent) { ((SunDropTargetEvent)entry.event).dispose(); } if (prev == null) { queues[i].head = entry.next; } else { prev.next = entry.next; } uncacheEQItem(entry); } else { prev = entry; } entry = entry.next; } queues[i].tail = prev; } } finally { pushPopLock.unlock(); } } synchronized long getMostRecentKeyEventTime() { pushPopLock.lock(); try { return mostRecentKeyEventTime; } finally { pushPopLock.unlock(); } } static void setCurrentEventAndMostRecentTime(AWTEvent e) { Toolkit.getEventQueue().setCurrentEventAndMostRecentTimeImpl(e); } private void setCurrentEventAndMostRecentTimeImpl(AWTEvent e) { pushPopLock.lock(); try { if (!fxAppThreadIsDispatchThread && Thread.currentThread() != dispatchThread) { return; } currentEvent = new WeakReference<>(e); // This series of 'instanceof' checks should be replaced with a // polymorphic type (for example, an interface which declares a // getWhen() method). However, this would require us to make such // a type public, or to place it in sun.awt. Both of these approaches // have been frowned upon. So for now, we hack. // // In tiger, we will probably give timestamps to all events, so this // will no longer be an issue. long mostRecentEventTime2 = Long.MIN_VALUE; if (e instanceof InputEvent) { InputEvent ie = (InputEvent)e; mostRecentEventTime2 = ie.getWhen(); if (e instanceof KeyEvent) { mostRecentKeyEventTime = ie.getWhen(); } } else if (e instanceof InputMethodEvent) { InputMethodEvent ime = (InputMethodEvent)e; mostRecentEventTime2 = ime.getWhen(); } else if (e instanceof ActionEvent) { ActionEvent ae = (ActionEvent)e; mostRecentEventTime2 = ae.getWhen(); } else if (e instanceof InvocationEvent) { InvocationEvent ie = (InvocationEvent)e; mostRecentEventTime2 = ie.getWhen(); } mostRecentEventTime = Math.max(mostRecentEventTime, mostRecentEventTime2); } finally { pushPopLock.unlock(); } } /** * Causes {@code runnable} to have its {@code run} * method called in the {@link #isDispatchThread dispatch thread} of * {@link Toolkit#getSystemEventQueue the system EventQueue}. * This will happen after all pending events are processed. * * @param runnable the {@code Runnable} whose {@code run} * method should be executed * asynchronously in the * {@link #isDispatchThread event dispatch thread} * of {@link Toolkit#getSystemEventQueue the system EventQueue} * @see #invokeAndWait * @see Toolkit#getSystemEventQueue * @see #isDispatchThread * @since 1.2 */ public static void invokeLater(Runnable runnable) { Toolkit.getEventQueue().postEvent( new InvocationEvent(Toolkit.getDefaultToolkit(), runnable)); } /** * Causes {@code runnable} to have its {@code run} * method called in the {@link #isDispatchThread dispatch thread} of * {@link Toolkit#getSystemEventQueue the system EventQueue}. * This will happen after all pending events are processed. * The call blocks until this has happened. This method * will throw an Error if called from the * {@link #isDispatchThread event dispatcher thread}. * * @param runnable the {@code Runnable} whose {@code run} * method should be executed * synchronously in the * {@link #isDispatchThread event dispatch thread} * of {@link Toolkit#getSystemEventQueue the system EventQueue} * @exception InterruptedException if any thread has * interrupted this thread * @exception InvocationTargetException if an throwable is thrown * when running {@code runnable} * @see #invokeLater * @see Toolkit#getSystemEventQueue * @see #isDispatchThread * @since 1.2 */ public static void invokeAndWait(Runnable runnable) throws InterruptedException, InvocationTargetException { invokeAndWait(Toolkit.getDefaultToolkit(), runnable); } static void invokeAndWait(Object source, Runnable runnable) throws InterruptedException, InvocationTargetException { if (EventQueue.isDispatchThread()) { throw new Error("Cannot call invokeAndWait from the event dispatcher thread"); } class AWTInvocationLock {} Object lock = new AWTInvocationLock(); InvocationEvent event = new InvocationEvent(source, runnable, lock, true); synchronized (lock) { Toolkit.getEventQueue().postEvent(event); while (!event.isDispatched()) { lock.wait(); } } Throwable eventThrowable = event.getThrowable(); if (eventThrowable != null) { throw new InvocationTargetException(eventThrowable); } } /* * Called from PostEventQueue.postEvent to notify that a new event * appeared. First it proceeds to the EventQueue on the top of the * stack, then notifies the associated dispatch thread if it exists * or starts a new one otherwise. */ private void wakeup(boolean isShutdown) { pushPopLock.lock(); try { if (nextQueue != null) { // Forward call to the top of EventQueue stack. nextQueue.wakeup(isShutdown); } else if (dispatchThread != null) { pushPopCond.signalAll(); } else if (!isShutdown) { initDispatchThread(); } } finally { pushPopLock.unlock(); } } // The method is used by AWTAccessor for javafx/AWT single threaded mode. private void setFwDispatcher(FwDispatcher dispatcher) { if (nextQueue != null) { nextQueue.setFwDispatcher(dispatcher); } else { fwDispatcher = dispatcher; } } } /** * The Queue object holds pointers to the beginning and end of one internal * queue. An EventQueue object is composed of multiple internal Queues, one * for each priority supported by the EventQueue. All Events on a particular * internal Queue have identical priority. */ class Queue { EventQueueItem head; EventQueueItem tail; }
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package presentation; import javax.swing.JFrame; /** * * @author Mamy Sitraka */ public class Main { public static void main(String[] args) { LoginForm login = new LoginForm(); login.setVisible(true); login.setLocationRelativeTo(null);//centrer le Frame login.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//on ferme l'application en fermant cette fenetre login.pack(); } }
Aidez-moi s'il vous plaît à faire marcher mon application.
Partager