IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Composants Java Discussion :

Drag & Drop et JTable


Sujet :

Composants Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Candidat au Club
    Profil pro
    Inscrit en
    Février 2011
    Messages
    3
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2011
    Messages : 3
    Par défaut Drag & Drop et JTable
    Bonjour,

    Suite aux différents codes que j'ai trouvé ici et ici, dont je remercie d'ailleurs les auteurs, j'aimerais mettre en place 2 Drag&Drop différents sur une JTable.

    L'un concerne le glisser/déposer de fichiers/dossier sur la JTable pour remplir automatiquement celle-ci.
    L'autre concerne le glisser/déplacer des différentes lignes de la JTable.

    Le problème dans mon code est qu'il y a une forme de conflit entre les 2. Lorsque le glisser/déplacer est activé, le glisser/déposer au-dessus de la JTable ne fonctionne pas, mais cela fonctionne au dessus de la JFrame.
    Comment faire pour que le glisser/déplacer fonctionne aussi au-dessus de la JTable ?

    Vous pourrez trouver ici les sources et un .jar de mon code.
    L'application n'accepte que les fichiers .mp3 et fonctionne uniquement avec java 1.6.

    Merci d'avance pour toute aide que vous pourrez m'apporter.

    Julien

    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
     
     
     
    import java.io.File;
    import java.io.IOException;
    import java.net.URL;
     
    import java.util.List;
    import java.util.Map;
    import java.util.Vector;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
     
    import java.awt.Desktop;
    import java.awt.Window;
    import java.awt.datatransfer.*;
    import java.awt.dnd.DnDConstants;
    import java.awt.dnd.DropTarget;
    import java.awt.dnd.DropTargetDragEvent;
    import java.awt.dnd.DropTargetDropEvent;
    import java.awt.dnd.DropTargetEvent;
    import java.awt.dnd.DropTargetListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.WindowEvent;
     
    import javax.sound.sampled.*;
     
    import javax.swing.*;
    import javax.swing.table.*;
     
    import com.explodingpixels.macwidgets.*;
     
    import org.tritonus.share.sampled.file.TAudioFileFormat;
     
     
     
    public class JTableDnDPanel {
     
    	private Vector<String> stuff1 = new Vector<String>();
     
    	private JFrame fr = null;
     
    	private JTable table;
     
    	private DefaultTableModel model;
     
    	private int count = 0;
     
    	private String[][] data;
     
    	private Window window;
     
     
    	private int iCurrentRow = 0;
     
     
    	// ----- Key Events
    	private Vector<Integer> keys = new Vector<Integer>(2);
    	private boolean pressed = false;
     
     
    	public JTableDnDPanel() 
    	{
    		createAndShowGUI();
    	}
     
     
    	public class PanelDropTarget implements DropTargetListener, MouseListener, KeyListener 
    	{
    		DropTarget dt;
     
     
    		public PanelDropTarget() 
    		{
     
    			data = new String[stuff1.size()][3];
     
    			count = 0;
    			for (int i = 0; i < stuff1.size(); i++) 
    			{
    				StringBuffer result = new StringBuffer();
    				result.append(i);
    				data[i][0] = result.toString();
    				data[i][1] = stuff1.get(i);
    				data[i][2] = " ";
    				count++;
    			}
     
     
    			fr = new JFrame("Playlist");
     
    			String[] columnNames = new String[] { "Index", "Name", "Duration", "Artist", "Path" };
    			model = new MyTableModel(data, columnNames);
     
    			table = MacWidgetFactory.createITunesTable(model);
     
    			//table = new JTable(model);
     
    			JScrollPane scrollPane = new JScrollPane(table);
    			TableCellRenderer ctcr = table.getCellRenderer(0, 0);
    			DefaultTableCellRenderer rendererRight = (DefaultTableCellRenderer)ctcr; 
    			rendererRight.setHorizontalAlignment(JLabel.RIGHT);  
     
    			table.setRowSelectionAllowed(true);
    			table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);//SINGLE_SELECTION
    			/* DROP MODES
    				    * DropMode.USE_SELECTION
    				    * DropMode.ON
    				    * DropMode.INSERT
    				    * DropMode.INSERT_ROWS
    				    * DropMode.INSERT_COLS
    				    * DropMode.ON_OR_INSERT
    				    * DropMode.ON_OR_INSERT_ROWS
    				    * DropMode.ON_OR_INSERT_COLS
    			*/
     
    			table.setDropMode(DropMode.ON_OR_INSERT_ROWS);
    			table.setDragEnabled(true);
    			table.setTransferHandler(new MyTransfertHandler());
    			table.setFillsViewportHeight(true);
    			table.addMouseListener(this);
    			table.setOpaque(false);
    			table.addKeyListener(this);
     
     
    			TableColumn colIndex = table.getColumnModel().getColumn(0);
    			colIndex.setPreferredWidth(50);
     
     
    			TableColumn colName = table.getColumnModel().getColumn(1);
    			colName.setPreferredWidth(260);
     
    			dt = new DropTarget(fr, this);
     
    			window = new Window(fr);
    			window.addKeyListener(this);
     
    			fr.setDropTarget(dt);
    			fr.add(scrollPane);
    			fr.setSize(630, 550);
    			fr.setLocationRelativeTo(null);
    			fr.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    			fr.setVisible(true);
    		}
     
    		protected void processWindowEvent(WindowEvent e)
    		{
    			System.out.println(e);
    		}
     
    		public void dragEnter(DropTargetDragEvent dtde) 
    		{
    			//System.out.println("Drag Enter");
    		}
     
    		public void dragExit(DropTargetEvent dte) 
    		{
    			//System.out.println("Drag Exit");
    		}
     
    		public void dragOver(DropTargetDragEvent dtde) 
    		{
    			//System.out.println("Drag Over");
    		}
     
    		public void dropActionChanged(DropTargetDragEvent dtde) 
    		{
    			//System.out.println("Drop Action Changed");
    		}
     
    		public void drop(DropTargetDropEvent dtde) 
    		{
    			try 
    			{
    				Transferable tr = dtde.getTransferable();
    				DataFlavor[] flavors = tr.getTransferDataFlavors();
     
    				for (int i = 0; i < flavors.length; i++) 
    				{
    					if (flavors[i].isFlavorJavaFileListType()) 
    					{
    						dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
    						List<?> list = (List<?>) tr.getTransferData(flavors[i]);
     
    						JFileChooser chooser = new JFileChooser();
     
    						for (int j = 0; j < list.size(); j++) 
    						{
    							StringBuffer result = new StringBuffer();
    							result.append( list.get(j) );
    							File f = new File(result.toString());
     
    							File[] a = f.listFiles();
     
    							String fileTypeName = chooser.getTypeDescription(f);
     
    							if ( (fileTypeName.compareTo("Directory") == 0) || (fileTypeName.compareTo("Répertoire") == 0) )
    							{
    								for ( int k = 0; k < a.length; k++ )
    								{
    									stuff1.add( a[k].toString() );
     
    									if ( isMp3File( a[k].toString() ) )
    									{
    										GetId3Tag gi3t = new GetId3Tag( a[k].toString() );
    										Long duration = gi3t.getDuration();
     
    										if ( gi3t.getTitle() != null )
    										{
    											model.addRow(new Object[]{table.getRowCount(), gi3t.getTitle(), getTime( duration ), gi3t.getArtiste(), a[k].toString()});
    										}
    										else
    										{
    											Pattern p = Pattern.compile("([^/]+?).(mp3?)");
    											Matcher m = p.matcher(a[k].toString());
     
    											String t = null;
     
    											while(m.find()) 
    											{
    												t = m.group(1);
    											}
     
    											p = Pattern.compile(":");
    											m = p.matcher(t);
     
    											String s = null;
     
    											if(m.find()) 
    											{
    												s = m.replaceAll("/");
    											}
    											else
    											{
    												s = t;
    											}
     
    											model.addRow(new Object[]{table.getRowCount(), s, getTime( duration ), " ", a[k].toString()});
    										}
     
    										Object[] o = new Object[5];
    										o[0] = table.getValueAt(table.getRowCount()-1, 0);
    										o[1] = table.getValueAt(table.getRowCount()-1, 1);
    										o[2] = table.getValueAt(table.getRowCount()-1, 2);
    										o[3] = table.getValueAt(table.getRowCount()-1, 3);
    										o[4] = table.getValueAt(table.getRowCount()-1, 4);
     
    									}		
    								}
    							}
    							else
    							{
    								stuff1.add( f.toString() );
     
    								if ( isMp3File( f.toString() ) )
    								{
    									GetId3Tag gi3t = new GetId3Tag( f.toString() );
    									Long duration = gi3t.getDuration();
     
    									if ( gi3t.getTitle() != null )
    									{
    										model.addRow(new Object[]{table.getRowCount(), gi3t.getTitle(), getTime( duration ), gi3t.getArtiste(), f.toString()});
    									}
    									else
    									{
    										Pattern p = Pattern.compile("([^/]+?).(mp3?)");
    										Matcher m = p.matcher(f.toString());
     
    										String t = null;
     
    										while(m.find()) 
    										{
    											t = m.group(1);
    										}
     
    										p = Pattern.compile(":");
    										m = p.matcher(t);
     
    										String s = null;
     
    										if(m.find()) 
    										{
    											s = m.replaceAll("/");
    										}
    										else
    										{
    											s = t;
    										}
     
     
    										model.addRow(new Object[]{table.getRowCount(), s, getTime( duration ), " ", f.toString()});
    									}
     
    									Object[] o = new Object[5];
    									o[0] = table.getValueAt(table.getRowCount()-1, 0);
    									o[1] = table.getValueAt(table.getRowCount()-1, 1);
    									o[2] = table.getValueAt(table.getRowCount()-1, 2);
    									o[3] = table.getValueAt(table.getRowCount()-1, 3);
    									o[4] = table.getValueAt(table.getRowCount()-1, 4);
     
    								}
    							}		
    						}
     
    						length();
     
    						dtde.dropComplete(true);
    						return;
    					} 
    					else if (flavors[i].isFlavorSerializedObjectType()) 
    					{
    						dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
    						//Object o = tr.getTransferData(flavors[i]);
    						dtde.dropComplete(true);
    						return;
    					} 
    					else if (flavors[i].isRepresentationClassInputStream()) 
    					{
    						dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
    						dtde.dropComplete(true);
    						return;
    					}
    				}
    				dtde.rejectDrop();
    			} catch (Exception e) 
    			{
    				e.printStackTrace();
    				dtde.rejectDrop();
    			}
    		}
     
     
    		class MyTableModel extends DefaultTableModel 
    		{
     
    			/**
                             * 
                             */
    			private static final long serialVersionUID = 1L;
     
     
    			public MyTableModel() 
    			{
    				super();
    			}
     
    			public MyTableModel(int rowCount, int columnCount) 
    			{
    				super(rowCount, columnCount);
    			}
     
    			public MyTableModel(Object[] columnNames, int rowCount) 
    			{
    				super(columnNames, rowCount);
    			}
     
    			public MyTableModel(Object[][] data, Object[] columnNames) 
    			{
    				super(data, columnNames);
    			}
     
    			public MyTableModel(Vector<?> columnNames, int rowCount) 
    			{
    				super(columnNames, rowCount);
    			}
     
    			public MyTableModel(Vector<?> data, Vector<?> columnNames) 
    			{
    				super(data, columnNames);
    			}
     
    			public boolean isCellEditable(int rowIndex, int columnIndex) 
    			{
    				return false;
             	}
     
     
    			/**
                             * Méthode permettant de modifier l'emplacement d'une ligne dans une
                             * JTable (codée à la va vite en utilisant les interne de
                             * DefaultTableModel ce qui n'est pas forcément top top)
                             * 
                             * @param rowIndexSrc
                             *            La ligne d'origine de l'entrée à bouger
                             * @param rowIndexDst
                             *            La ligne de destination de l'entrée à bouger
                             */
    			@SuppressWarnings("unchecked")
    			public void moveRow(int rowIndexSrc, int rowIndexDst) 
    			{
    				Vector<?> r = (Vector<?>) dataVector.get(rowIndexSrc);
    				removeRow(rowIndexSrc);
    				dataVector.add(rowIndexDst, r);
    				fireTableRowsInserted(rowIndexDst, rowIndexDst);
    			}
    		}
     
     
    		class MyTransfertHandler extends TransferHandler 
    		{
    			/**
                             * 
                             */
    			private static final long serialVersionUID = 1L;
     
    			@Override
    			public int getSourceActions(JComponent c) 
    			{
    				return TransferHandler.MOVE;
    			}
     
    			@Override
    			protected Transferable createTransferable(JComponent c) 
    			{
     
    				// on récupère la donnée qui nous intéresse (c'est a dire
    				// l'emplacement de la ligne que l'on veut bouger)
    				// Puis on l'enveloppe dans un Objet héritant de transferable. (une
    				// StringSelection en l'occurence)
    				JTable t = (JTable) c;
    				StringSelection s = new StringSelection(String.valueOf(t.getSelectedRow()));
    				return s;
    			}
     
    			public boolean canImport(TransferHandler.TransferSupport info) 
    			{
    				// pour ne gérer que le drop et pas le paste
    				if (!info.isDrop()) 
    				{
    					return false;
    				}
     
    				// On ne supporte que les chaines en entrée
    				if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) 
    				{
    					return false;
    				}
     
    				// On recherche l'emplacement du drop
    				JTable.DropLocation dl = (JTable.DropLocation) info.getDropLocation();
     
    				// On ne supporte que les emplacements de drop valides
    				return dl.getDropPoint() != null;
    			}
     
    			public boolean importData(TransferHandler.TransferSupport info) 
    			{
    				// dans le cas ou l'on ne pourrait supporter l'import
     
    				if (!canImport(info)) 
    				{
    					return false;
    				}
     
    				// On récupère l'emplacement du Drop
    				JTable.DropLocation dl = (JTable.DropLocation) info.getDropLocation();
     
    				// On récupère la ligne de destinatop du drop
    				int dstRow = dl.getRow();
     
    				// on récupère l'objet de transfert
    				Transferable trans = info.getTransferable();
     
    				// On récupère la donnée utile depuis l'objet de transfert
    				// (l'emplacement d'origine de la ligne à bouger)
    				int srcRow;
    				try 
    				{
    					srcRow = Integer.parseInt((String) trans.getTransferData(DataFlavor.stringFlavor));
    				} 
    				catch (UnsupportedFlavorException e) 
    				{
    					e.printStackTrace();
    					return false;
    				} 
    				catch (IOException e) 
    				{
    					e.printStackTrace();
    					return false;
    				}
     
    				// on effectue les modifications sur la JTable
    				JTable table = (JTable) info.getComponent();
    				MyTableModel m = (MyTableModel) table.getModel();
     
    				if (dstRow < 0) 
    				{
    					dstRow = 0;
    				}
    				if (dstRow > m.getRowCount() - 1) 
    				{
    					//dstRow = m.getRowCount() - 1;
    				}
     
    				if ( srcRow < dstRow )
    				{
    					dstRow = dstRow - 1;
    				}
     
    				m.moveRow(srcRow, dstRow);
     
    				reIndexData();
     
    				table.setRowSelectionInterval(dstRow, dstRow);
     
    				iCurrentRow = dstRow;
     
    				Object[] o = new Object[5];
    				o[0] = table.getValueAt(table.getSelectedRow(), 0);
    				o[1] = table.getValueAt(table.getSelectedRow(), 1);
    				o[2] = table.getValueAt(table.getSelectedRow(), 2);
    				o[3] = table.getValueAt(table.getSelectedRow(), 3);
    				o[4] = table.getValueAt(table.getSelectedRow(), 4);
     
    				return true;
    			} 
    		}
     
     
    		@Override
    		public void mouseClicked(MouseEvent e) 
    		{
    			iCurrentRow = table.getSelectedRow();
     
    			if (e.getClickCount() == 2) 
    			{
    				Object[] o = new Object[5];
    				o[0] = table.getValueAt(table.getSelectedRow(), 0);
    				o[1] = table.getValueAt(table.getSelectedRow(), 1);
    				o[2] = table.getValueAt(table.getSelectedRow(), 2);
    				o[3] = table.getValueAt(table.getSelectedRow(), 3);
    				o[4] = table.getValueAt(table.getSelectedRow(), 4);
     
    			}
    		}
     
     
    		@Override
    		public void mousePressed(MouseEvent e) 
    		{
    			//System.out.println("pressed");
    		}
     
     
     
    		@Override
    		public void mouseReleased(MouseEvent e) 
    		{
    			//System.out.println("released");
    		}
     
     
    		@Override
    		public void mouseEntered(MouseEvent e) 
    		{
    			//System.out.println("entered");
    		}
     
     
    		@Override
    		public void mouseExited(MouseEvent e) 
    		{
    			//System.out.println("exited");
    		}
     
     
    		@Override
    		public void keyTyped(KeyEvent e) {	}
     
     
    		@Override
    		public void keyPressed(KeyEvent e) 
    		{
    			pressed = true;
     
    			if ( pressed )
    			{
    				if ( e.getKeyCode() == 157 )
    				{	
    					keys.setSize(2);
    					keys.setElementAt(e.getKeyCode(), 0);
    				}
     
    				if ( e.getKeyCode() == 87 )
    				{
    					if ( !keys.isEmpty() )
    					{
    						try
    						{
    							if ( keys.get(0) == 157 )
    							{
    								fr.setVisible(false);
    							}
    						}
    						catch( NullPointerException npe )
    						{ }
    					}
    				}
    				pressed = false;
    			}			
    		}
     
     
    		@Override
    		public void keyReleased(KeyEvent e) 
    		{
    			pressed = false;
    			keys.clear();
    			keys.setSize(2);
    		}		
     
    	}// ---- End   PanelDropTarget
     
     
    	public class GetId3Tag
    	{
    		File file;
    		AudioFileFormat baseFileFormat = null;
    		AudioFormat baseFormat = null;
    		Map<?, ?> properties;
     
    		public GetId3Tag(String filename)
    		{
    			file = new File(filename);
     
    			try {
    				baseFileFormat = AudioSystem.getAudioFileFormat(file);
    			} catch (UnsupportedAudioFileException e) {
    				//e.printStackTrace();
    			} catch (IOException e) {
    				//e.printStackTrace();
    			}
     
    			baseFormat = baseFileFormat.getFormat();
     
    			properties = ((TAudioFileFormat)baseFileFormat).properties();
    		}
     
    		public boolean isTags()
    		{
    			if (baseFileFormat instanceof TAudioFileFormat)
    			{
    				return true;
    			}	
    			else
    			{
    				return false;
    			}
    		}
     
    		public String getTitle()
    		{  
    		    String key = "title";
    		    String title = (String) properties.get(key);
    		    return title;
    		}
     
    		public String getArtiste()
    		{
    			String key = "author";
    		    String author = (String) properties.get(key);
    		    return author;	
    		}
     
    		public Long getDuration()
    		{
    			String key = "duration";
    		    Long duration = (Long) properties.get(key);
    		    return duration;
    		}
    	}
     
     
    	public boolean isMp3File( String myMp3 )
    	{
    		boolean b = Pattern.matches("(.+?mp3?)+", myMp3);
     
    		if ( b )
    		{
    			return true;
    		}
    		else
    		{
    			return false;
    		}
    	}
     
     
    	public String getTime( Long duration )
    	{
    		int hours = hours(duration);
    		int minutes = minutes(duration);
    		int seconds = seconds(duration);
    		String minutes1 = null;
    		String seconds1 = null;
     
    		if ( hours > 0 )
    		{
    			if ( minutes < 10 )
    			{
    				minutes1 = "0"+minutes;
    			}
    			else
    			{
    				minutes1 = ""+minutes;
    			}
    		}
    		else
    		{
    			minutes1 = ""+minutes;
    		}
     
     
     
    		if ( seconds < 10 )
    		{
    			seconds1 = "0"+seconds;
    		}
    		else
    		{
    			seconds1 = ""+seconds;
    		}
     
    		if ( hours == 0 )
    		{
    			return minutes1+":"+seconds1;
    		}
    		else
    		{
    			return hours+":"+minutes1+":"+seconds1;
    		}
    	}
     
    	public int hours( float time )
    	{
    		int hours = (int) ((time/1000) / (1000*60*60));
    		return hours;
    	}
     
    	public int minutes( float time )
    	{
    		int minutes = (int) (((time/1000) % (1000*60*60)) / (1000*60));
    		return minutes;
    	}
     
    	public int seconds( float time )
    	{
    		int seconds = (int) ((((time/1000) % (1000*60*60)) % (1000*60)) / 1000);
    		return seconds;
    	}
     
     
    	public void reIndexData()
    	{
    		Vector<?> entry = model.getDataVector();
     
    		for ( int i = 0; i < entry.size(); i++)
    		{
    			table.setValueAt(i, i, 0);
    		}
    	}
     
     
     
    	/* 
    	 * ---- PURE DATA Functions
    	 */
    	public void createAndShowGUI()
    	{
    		javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                	new PanelDropTarget();
                }
    		});
    	}
     
     
    	public void displayPlaylist()
    	{
    		keys.clear();
    		keys.setSize(2);
    		pressed = false;
    		fr.setVisible(true);
    		window.toFront();
    	}
     
     
    	public void close()
    	{
    		fr.dispose();
    	}
     
     
    	public void bang() 
    	{
    		try
    		{
    			Object[] o = new Object[5];
    			o[0] = table.getValueAt(table.getSelectedRow(), 0);
    			o[1] = table.getValueAt(table.getSelectedRow(), 1);
    			o[2] = table.getValueAt(table.getSelectedRow(), 2);
    			o[3] = table.getValueAt(table.getSelectedRow(), 3);
    			o[4] = table.getValueAt(table.getSelectedRow(), 4);
    		}
    		catch (ArrayIndexOutOfBoundsException a)
    		{ 
    			if ( model.getDataVector().size() == 0 )
    			{
    			}
    			else
    			{
    			}
    		}
    	}
     
    	public void dump()
    	{
    		Vector<?> entry = model.getDataVector();
     
    		int i = 0;
     
    		try
    		{
    			do
    			{
    				@SuppressWarnings("unchecked")
    				Object[] o = ((Vector<String>) entry.get(i)).toArray();
     
    				i++;
    			}
    			while( i != entry.size() );
     
    			// -- Bang when finished reading data
    		}
    		catch (ArrayIndexOutOfBoundsException a)
    		{ 
    		}
    	}
     
     
    	public void select(float index)
    	{
    		try
    		{
    			Vector<?> entry = model.getDataVector();
     
    			iCurrentRow = (int) index;
     
    			table.setRowSelectionInterval(iCurrentRow, iCurrentRow);
     
    			Object[] o = ((Vector<String>) entry.get(iCurrentRow)).toArray();
     
    		}
    		catch (IllegalArgumentException i)
    		{ 
    			if ( model.getDataVector().size() == 0 )
    			{
    			}
    			else
    			{
    			}
    		}
    	}
     
     
    	public void next()
    	{
    		try
    		{
    			Vector<?> entry = model.getDataVector();
     
    			iCurrentRow = (iCurrentRow + 1) % entry.size();
     
    			Object[] o = ((Vector<String>) entry.get(iCurrentRow)).toArray();
     
     
    			table.setRowSelectionInterval(iCurrentRow, iCurrentRow);
    		}
    		catch (ArithmeticException a)
    		{ 
    		}
    	}
     
    	public void prev()
    	{
    		try
    		{
    			Vector<?> entry = model.getDataVector();
     
    			iCurrentRow = (iCurrentRow - 1 + entry.size()) % entry.size();
     
    			System.out.println(iCurrentRow);
     
    			Object[] o = ((Vector<String>) entry.get(iCurrentRow)).toArray();
     
    			table.setRowSelectionInterval(iCurrentRow, iCurrentRow);
    		}
    		catch (ArithmeticException a)
    		{ 
    		}
    	}
     
    	public void help()
    	{
    		URL path = getClass().getProtectionDomain().getCodeSource().getLocation();
     
    		Pattern p = Pattern.compile("^file:");
    		Matcher m = p.matcher(path.toString());
     
    		String t = null;
     
    		t = m.replaceAll("");
     
    		File file = new File(t + "../JTableDnDPanelPD-help.pd");
     
    		Desktop desktop = Desktop.getDesktop();
    		try 
    		{
    			desktop.open(file);
    		} 
    		catch (IOException e) 
    		{
    			e.printStackTrace();
    		}
    	}
     
    	public void javaSource()
    	{
    		URL path = getClass().getProtectionDomain().getCodeSource().getLocation();
     
    		Pattern p = Pattern.compile("^file:");
    		Matcher m = p.matcher(path.toString());
     
    		String t = null;
     
    		t = m.replaceAll("");
     
    		File file = new File(t + "JTableDnDPanelPD.java");
     
    		Desktop desktop = Desktop.getDesktop();
    		try 
    		{
    			desktop.open(file);
    		} 
    		catch (IOException e) 
    		{
    			e.printStackTrace();
    		}
    	}
     
     
    	public float length()
    	{
    		float length = (float) model.getDataVector().size();
    		return length;
    	}
     
    	public static void main(String args[]) 
    	{
    		new JTableDnDPanel();
    	}
    }

  2. #2
    Candidat au Club
    Profil pro
    Inscrit en
    Février 2011
    Messages
    3
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2011
    Messages : 3
    Par défaut Problème résolu
    Bonjour,

    Pour ceux que ça intéresse, voici une réponse au problème que j'ai soulevé ci-dessus.

    Effectivement, il y a "conflit" entre le DropTargetListener et le TransferHandler.
    La solution est donc toute simple, il suffit de n'utiliser que le TransferHandler.

    Voici un exemple, peut-être pas super optimisé, mais cela fonctionne.
    Dans cet exemple il vous est possible de :
    - glisser/déposer un ou des fichiers, ou un dossier sur le tableau pour le remplir
    - de déplacer les lignes pour les ranger
    - de sélectionner un intervalle de lignes pour leur suppression à l'aide de la touche backspace
    - de double cliquer sur une ligne pour en sortir le contenu

    La seule contrainte est que seul les fichiers .mp3 sont acceptés.

    Julien


    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
     
     
    import java.io.File;
    import java.io.IOException;
     
    import java.util.List;
    import java.util.Vector;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
     
    import java.awt.Window;
    import java.awt.datatransfer.*;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.WindowEvent;
     
    import javax.swing.*;
    import javax.swing.TransferHandler.TransferSupport;
    import javax.swing.table.*;
     
    public class exampleDnDJTable extends JComponent implements MouseListener, KeyListener {
     
    	private static final long serialVersionUID = 1L;
     
    	private Vector<String> stuff1 = new Vector<String>();
     
    	private JFrame fr = null;
     
    	private JTable table;
     
    	private DefaultTableModel model;
     
    	private int count = 0;
     
    	private String[][] data;
     
    	private Window window;
     
    	private int iCurrentRow = 0;
     
    	// ----- Key Events
    	private Vector<Integer> keys = new Vector<Integer>(2);
    	private boolean pressed = false;
     
     
    	public exampleDnDJTable() {
     
    		data = new String[stuff1.size()][3];
     
    		count = 0;
    		for (int i = 0; i < stuff1.size(); i++) {
    			StringBuffer result = new StringBuffer();
    			result.append(i);
    			data[i][0] = result.toString();
    			data[i][1] = stuff1.get(i);
    			data[i][2] = " ";
    			count++;
    		}
     
    		String[] columnNames = new String[] { "Index", "Name", "Duration", "Artist", "Path" };
    		model = new MyTableModel(data, columnNames);
     
    		table = new JTable(model);
     
    		TableCellRenderer ctcr = table.getCellRenderer(0, 0);
    		DefaultTableCellRenderer rendererRight = (DefaultTableCellRenderer) ctcr;
    		rendererRight.setHorizontalAlignment(JLabel.RIGHT);
     
    		table.setRowSelectionAllowed(true);
    		table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);// SINGLE_SELECTION
    		/*
    		 * DROP MODES DropMode.USE_SELECTION DropMode.ON DropMode.INSERT
    		 * DropMode.INSERT_ROWS DropMode.INSERT_COLS DropMode.ON_OR_INSERT
    		 * DropMode.ON_OR_INSERT_ROWS DropMode.ON_OR_INSERT_COLS
    		 */
     
    		table.setDropMode(DropMode.INSERT_ROWS);
    		table.setDragEnabled(true);
    		table.setOpaque(false);
    		table.setFillsViewportHeight(true);
     
    		table.setTransferHandler(new MyTransfertHandler());
     
    		table.addMouseListener(this);
    		table.addKeyListener(this);
     
    		TableColumn colIndex = table.getColumnModel().getColumn(0);
    		colIndex.setPreferredWidth(50);
     
    		TableColumn colName = table.getColumnModel().getColumn(1);
    		colName.setPreferredWidth(260);
     
    		JScrollPane scrollPane = new JScrollPane(table);
     
    		fr = new JFrame("Playlist");
     
    		window = new Window(fr);
    		window.addKeyListener(this);
     
    		fr.pack();
    		fr.setSize(630, 550);
    		fr.setLocationRelativeTo(null);
    		fr.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    		fr.setVisible(true);
     
    		fr.getContentPane().add(scrollPane);
    	}
     
    	protected void processWindowEvent(WindowEvent e) {
    		System.out.println(e);
    	}
     
    	class MyTableModel extends DefaultTableModel {
     
    		private static final long serialVersionUID = 1L;
     
    		public MyTableModel() {
    			super();
    		}
     
    		public MyTableModel(int rowCount, int columnCount) {
    			super(rowCount, columnCount);
    		}
     
    		public MyTableModel(Object[] columnNames, int rowCount) {
    			super(columnNames, rowCount);
    		}
     
    		public MyTableModel(Object[][] data, Object[] columnNames) {
    			super(data, columnNames);
    		}
     
    		public MyTableModel(Vector<?> columnNames, int rowCount) {
    			super(columnNames, rowCount);
    		}
     
    		public MyTableModel(Vector<?> data, Vector<?> columnNames) {
    			super(data, columnNames);
    		}
     
    		public boolean isCellEditable(int rowIndex, int columnIndex) {
    			return false;
    		}
     
    		/**
                     * Méthode permettant de modifier l'emplacement d'une ligne dans une
                     * JTable (codée à la va vite en utilisant les interne de
                     * DefaultTableModel ce qui n'est pas forcément top top)
                     * 
                     * @param rowIndexSrc
                     *            La ligne d'origine de l'entrée à bouger
                     * @param rowIndexDst
                     *            La ligne de destination de l'entrée à bouger
                     */
    		@SuppressWarnings("unchecked")
    		public void moveRow(int rowIndexSrc, int rowIndexDst) 
    		{
    			Vector<?> r = (Vector<?>) dataVector.get(rowIndexSrc);
    			removeRow(rowIndexSrc);
    			dataVector.add(rowIndexDst, r);
    			fireTableRowsInserted(rowIndexDst, rowIndexDst);
    		}
    	}
     
    	class MyTransfertHandler extends TransferHandler 
    	{
    		private static final long serialVersionUID = 1L;
     
    		@Override
    		public int getSourceActions(JComponent c) {
    			return TransferHandler.MOVE;
    		}
     
    		@Override
    		protected Transferable createTransferable(JComponent c) {
     
    			// on récupère la donnée qui nous intéresse (c'est a dire
    			// l'emplacement de la ligne que l'on veut bouger)
    			// Puis on l'enveloppe dans un Objet héritant de transferable.
    			// (une
    			// StringSelection en l'occurence)
    			JTable t = (JTable) c;
    			StringSelection s = new StringSelection(String.valueOf(t.getSelectedRow()));
    			return s;
    		}
     
    		public boolean canImport(TransferHandler.TransferSupport info) {
    			// pour ne gérer que le drop et pas le paste
    			if (!info.isDrop()) {
    				return false;
    			}
     
    			// On ne supporte que les chaines en entrée
    			if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
    				return true;
    			}
     
    			// On recherche l'emplacement du drop
    			JTable.DropLocation dl = (JTable.DropLocation) info.getDropLocation();
     
    			// On ne supporte que les emplacements de drop valides
    			return dl.getDropPoint() != null;
    		}
     
    		public boolean importData(TransferHandler.TransferSupport info) {
    			// dans le cas ou l'on ne pourrait supporter l'import
     
    			if (!canImport(info)) 
    			{
    				return false;
    			}
     
    			// On récupère l'emplacement du Drop
    			JTable.DropLocation dl = (JTable.DropLocation) info.getDropLocation();
     
    			// On récupère la ligne de destinatop du drop
    			int dstRow = dl.getRow();
     
    			// on récupère l'objet de transfert
    			Transferable trans = info.getTransferable();
     
    			// On récupère la donnée utile depuis l'objet de transfert
    			// (l'emplacement d'origine de la ligne à bouger)
    			int srcRow;
     
    			try {
    				srcRow = Integer.parseInt((String) trans.getTransferData(DataFlavor.stringFlavor));
    			} 
    			catch (UnsupportedFlavorException e) 
    			{
    				// ---------------------------
    				// Si les données ne sont pas supportées, alors l'objet vient de l'exptérieure de la JTable.
    				// On effectue alors le glisser / déplacer
    				// ---------------------------
    				drop(info);
     
    				return false;
    			} 
    			catch (IOException e) 
    			{
    				e.printStackTrace();
    				return false;
    			}
     
    			// on effectue les modifications sur la JTable
    			JTable table = (JTable) info.getComponent();
    			MyTableModel m = (MyTableModel) table.getModel();
     
    			if (dstRow < 0) 
    			{
    				dstRow = 0;
    			}
     
    			if (srcRow < dstRow) 
    			{
    				dstRow = dstRow - 1;
    			}
     
    			m.moveRow(srcRow, dstRow);
     
    			reIndexData();
     
    			table.setRowSelectionInterval(dstRow, dstRow);
     
    			iCurrentRow = dstRow;
     
    			Object[] o = new Object[5];
    			o[0] = table.getValueAt(table.getSelectedRow(), 0);
    			o[1] = table.getValueAt(table.getSelectedRow(), 1);
    			o[2] = table.getValueAt(table.getSelectedRow(), 2);
    			o[3] = table.getValueAt(table.getSelectedRow(), 3);
    			o[4] = table.getValueAt(table.getSelectedRow(), 4);
     
    			return true;
    		}
    	}
     
    	public void drop(TransferSupport dtde)
    	{
    		try {
    			Transferable tr = dtde.getTransferable();
    			DataFlavor[] flavors = tr.getTransferDataFlavors();
     
    			for (int i = 0; i < flavors.length; i++) 
    			{
    				if (flavors[i].isFlavorJavaFileListType()) 
    				{
     
    					List<?> list = (List<?>) tr.getTransferData(flavors[i]);
     
    					JFileChooser chooser = new JFileChooser();
     
    					for (int j = 0; j < list.size(); j++) 
    					{
    						StringBuffer result = new StringBuffer();
    						result.append(list.get(j));
    						File f = new File(result.toString());
     
    						File[] a = f.listFiles();
     
    						String fileTypeName = chooser.getTypeDescription(f);
     
    						if ((fileTypeName.compareTo("Directory") == 0) || (fileTypeName.compareTo("Répertoire") == 0)) 
    						{
    							for (int k = 0; k < a.length; k++) 
    							{
    								stuff1.add(a[k].toString());
     
    								if (isMp3File(a[k].toString())) 
    								{
    									Pattern p = Pattern.compile("([^/]+?).(mp3?)");
    									Matcher m = p.matcher(a[k].toString());
     
    									String t = null;
     
    									while (m.find()) 
    									{
    										t = m.group(1);
    									}
     
    									p = Pattern.compile(":");
    									m = p.matcher(t);
     
    									String s = null;
     
    									if (m.find()) 
    									{
    										s = m.replaceAll("/");
    									} 
    									else 
    									{
    										s = t;
    									}
     
    									model.addRow(new Object[] {table.getRowCount(), s, " ", " ", a[k].toString() });
     
     
    									Object[] o = new Object[5];
    									o[0] = table.getValueAt(table.getRowCount() - 1, 0);
    									o[1] = table.getValueAt(table.getRowCount() - 1, 1);
    									o[2] = table.getValueAt(table.getRowCount() - 1, 2);
    									o[3] = table.getValueAt(table.getRowCount() - 1, 3);
    									o[4] = table.getValueAt(table.getRowCount() - 1, 4);
    								}
    							}
    						} 
    						else 
    						{
    							stuff1.add(f.toString());
     
    							if (isMp3File(f.toString())) 
    							{
    								Pattern p = Pattern.compile("([^/]+?).(mp3?)");
    								Matcher m = p.matcher(f.toString());
     
    								String t = null;
     
    								while (m.find()) 
    								{
    									t = m.group(1);
    								}
     
    								p = Pattern.compile(":");
    								m = p.matcher(t);
     
    								String s = null;
     
    								if (m.find()) 
    								{
    									s = m.replaceAll("/");
    								} 
    								else 
    								{
    									s = t;
    								}
     
    								model.addRow(new Object[] { table.getRowCount(), s, " ", " ", f.toString() });
     
     
    								Object[] o = new Object[5];
    								o[0] = table.getValueAt( table.getRowCount() - 1, 0);
    								o[1] = table.getValueAt( table.getRowCount() - 1, 1);
    								o[2] = table.getValueAt( table.getRowCount() - 1, 2);
    								o[3] = table.getValueAt( table.getRowCount() - 1, 3);
    								o[4] = table.getValueAt( table.getRowCount() - 1, 4);
    							}
    						}
    					}
     
    					length();
     
    					return;
    				} 
    				else if (flavors[i].isFlavorSerializedObjectType()) 
    				{
    					return;
    				} 
    				else if (flavors[i].isRepresentationClassInputStream()) 
    				{
    					// Utilisé sur les plateformes Linux
    					return;
    				}
    			}
    		} catch (Exception e) 
    		{
    			e.printStackTrace();
    		}
    	}
     
    	@Override
    	public void mouseClicked(MouseEvent e) 
    	{
    		// Permet d'obtenir les données de la ligne sélectionnée à l'aide d'un double clic de souris
    		iCurrentRow = table.getSelectedRow();
     
    		if (e.getClickCount() == 2) {
    			Object[] o = new Object[5];
    			o[0] = table.getValueAt(table.getSelectedRow(), 0);
    			o[1] = table.getValueAt(table.getSelectedRow(), 1);
    			o[2] = table.getValueAt(table.getSelectedRow(), 2);
    			o[3] = table.getValueAt(table.getSelectedRow(), 3);
    			o[4] = table.getValueAt(table.getSelectedRow(), 4);
     
    			System.out.println(o[0] + " " + o[1] + " " + o[2] + " " + o[3] + " " + o[4] + " " );
    		}
    	}
     
    	@Override
    	public void mousePressed(MouseEvent e) {
    		// System.out.println("pressed");
    	}
     
    	@Override
    	public void mouseReleased(MouseEvent e) {
    		// System.out.println("released");
    	}
     
    	@Override
    	public void mouseEntered(MouseEvent e) {
    		// System.out.println("entered");
    	}
     
    	@Override
    	public void mouseExited(MouseEvent e) {
    		// System.out.println("exited");
    	}
     
    	@Override
    	public void keyTyped(KeyEvent e) {
    	}
     
    	@Override
    	public void keyPressed(KeyEvent e) {
    		pressed = true;
     
    		//System.out.println(e.getKeyCode());
     
    		if (pressed) {
    			if (e.getKeyCode() == 157) 
    			{
    				keys.setSize(2);
    				keys.setElementAt(e.getKeyCode(), 0);
    			}
     
    			if (e.getKeyCode() == 87) 
    			{
    				if (!keys.isEmpty()) 
    				{
    					try {
    						if (keys.get(0) == 157) 
    						{
    							fr.setVisible(false);
    						}
    					} 
    					catch (NullPointerException npe) 
    					{
    					}
    				}
    			}
     
     
    			// Supprime les lignes sélectionnées
    			if ( e.getKeyCode() == 8 )
    			{
    				if ( table.getSelectedRow() != -1 )
    				{
    					int lastRow = (table.getSelectedRow() + table.getSelectedRows().length) - 1 ;
    					iCurrentRow = table.getSelectedRow() - 1;
     
    					for (int i = lastRow; i > iCurrentRow; i--)
    					{
    						model.removeRow(i);
    					}
     
    					reIndexData();
     
    					if ( iCurrentRow > 0 )
    					{
    						table.setRowSelectionInterval(iCurrentRow, iCurrentRow);
    					}
    					else if ( table.getRowCount() > 0 )
    					{
    						table.setRowSelectionInterval(0, 0);
    					}
    				}
    			}
     
    			pressed = false;
    		}
    	}
     
    	@Override
    	public void keyReleased(KeyEvent e) {
    		pressed = false;
    		keys.clear();
    		keys.setSize(2);
    	}
     
    	public boolean isMp3File(String myMp3) {
    		boolean b = Pattern.matches("(.+?mp3?)+", myMp3);
     
    		if (b) 
    		{
    			return true;
    		} 
    		else 
    		{
    			return false;
    		}
    	}
     
    	public void reIndexData() {
    		Vector<?> entry = model.getDataVector();
     
    		for (int i = 0; i < entry.size(); i++) 
    		{
    			table.setValueAt(i, i, 0);
    		}
    	}
     
    	public float length() {
    		float length = (float) model.getDataVector().size();
    		return length;
    	}
     
    	public static void main(String args[]) {
    		javax.swing.SwingUtilities.invokeLater(new Runnable() {
    			public void run() {
    				new exampleDnDJTable();
    			}
    		});
    	}
    }

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Drag and Drop avec Jtable
    Par hoziris dans le forum Composants
    Réponses: 0
    Dernier message: 11/04/2012, 15h53
  2. Drag and Drop entre JTable
    Par Polux000 dans le forum Composants
    Réponses: 0
    Dernier message: 04/12/2008, 10h03
  3. drag and drop jtable -> jtree
    Par roico dans le forum Composants
    Réponses: 1
    Dernier message: 16/11/2007, 10h14
  4. Drag n drop JTable -> JTree
    Par KeKeMaN dans le forum Composants
    Réponses: 6
    Dernier message: 14/05/2007, 15h50

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo