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

Format d'échange (XML, JSON...) Java Discussion :

Page Sources Java libres - participez ici [Sources]


Sujet :

Format d'échange (XML, JSON...) Java

  1. #101
    Futur Membre du Club
    Homme Profil pro
    Analyste cogniticien
    Inscrit en
    Décembre 2004
    Messages
    7
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Morbihan (Bretagne)

    Informations professionnelles :
    Activité : Analyste cogniticien
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Décembre 2004
    Messages : 7
    Points : 9
    Points
    9
    Par défaut problème utilisation classes fournies
    Citation Envoyé par Razgriz Voir le message
    Voici un dernier encrypteur (je commence à faire ch*** avec mes encrypteurs je sais lol), qui utilise cette fois un chifrement non-symétrique, et qui est également très performant. L'inconvéniant d'un tel algorithme (non symétrique) est qu'il possède une complexité assez élevée (i.e. il va tourner beaucoup plus lentement pour de grandes quantités de données qu'un algorihme symétrique), et donc qu'il est peu pratique à utilsier dans ce cas, mais une petite asctuce permet de s'en sortir facilement de combinaisaond e cryptage symétriques et non symétriques permet d'utiliser efficacement l'algorithme.

    J'utilise pour l'encrypteur suivant l'algorithme RSA, inventé par Rivest, Shamir et Eddleman.

    [EDIT]
    Dernière mise à jour le 16/10/2007 (modélisatio et sécurité). Vous avez besoin des classes FileEncryptor et CipherEcryptor pour la faire fonctionner.
    [/EDIT]

    Le voici :

    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
     
    /*
     * RSAEncryptor.java
     *
     * Created on 17 juin 2006, 15:58
     * 
     */
     
    package org.cosmopol.crypto;
     
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.OutputStream;
    import java.security.InvalidKeyException;
    import java.security.Key;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.NoSuchAlgorithmException;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.SecureRandom;
    import java.util.ArrayList;
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.ShortBufferException;
    import javax.crypto.BadPaddingException;
     
    /**
     * This class provides methods to generate keys, encrypt or decrypt files and
     * streams with the RSA crypting algorithm.
     * @author Absil Romain
     */
    public class RSAEncryptor extends FileEncryptor
    {
        private Key publicKey;
        private Key privateKey;
        private boolean isEncryptInitialized;
        private boolean isDecryptInitialized;
     
        /**
         * Constructs a new RSA encryptor with the specified file containing one 
         * of the keys, in encrypt or decrypt mode (depends on the type of stored
         * key, if the key is public, then the encryptor is in encrypt mode,
         * otherwise it is in decrypt mode.
         * @param keyFileName the name of the file containing a RSA key.
         * @throws java.io.FileNotFoundException if the file containing the key doesn't
         * exist.
         * @throws java.io.IOException if an error occurs during reading the file 
         * containing the key.
         * @throws java.lang.ClassNotFoundException if the class of the key is unknown.
         * @throws java.security.InvalidKeyException is the stored key is not a valid type of key.
         */
        public RSAEncryptor(String keyFileName) 
            throws FileNotFoundException, IOException, ClassNotFoundException, 
                InvalidKeyException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(keyFileName));
            Object key = keyIn.readObject();
            keyIn.close();
     
            if(key instanceof PublicKey)
            {
                publicKey = (Key)key;
                isEncryptInitialized = true;
            }
            else if(key instanceof PrivateKey)
            {
                privateKey = (Key)key;
                isDecryptInitialized = true;
            }
            else
                throw new InvalidKeyException("The file does not contain a " +
                        "valid key");
        }
     
        /**
         * Constructs a new RSA encryptor with the specified file containing one 
         * of the keys, in encrypt or decrypt mode (depends on the type of stored
         * key, if the key is public, then the encryptor is in encrypt mode,
         * otherwise it is in decrypt mode.
         * @param keyFile the file containing a RSA key.
         * @throws java.io.FileNotFoundException if the file containing the key doesn't
         * exist.
         * @throws java.io.IOException if an error occurs during reading the file 
         * containing the key.
         * @throws java.lang.ClassNotFoundException if the class of the key is unknown.
         * @throws java.security.InvalidKeyException is the stored key is not a valid type of key.
         */
        public RSAEncryptor(File keyFile) 
            throws FileNotFoundException, IOException, ClassNotFoundException, InvalidKeyException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(keyFile));
            Object key = keyIn.readObject();
            keyIn.close();
     
            if(key instanceof PublicKey)
            {
                publicKey = (Key)key;
                isEncryptInitialized = true;
            }
            else if(key instanceof PrivateKey)
            {
                privateKey = (Key)key;
                isDecryptInitialized = true;
            }
            else
                throw new InvalidKeyException("The file does not contain a " +
                        "valid key");
        }
     
        /**
         * Constructs a new RSA encryptor in encrypt mode with the specified
         * public key.
         * @param key the public key (used to encrypt files and streams).
         **/
        public RSAEncryptor(PublicKey key)
        {
            this.publicKey = key;
            this.isEncryptInitialized = true;
        }
     
        /**
         * Constructs a new RSA encryptor in decrypt mode with the specified
         * private key.
         * @param key the private key (used to decrypt files and streams).
         **/
        public RSAEncryptor(PrivateKey key)
        {
            this.privateKey = key;
            this.isDecryptInitialized = true;
        }
     
        /**
         * Constructs a new RSA encryptor in encrypt and decrypt mode with the
         * specified files containing the public and private key.
         * @param publicKeyFileName the name of the file containing the public key.
         * @param privateKeyFileName the name of the file containing the private key.
         * @throws java.io.FileNotFoundException if one of the files containing a key 
         * doen't exist.
         * @throws java.io.IOException if an error occurs during reading one of the keys.
         * @throws java.lang.ClassNotFoundException if one of the class of the keys is
         * unknown.
         * @throws java.security.InvalidKeyException if the files containing the keys don't
         * contain valid keys.
         */
        public RSAEncryptor(String publicKeyFileName, String privateKeyFileName) 
            throws FileNotFoundException, IOException, ClassNotFoundException,
                InvalidKeyException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(publicKeyFileName));
            Object puKey = keyIn.readObject();
            keyIn.close();
     
            keyIn = new ObjectInputStream(
                    new FileInputStream(privateKeyFileName));
            Object prKey = keyIn.readObject();
            keyIn.close();
     
            if(puKey instanceof PublicKey && prKey instanceof PrivateKey)
            {
                this.publicKey = (Key)puKey;
                this.isEncryptInitialized = true;
                this.privateKey = (Key)prKey;
                this.isDecryptInitialized = true;
            }
            else
                throw new InvalidKeyException("Some of the files don't contains" +
                        " a valid key");
        }
     
        /**
         * Constructs a new RSA encryptor in encrypt and decrypt mode with the
         * specified files containing the public and private key.
         * @param publicKeyFile the file containing the public key.
         * @param privateKeyFile the file containing the private key.
         * @throws java.io.FileNotFoundException if one of the files containing a key 
         * doen't exist.
         * @throws java.io.IOException if an error occurs during reading one of the keys.
         * @throws java.lang.ClassNotFoundException if one of the class of the keys is
         * unknown.
         */
        public RSAEncryptor(File publicKeyFile, File privateKeyFile) 
            throws FileNotFoundException, IOException, ClassNotFoundException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(publicKeyFile));
            this.publicKey = (Key) keyIn.readObject();
            this.isEncryptInitialized = true;
            keyIn.close();
     
            keyIn = new ObjectInputStream(
                    new FileInputStream(privateKeyFile));
            this.privateKey = (Key) keyIn.readObject();
            this.isDecryptInitialized = true;
            keyIn.close();
        }
     
        /**
         * Construct a new RSA encryptor in encrypt and decrypt mode with the
         * specified public and private key.
         * @param publicKey the public key (used to encrypt files and streams).
         * @param privateKey the private key (used to decrypt files and streams).
         **/
        public RSAEncryptor(PublicKey publicKey, PrivateKey privateKey)
        {
            this.publicKey = publicKey;
            this.isEncryptInitialized = true;
            this.privateKey = privateKey;
            this.isDecryptInitialized = true;
        }
     
        /**
         * Construct a new RSA encryptor in encrypt and decrypt mode with the
         * specified pair of keys.
         * @param keyPair the pair of keys used to encrypt and decrypt files and
         * streams.
         **/
        public RSAEncryptor(KeyPair keyPair)
        {
            this(keyPair.getPublic(), keyPair.getPrivate());
        }
     
        /**
         * Returns the public key of the underlying encryptor.
         * @return the public key of the underlying encryptor.
         **/
        public PublicKey getPublicKey()
        {
            return (PublicKey) publicKey;
        }
     
        /**
         * Sets the public key of the underlying encryptor.
         * @param key the public key to set.
         **/
        public void setPublicKey(PublicKey key)
        {
            this.publicKey = key;
        }
     
        /**
         * Returns the private key of the underlying encryptor.
         * @return the private key of the underlying encryptor.
         **/
        public PrivateKey getPrivateKey()
        {
            return (PrivateKey) privateKey;
        }
     
        /**
         * Returns a new instance of RSAEncryptor with the specified size for
         * generated keys.
         * @param size the size of the generated keys.
         * @return a new instance of RSAEncryptor.
         **/
        public static RSAEncryptor getInstance(int size)
        {
            return new RSAEncryptor(generateKeys(size));
        }
     
        /**
         * Returns a new instance of RSAEncryptor with the specified size for
         * generated keys and writes them into the specified files.
         * @return a new instance of RSAEncryptor.
         * @param size the size of the generated keys.
         * @param publicKeyFileName the name of the file in wich youw ant to write
         * the public key.
         * @param privateKeyFileName the name of the file in wich youw ant to write
         * the private key.
         * @throws java.io.IOException if an error occurs during writing one of the keys.
         */
        public static RSAEncryptor getInstance(int size, String publicKeyFileName,
                String privateKeyFileName) throws IOException
        {
            return new RSAEncryptor(generateAndSaveKeys(size, publicKeyFileName, privateKeyFileName));
        }
     
        /**
         * Returns a new instance of RSAEncryptor with the specified size for
         * generated keys and writes them into the specified files.
         * @return a new instance of RSAEncryptor.
         * @param size the size of the generated keys.
         * @param publicKeyFile the file in wich youw ant to write the public key.
         * @param privateKeyFile the file in wich youw ant to write the private key.
         * @throws java.io.IOException if an error occurs during writing one of the keys.
         */
        public static RSAEncryptor getInstance(int size, File publicKeyFile, 
                File privateKeyFile) throws IOException
        {
            return new RSAEncryptor(generateAndSaveKeys(size, publicKeyFile, privateKeyFile));
        }
     
        /**
         * Returns a pair of keys generated with the specified size.
         * @return a pair of keys generated with the specified size.
         * @param size the size of the generated key.
         */
        public static KeyPair generateKeys(int size)
        {
            KeyPairGenerator pairgen = null;
            try
            {
                pairgen = KeyPairGenerator.getInstance("RSA");
            } 
            catch (NoSuchAlgorithmException ex)//never launched
            {
                ex.printStackTrace();
            }
            SecureRandom random = new SecureRandom();
            pairgen.initialize(size, random);
            KeyPair keyPair = pairgen.generateKeyPair();
            return keyPair;
        }
     
        /**
         * Returns a pair of keys generated with the specified size and writes 
         * them into the specified files.
         * @param size the size of the generated keys.
         * @param publicKeyFileName the name of the file in wich youw ant to write
         * the public key.
         * @param privateKeyFileName the name of the file in wich youw ant to write
         * the private key.
         * @return a pair of keys with the specified size.
         * @throws java.io.IOException if an error occurs during writing the keys.
         **/
        public static KeyPair generateAndSaveKeys(int size, String publicKeyFileName, 
                String privateKeyFileName) throws IOException
        {
            return generateAndSaveKeys(size, new File(publicKeyFileName), new File(privateKeyFileName));
        }
     
        /**
         * Returns a pair of keys generated with the specified size and writes 
         * them into the specified files.
         * @param size the size of the generated keys.
         * @param publicKeyFile the file in wich you want to write the public key.
         * @param privateKeyFile the file in wich you want to write the private key.
         * @return a pair of keys with the specified size.
         * @throws java.io.IOException if an error occurs during writing the keys.
         **/
        public static KeyPair generateAndSaveKeys(int size, File publicKeyFile, 
                File privateKeyFile) throws IOException
        {
            KeyPair keyPair = generateKeys(size);
     
            ObjectOutputStream out = new ObjectOutputStream(
                    new FileOutputStream(publicKeyFile));
            out.writeObject(keyPair.getPublic());
            out.close();
     
            out = new ObjectOutputStream(
                    new FileOutputStream(privateKeyFile));
            out.writeObject(keyPair.getPrivate());
            out.close();
     
            return keyPair;
        }
     
        /**
         * Encrypts the specified input stream to the specified output stream.
         * 
         * @param in the stream to encrypt.
         * @param out the stream where you want to write the encrypted stream.
         * @throws java.io.IOException if an error occurs during writing encrypted
         * datas.
         * @throws java.security.InvalidKeyException if the key is not valid for
         * this type of operation.
         */
        public void encryptStream(InputStream in, OutputStream out) 
            throws InvalidKeyException, IOException
        {
            if(!this.isEncryptInitialized)
                throw new IllegalStateException("The underlying encryptor is not" +
                        " initialized in encrypt mode. You must specify a " +
                        "public key.");
            KeyGenerator keygen = null;
            Cipher cipherRsa = null;
            Cipher cipherAes= null;
            try
            {
                keygen = KeyGenerator.getInstance("AES");
                cipherRsa = Cipher.getInstance("RSA");
                cipherAes = Cipher.getInstance("AES");
            }
            catch(NoSuchAlgorithmException e)//never launched
            {
                e.printStackTrace();
            }
            catch(NoSuchPaddingException e)
            {
                e.printStackTrace();
            }
            SecureRandom random = new SecureRandom();
            keygen.init(random);
            SecretKey key = keygen.generateKey();
     
            cipherRsa.init(Cipher.WRAP_MODE, publicKey);
            byte[] wrappedKey = null;
            try
            {
                wrappedKey = cipherRsa.wrap(key);
            } 
            catch (InvalidKeyException ex)
            {
                ex.printStackTrace();
            } 
            catch (IllegalBlockSizeException ex)
            {
                ex.printStackTrace();
            }
     
            Integer length = wrappedKey.length;
            DataOutputStream writer = new DataOutputStream(out);
            writer.writeInt(length);
            writer.write(wrappedKey);
     
            cipherAes.init(Cipher.ENCRYPT_MODE, key);
            super.crypt(in, writer, cipherAes);
    //        in.close();
    //        out.close();
            //writer.close();
        }
     
        /**
         * Decrypts the specified input stream to the specified output stream.
         * @param in the stream to decrypt.
         * @param out the stream where you want to write the decrypted stream.
         * @throws java.io.IOException if an error occurs during writing encrypted
         * datas.
         * @throws java.security.InvalidKeyException if the key is not valid for
         * this type of operation.
         */
        public void decryptStream(InputStream in, OutputStream out) 
            throws IOException, InvalidKeyException
        {
            if(!this.isEncryptInitialized)
                throw new IllegalStateException("The underlying encryptor is not" +
                        " initialized in decrypt mode. You must specify a " +
                        "private key.");
            DataInputStream reader = new DataInputStream(in);
            int length = reader.readInt();
            byte[] wrappedKey = new byte[length];
            in.read(wrappedKey, 0, length);
            Cipher cipherRsa = null;
            Cipher cipherAes = null;
            Key key = null;
            try
            {
                cipherRsa = Cipher.getInstance("RSA");
                cipherAes = Cipher.getInstance("AES");
                cipherRsa.init(Cipher.UNWRAP_MODE, privateKey); 
                key = cipherRsa.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
            }
            catch(NoSuchAlgorithmException e)//never thrown
            {
                e.printStackTrace();
            }
            catch(NoSuchPaddingException e)
            {
                e.printStackTrace();
            }
     
            cipherAes.init(Cipher.DECRYPT_MODE, key);
     
            super.crypt(reader, out, cipherAes);
    //        in.close();
    //        out.close();
            //reader.close();
        }
     
    }
    j'ai tout essayé pour décrypter et me récupère systématiquement:

    The underlying encryptor is not initialized in decrypt mode. You must specify a private key.
    Fichiers attachés Fichiers attachés
      0  0

  2. #102
    Membre averti Avatar de Razgriz
    Profil pro
    Professeur / chercheur en informatique / mathématiques
    Inscrit en
    Avril 2006
    Messages
    391
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Professeur / chercheur en informatique / mathématiques

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Points : 306
    Points
    306
    Par défaut
    Il y a une erreur dans mon code, mais elle crève les yeux ;-)

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    public void decryptStream(InputStream in, OutputStream out) 
            throws IOException, InvalidKeyException
        {
            if(!this.isEncryptInitialized)
                  //blabla
        }
    A changer par :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    public void decryptStream(InputStream in, OutputStream out) 
            throws IOException, InvalidKeyException
        {
            if(!this.isDecryptInitialized)
                  //blabla
        }
    Les classes postées ici ne sont peut-être pas les dernières versions existantes. Mais tout au plus ellent souffrent de défauts bidons tels que celui-là. Erreurs de copier/coller en refactoring :s
    On a toujours besoin d'un plus bourrin que soi

    Oui il y a quelques bugs dans ma librairie de Sécurité, mais les classes postées ne sont pas celles de la dernière version, et j'ai la flemme de tout modifier. Je vous donnerai avec plaisir la dernière version du jar par mp.
      0  0

  3. #103
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2009
    Messages
    22
    Détails du profil
    Informations personnelles :
    Localisation : Royaume-Uni

    Informations forums :
    Inscription : Décembre 2009
    Messages : 22
    Points : 26
    Points
    26
    Par défaut
    Voici une source permettant de creer une "etched border" ayant le nombre de cotes que l'on veut.

    (les constructeurs pour une border a plus d'un cote sont un peu rebarbatif, si quelqu'un a une meilleure idee je suis preneuse!)

    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
     
     
    /*
     * SidedEtchedBorder.java
     *
     * Created on 18-Mar-2010
     */
    package my.util.ui.border;
     
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Insets;
     
    import javax.swing.SwingConstants;
    import javax.swing.border.EtchedBorder;
     
    /**
     * This class creates an etched border that can be one,
     * two, three or four sided. 
     * <p>
     * As his parent <code>javax.swing.border.EtchedBorder</code> {@link javax.swing.border.EtchedBorder}:
     * <ul>
     * <li> The border can be etched-in or etched-out.
     * <li> If colors highlight/shadow aren't initialized, they will be
     * derived from the component for which the border is being painted.
     * </ul>
     *
     * @author Julie Duvillier
     */
    public class SidedEtchedBorder 
            extends EtchedBorder{
     
        /* Booleans holding which side of the border will be paint. */
        private boolean top, left,bottom,right;
     
        /**
         * Creates four sided a lowered etched border with default colors.
         */
        public SidedEtchedBorder(){
            this(LOWERED,true, true, true, true);
        }
     
        /**
         * Creates a sided lowered etched border with default colors.
         * @param top           if <code>true</code> the top side will be painted
         * @param left          if <code>true</code> the left side will be painted
         * @param bottom        if <code>true</code> the bottom side will be painted
         * @param right         if <code>true</code> the right side will be painted
         */
        public SidedEtchedBorder(boolean top, boolean left,boolean bottom, boolean right){
            this(LOWERED,null,null, top, left,bottom, right);
        }
     
        /**
         * Created a sided etched border with the specifed etch-type
         * and default colors.
         * @param etchType      the type of etch to be paint
         * @param top           if <code>true</code> the top side will be painted
         * @param left          if <code>true</code> the left side will be painted
         * @param bottom        if <code>true</code> the bottom side will be painted
         * @param right         if <code>true</code> the right side will be painted
         */
        public SidedEtchedBorder(int etchType,
                                 boolean top, boolean left,boolean bottom, boolean right){
             this(etchType,null,null, top, left,bottom, right);
     
        }
     
        /**
         * Creates a sided lowered etched border with the specified colors.
         * @param highlight     the color to use for highlight
         * @param shadow        the color to use for shadow
         * @param top           if <code>true</code> the top side will be painted
         * @param left          if <code>true</code> the left side will be painted
         * @param bottom        if <code>true</code> the bottom side will be painted
         * @param right         if <code>true</code> the right side will be painted
         */
        public SidedEtchedBorder(Color highlight, Color shadow,
                                 boolean top, boolean left,boolean bottom, boolean right){
     
        }
     
        /**
         * Creates a sided etched border with the specified etch-type.
         * and colors.
         * @param etchType      the type of etch to be paint
         * @param highlight     the color to use for highlight
         * @param shadow        the color to use for shadow
         * @param top           if <code>true</code> the top side will be painted
         * @param left          if <code>true</code> the left side will be painted
         * @param bottom        if <code>true</code> the bottom side will be painted
         * @param right         if <code>true</code> the right side will be painted
         */
         public SidedEtchedBorder(int etchType,
                                  Color highlight, Color shadow,
                  boolean top, boolean left,boolean bottom, boolean right){
            super(etchType, highlight, shadow);
            this.top = top;
            this.right = right;
            this.bottom = bottom;
            this.left = left;
     
         }
     
         /**
          * Creates a one sided lowered etched border with default colors.
          * @param side the side to be draw
          */
         public SidedEtchedBorder( int side){
             this(side,LOWERED,null,null);
         }
     
         /**
          * Creates a one sided lowered etched border with the specified etch-type
          * and default colors.
          * @param side         the side to be draw
          * @param etchType     the type of etch to be paint
          */
         public SidedEtchedBorder(int side,int etchType ){
             this(side,LOWERED,null,null);
         }
     
         /**
          * Creates a one sided lowered etched border with specifed colors.
          * @param side         the side to be draw
          * @param highlight    the color to use for highlight
          * @param shadow       the color to use for shadow
          */
         public SidedEtchedBorder(int side,Color highlight, Color shadow){
             this(side,LOWERED,highlight,shadow);
         }
         /**
          * Creates a one sided etched border with the specified etch-type
          * and colors.
          * @param side          the side to be draw
          * @param etchType      the type of etch to be paint
          * @param highlight     the color to use for highlight
          * @param shadow        the color to use for shadow
          */
         public SidedEtchedBorder( int side, int etchType, Color highlight, Color shadow){
            this(etchType,highlight,shadow, false,false,false,false);
            switch(side){
                case SwingConstants.TOP: top =true; break;
                case SwingConstants.LEFT: left =true; break;
                case SwingConstants.BOTTOM: bottom =true; break;
                case SwingConstants.RIGHT: right =true; break;
             }
         }
     
     
     
         /**
          * Paints the border for the specified component
          * with the specified position and size.
          */
        @Override
        public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
            g.translate(x, y);
            int w = width ;
            int h= height;
     
            Color col1 = (etchType == LOWERED)? getShadowColor(c)
                                              : getHighlightColor(c);
     
            Color col2 = (etchType == LOWERED)? getHighlightColor(c)
                                              : getShadowColor(c);
     
            if( top ){
                drawLine(g,col1,0, 0, w-2, 0);
                drawLine(g,col2,1, 1, w-3, 1);
            }
            if( left ){
                drawLine(g,col1,0, 0, 0, h-2);
                drawLine(g,col2,1, h-3, 1, 1);
            }
            if( bottom){
                drawLine(g,col1,0, h-2, w-2, h-2);
                drawLine(g,col2,0, h-1, w-1, h-1);
            }
            if( right){
                drawLine(g,col1, w-2, 0 , w-2, h-2);
                drawLine(g,col2,w-1, h-1, w-1, 0);
            }
     
            g.translate(-x, -y);
        }
     
        /**
         * Draw a line with the specifed graphics, color, between the points
         * of coordinates A1(x1,y1) and A2(x2,y2).
         * @param g         the graphics objects to use
         * @param color     the color of the line to be draw
         * @param x1        abscissa of A1
         * @param y1        ordinate of A1
         * @param x2        abscissa of A2
         * @param y2        ordinate of A2
         */
        private void drawLine(Graphics g,Color color, int x1, int y1, int x2, int y2 ){
            g.setColor(color);
            g.drawLine(x1, y1, x2, y2);
        }
     
        /**
         * Gets the insets of the border.
         * @param c         the component for which the border is painted
         * @return          the <code>Insets</code> object of the border
         */
        @Override
         public Insets getBorderInsets(Component c) {
            return getBorderInsets(c, new Insets(0, 0, 0, 0));
        }
     
        /**
         * Gets the insets of the border after reinitializing it
         * with border insets.
         * @param c         the component for which the border is painted
         * @param insets    the <code>Insets</code> object to be reinitialized
         * @return          the <code>Insets</code> object of the border
         */
        @Override
         public Insets getBorderInsets(Component c, Insets insets) {
            insets.left = insets.top = insets.right = insets.bottom = 0;
            if( top ){
                insets.top = 2;
            }
            if(left) {
                insets.left =2;
            }
            if(bottom){
                insets.bottom = 2;
            }
            if(right){
                insets.right =2;
            }
            return insets;
        }
     
    }
      0  0

  4. #104
    Membre expérimenté Avatar de herve91
    Profil pro
    Inscrit en
    Novembre 2004
    Messages
    1 282
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2004
    Messages : 1 282
    Points : 1 608
    Points
    1 608
    Par défaut
    Citation Envoyé par petibras Voir le message
    les constructeurs pour une border a plus d'un cote sont un peu rebarbatif, si quelqu'un a une meilleure idee je suis preneuse!
    Une proposition :
    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
    public class SidedEtchedBorder extends EtchedBorder {
     
    	public enum EnumSide {
    		TOP, LEFT, BOTTOM, RIGHT;
    	}
     
    	private Collection<EnumSide> sides;
     
    	public SidedEtchedBorder() {
    		this(EnumSide.values());
    	}
     
    	public SidedEtchedBorder(EnumSide... sides) {
    		this(LOWERED, sides);
    	}
     
    	public SidedEtchedBorder(int etchType) {
    		this(etchType, EnumSide.values());
    	}
     
    	public SidedEtchedBorder(int etchType, EnumSide... sides) {
    		this(etchType, null, null, sides);
    	}
     
    	public SidedEtchedBorder(Color highlight, Color shadow) {
    		this(LOWERED, highlight, shadow);
    	}
     
    	public SidedEtchedBorder(int etchType, Color highlight, Color shadow) {
    		this(etchType, highlight, shadow, EnumSide.values());
    	}
     
    	public SidedEtchedBorder(Color highlight, Color shadow, EnumSide... sides) {
    		this(LOWERED, highlight, shadow, sides);
    	}
     
    	public SidedEtchedBorder(int etchType, Color highlight, Color shadow,
    			EnumSide... sides) {
    		super(etchType, highlight, shadow);
    		this.sides = new HashSet<EnumSide>(Arrays.asList(sides));
    	}
     
    	@Override
    	public void paintBorder(Component c, Graphics g, int x, int y, int width,
    			int height) {
    		// ...
     
    		if (edging(EnumSide.TOP)) {
    			// ...
    		}
    		if (edging(EnumSide.LEFT)) {
    			// ...
    		}
    		if (edging(EnumSide.BOTTOM)) {
    			// ...
    		}
    		if (edging(EnumSide.RIGHT)) {
    			// ...
    		}
     
    		// ...
    	}
     
    	@Override
    	public Insets getBorderInsets(Component c, Insets insets) {
    		// ...
     
    		if (edging(EnumSide.TOP)) {
    			// ...
    		}
    		if (edging(EnumSide.LEFT)) {
    			// ...
    		}
    		if (edging(EnumSide.BOTTOM)) {
    			// ...
    		}
    		if (edging(EnumSide.RIGHT)) {
    			// ...
    		}
     
    		return insets;
    	}
     
    	protected boolean edging(EnumSide side) {
    		return this.sides.contains(side);
    	}
    }
      0  0

  5. #105
    Expert éminent sénior
    Avatar de Auteur
    Profil pro
    Inscrit en
    Avril 2004
    Messages
    7 643
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 7 643
    Points : 11 131
    Points
    11 131
    Par défaut [JTabbedPane] setMnemonicAt et les chiffres
    bonjour,

    il y a quelques temps déjà je voulais avoir la possibilité d'utiliser les raccourcis Alt+1, Alt+2 sur un JTabbedPane pour passer d'un onglet à l'autre.

    Voici donc ma contribution :
    http://www.developpez.net/forums/d78...icat-chiffres/
      0  0

  6. #106
    Membre expérimenté Avatar de herve91
    Profil pro
    Inscrit en
    Novembre 2004
    Messages
    1 282
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2004
    Messages : 1 282
    Points : 1 608
    Points
    1 608
    Par défaut [Java/Swing] PopupEditor pour un JTable
    Bonsoir,
    il s'agit d'une classe permettant d'éditer une cellule de JTable sous la forme d'un PopupMenu.
    Le PopupMenu contient des checkBoxMenuItem permettant de sélectionner plusieurs éléments en même temps, et présélectionnés selon la valeur de la cellule.
    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
    package popup;
     
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseListener;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.util.ArrayList;
    import java.util.List;
     
    import javax.swing.AbstractCellEditor;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JTable;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
     
    public class PopupEditor extends AbstractCellEditor implements TableCellEditor,
            PropertyChangeListener {
     
        private TableCellRenderer renderer;
     
        private JXPopupMenu popupMenu = new JXPopupMenu();
     
        private JButton validate = makeButton("\u21B5", Color.GREEN.darker(),
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        stopCellEditing();
                    }
                });
     
        private JButton cancel = makeButton("X", Color.RED, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                cancelCellEditing();
            }
        });
     
        private JPanel panelButtons;
     
        protected JXCheckBoxMenuItem[] checkBoxMenuItems;
     
        private static final MouseListener mouseListener = new MouseAdapter() {
        };
     
        public PopupEditor(TableCellRenderer renderer, Object[] items) {
            this.renderer = renderer;
     
            panelButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
            panelButtons.add(validate);
            panelButtons.add(cancel);
     
            setChoosableItems(items);
        }
     
        protected JButton makeButton(String text, Color color,
                ActionListener listener) {
            JButton button = new JButton(text);
            button.setForeground(color);
            button.setBorder(BorderFactory.createRaisedBevelBorder());
            button.setFocusPainted(false);
            button.addActionListener(listener);
            return button;
        }
     
        public boolean stopCellEditing() {
            popupMenu.close();
            return super.stopCellEditing();
        }
     
        public void cancelCellEditing() {
            popupMenu.close();
            super.cancelCellEditing();
        }
     
        public void setChoosableItems(Object[] items) {
            popupMenu.removeAll();
     
            this.checkBoxMenuItems = new JXCheckBoxMenuItem[items.length];
            for (int i = 0; i < items.length; i++) {
                JXCheckBoxMenuItem menuItem = new JXCheckBoxMenuItem(items[i]);
                checkBoxMenuItems[i] = menuItem;
                popupMenu.add(menuItem);
            }
     
            popupMenu.addSeparator();
            popupMenu.add(panelButtons);
            popupMenu.pack();
            popupMenu.setPackSize(popupMenu.getPreferredSize());
        }
     
        public Object getCellEditorValue() {
            List l = new ArrayList();
            for (int i = 0; i < checkBoxMenuItems.length; i++) {
                JXCheckBoxMenuItem menuItem = checkBoxMenuItems[i];
                if (menuItem.isSelected()) {
                    l.add(menuItem.getItem());
                }
            }
            return l.toArray();
        }
     
        protected void setCellEditorValue(Object value) {
            for (int i = 0; i < checkBoxMenuItems.length; i++) {
                JXCheckBoxMenuItem menuItem = checkBoxMenuItems[i];
                menuItem.setSelected(false);
            }
     
            if (value != null) {
                Object[] v = (Object[]) value;
                for (int i = 0; i < checkBoxMenuItems.length; i++) {
                    JXCheckBoxMenuItem menuItem = checkBoxMenuItems[i];
                    for (int j = 0; j < v.length; j++) {
                        if (v[j] != null && menuItem.getItem().equals(v[j])) {
                            menuItem.setSelected(true);
                            break;
                        }
                    }
                }
            }
        }
     
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getOldValue() == this && evt.getNewValue() == null) {
                popupMenu.close();
            }
        }
     
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
            table.removePropertyChangeListener("tableCellEditor", this);
            table.addPropertyChangeListener("tableCellEditor", this);
     
            setCellEditorValue(value);
     
            Rectangle rect = table.getCellRect(row, column, false);
            Dimension size = popupMenu.getPackSize();
            popupMenu.setPreferredSize(new Dimension(Math.max(rect.width,
                    size.width), size.height));
            popupMenu.show(table, rect.x, rect.y + rect.height);
     
            Component comp = renderer.getTableCellRendererComponent(table, value,
                    isSelected, false, row, column);
            comp.removeMouseListener(mouseListener);
            comp.addMouseListener(mouseListener);
            return comp;
        }
     
        private static class JXPopupMenu extends JPopupMenu {
     
            private Dimension packSize;
     
            private boolean closeable;
     
            public Dimension getPackSize() {
                return packSize;
            }
     
            public void setPackSize(Dimension packSize) {
                this.packSize = packSize;
            }
     
            public void close() {
                closeable = true;
                setVisible(false);
            }
     
            public void setVisible(boolean b) {
                if (b || closeable) {
                    super.setVisible(b);
                    closeable = false;
                }
            }
        }
     
        private static class JXCheckBoxMenuItem extends JCheckBoxMenuItem {
     
            private Object item;
     
            public JXCheckBoxMenuItem(Object item) {
                super(item.toString());
                this.item = item;
            }
     
            public Object getItem() {
                return item;
            }
        }
     
    }
    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
    package popup;
     
    import javax.swing.table.DefaultTableCellRenderer;
     
    public class ArrayTableCellRenderer extends DefaultTableCellRenderer {
     
        private String separator;
     
        public ArrayTableCellRenderer() {
            this(null);
        }
     
        public ArrayTableCellRenderer(String separator) {
            this.separator = separator != null ? separator : " ";
        }
     
        protected void setValue(Object value) {
            if (value != null) {
                value = format((Object[]) value);
            }
            super.setValue(value);
        }
     
        protected Object format(Object[] values) {
            boolean separate = false;
            StringBuffer sb = new StringBuffer();
     
            for (int i = 0; i < values.length; i++) {
                if (values[i] != null) {
                    if (separate) {
                        sb.append(getSeparator());
                    }
                    sb.append(values[i]);
                    separate = true;
                }
            }
            return sb;
        }
     
        protected String getSeparator() {
            return separator;
        }
     
        protected void setSeparator(String separator) {
            this.separator = separator;
        }
    }
    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
    package popup;
     
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
     
    public class TestPopupEditor extends JFrame {
     
        public TestPopupEditor() {
            Object[] couleurs = { "Blanc", "Rouge", "Vert", "Bleu", "Jaune", "Noir" };
            Object[] formes = { "Rond", "Carré", "Triangle" };
            Object[] poids = { "1kg", "2kg", "3kg", "4kg", "5kg" };
     
            JTable jTable = new JTable(new Object[][] {
                    new Object[] { new Object[] { "Rouge", "Vert" }, null, null },
                    new Object[] { null, new Object[] { "Carré", "Triangle" },
                            new Object[] { "1kg", "2kg" } }, new Object[3] },
                    new String[] { "Couleurs", "Formes", "Poids" });
     
            jTable.setDefaultRenderer(Object.class, new ArrayTableCellRenderer());
     
            TableCellRenderer popupRenderer = new ArrayTableCellRenderer();
            jTable.getColumnModel().getColumn(0).setCellEditor(
                    new PopupEditor(popupRenderer, couleurs));
            jTable.getColumnModel().getColumn(1).setCellEditor(
                    new PopupEditor(popupRenderer, formes));
            jTable.getColumnModel().getColumn(2).setCellEditor(
                    new PopupEditor(popupRenderer, poids));
     
            getContentPane().add(new JScrollPane(jTable));
            setSize(600, 300);
            setVisible(true);
        }
     
        public static void main(String[] args) {
            new TestPopupEditor();
        }
    }
    Images attachées Images attachées  
      0  0

  7. #107
    Membre expérimenté Avatar de herve91
    Profil pro
    Inscrit en
    Novembre 2004
    Messages
    1 282
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2004
    Messages : 1 282
    Points : 1 608
    Points
    1 608
    Par défaut [Java/Swing] Librairie Java Drag & Drop
    Bonsoir,

    il s'agit d'une librairie permettant de faire du drag&drop dans une application Java/Swing au sein d'une fenêtre JFrame, JDialog ou JWindow, via le glasspane de la fenêtre.

    Le drag s'applique sur des composants Swing et s'accompagne d'effets visuels comme la superposition d'une image translucide sur l'objet à déplacer, et ce jusqu'au drop sur l'objet cible. L'objet cible dispose également d'un effet visuel paramétrable dynamiquement (surbrillance, bordure, forme pleine, etc.).

    La sélection du drag peut être multiple par simple clique sur chacun des objets à déplacer, puis glissement du dernier objet sélectionné vers la cible. Sur chaque objet sélectionné, l'image translucide clignote tant que le glissement n'est pas réalisé. En cliquant de nouveau sur un objet sélectionné, l'image disparaît.

    Il est possible de définir le niveau de transparence de l'image pour chaque objet source, ainsi que l'image elle-même :
    1. picture : fichier image en ressource de l'application
    2. component : il s'agit d'une image du composant calculée en mémoire
    3. text : un texte mono ou multi lignes affiché à la façon d'une info-bulle, avec la possibilité de définir la couleur de fond de la vignette ainsi que l'alignement du texte à l'intérieur (gauche, centré, droite).

    Toutes les classes sont extensibles permettant d'ajouter facilement d'autres comportements.
    Il est également possible de définir des groupes d'objets autorisés à être déplacés ensemble. Enfin, un système de notification est mis en place pour déclencher des traitements clients à l'issue du drop.
    Le fichier joint contient les classes compilées, les sources, ainsi qu'une démonstration des possibilités de la librairie. Il porte l'extension .zip. Une fois le téléchargement effectué, il faut renommer l'extension .zip en .jar pour obtenir le fichier "dnd.jar"
    Images attachées Images attachées  
    Fichiers attachés Fichiers attachés
    • Type de fichier : zip dnd.zip (376,8 Ko, 218 affichages)
      0  0

  8. #108
    Membre régulier

    Homme Profil pro
    Lycéen-Développeur Java autodidacte
    Inscrit en
    Février 2011
    Messages
    33
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 26
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Lycéen-Développeur Java autodidacte
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2011
    Messages : 33
    Points : 117
    Points
    117
    Par défaut Boîte de dialogue permettant de proposer un choix de fonte
    Auteur : commence par 'M' et finit par 'I', en trois lettres ...
    Voilà après avoir passé de longues heures (bon d'accord, au moins 1) sur le Net parmi des solutions qui ne me plaisaient pas, j'ai décidé de coder moi-même une boîte de dialogue qui propose à l'utilisateur de choisir une fonte de caractères (police, style et taille) parmi celles installées sur son système.

    L'apparence est plutôt 'classique' (voir image jointe).

    Il faut spécifier la fonte par défaut à la création de la boîte de dialogue.

    Seul le champ de texte affichant la taille est éditable, pour les autres on peut seulement choisir parmi les valeurs des listes correspondantes.

    D'autre part, l'ensemble n'est pas inséré directement dans le conteneur de la boîte de dialogue, mais dans un panneau, ce qui facilite la mise en place d'un système d'onglets lorsque l'on veut proposer d'autres options (choix de taille, de couleur, etc.)

    J'ai essayé de commenter tant que possible

    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
    /*
     * Développé par ZeusOlym
     * Contact : <lev.grec@gmail.com>
     * Merci de donner un objet à votre mail
     * 
     */
     
    import java.awt.* ;
    import java.awt.event.* ;
    import javax.swing.* ;
    import javax.swing.event.* ;
     
    /*===================Classe permettant de proposer un choix de police de caractères===================
     * 
     * Créer la boîte :
     * 
     * ChoixDePolice choix = new ChoixDePolice(Font police_de_départ);
     * Un objet dérivé de JDialog est créé
     * 
     * Pour récupérer la valeur entrée par l'utilisateur :
     * fontGetter() : Font
     * 
     * Pour détruire la boîte (par défaut, elle est seulement masquée à sa fermeture) :
     * dispose() : void
     * 
     *====================================================================================================*/
     
    //Création de la boîte de dialogue
    @SuppressWarnings("serial")
    class ChoixDePolice extends JDialog{
    	public ChoixDePolice(final Font f){
    		//Créer la boîte
    		super((JFrame)null, "Choix de la fonte", true);
    		//Créer le panneau
    		polices = new Polices(f, this);
    		scroll_police = new JScrollPane(polices);
    		add(scroll_police);
    		polices.setter(f);
    		//Modifier le comportement pour que la fermeture de la boîte aie le même résultat
    		//qu'un clic sur 'Annuler'
    		addWindowListener(new WindowAdapter(){
    			public void windowClosing(WindowEvent e){
    				polices.setter(f);
    			}
    		});
    		//Dimensionner et afficher la boîte
    		pack();
    		setLocationRelativeTo(null);
    		setVisible(true);
    	}
     
    	//Récupérer la fonte demandée
    	public Font fontGetter(){
    		return polices.getter();
    	}
    	Dimension dims; JScrollPane scroll_police; static Polices polices;
     
     
    	//Création du panneau gérant la police
    	class Polices extends JPanel implements ActionListener{
    		public Polices(Font f, JDialog appel){
    			//Permet d'utiliser f et appel en dehors du constructeur
    			arg0 = f;
    			arg1 = appel;
     
    			//Création du champ exemple et de tableaux contenant le choix proposé
    			exemple = new JTextField("Voix ambiguë d'un coeur qui, au zéphyr, préfère les jattes de kiwis", 24);
    			exemple.setEditable(false);
     
    			tailles = new String[]{"6","8","10","11","12","14","16","18","20","22","24","26","28","30","32","34","36","40","44","48"};
    			styles = new String[]{"Normal", "Gras", "Italique", "Gras et Italique"};
    			polices = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
     
    			//Création des box JTextField + JList permettant de choisir
    			fonte = new Vertical(0, polices, false);
    			style = new Vertical(0, styles, false);
    			size = new Vertical(0, tailles, true);
     
    			//Création des boutons de fin de dialogue
    			annuler = new JButton("Annuler");
    			annuler.addActionListener(this);
    			ok = new JButton("OK");
    			ok.addActionListener(this);
     
    			//Box contenant les boutons
    			prov_valid = Box.createHorizontalBox();
    			prov_valid.add(annuler);
    			prov_valid.add(Box.createHorizontalStrut(5));
    			prov_valid.add(ok);
     
    			entier = Box.createVerticalBox();
     
    			//Box gérant la mise en page des boutons
    			valid = Box.createHorizontalBox();
    			valid.add(Box.createGlue());
    			valid.add(prov_valid);
     
    			//Box gérant la mise en page des listes de choix
    			settings = Box.createHorizontalBox();
    			settings.add(fonte);
    			settings.add(Box.createHorizontalStrut(5));
    			settings.add(style);
    			settings.add(Box.createHorizontalStrut(5));
    			settings.add(size);
     
    			//Box contenant l'intégralité des composants
    			entier.add(settings);
    			entier.add(Box.createVerticalStrut(5));
    			entier.add(exemple);
    			entier.add(Box.createVerticalStrut(5));
    			entier.add(valid);
     
    			//Remplissage des valeurs par défauts et affichage de l'exemple
    			setter(f);
    			exemple();
     
    			//Écouter le champ de texte de saisie de la taille afin que les modifications
    			//soient répercutées lorsque son contenu change
    			size.resultat.addActionListener(this);
     
    			//Ajout du résultat au panneau
    			add(entier);
    		}
     
    		//Remplir les JTextField de résultat avec les valeurs par défaut transmises
    		//sous forme d'objet 'Font'
    		public void setter(Font f){
    			fonte.resultat.setText(f.getName());
    			size.resultat.setText(String.valueOf(f.getSize()));
    			int prov = f.getStyle();
    			String prov2 = "";
    			if(prov==Font.PLAIN){prov2 = "Normal";}
    			else if(prov==Font.BOLD){prov2 = "Gras";}
    			else if(prov==Font.ITALIC){prov2 = "Italique";}
    			else if(prov==Font.BOLD+Font.ITALIC){prov2 = "Gras et Italique";}
    			style.resultat.setText(prov2);
    		}
     
    		//Retourner les valeurs saisies par l'utilisateur sous forme d'objet 'Font'
    		public Font getter(){
    			String prov = style.resultat.getText();
    			if(prov.equals("Normal")){
    				styl = Font.PLAIN;
    			}
    			else if(prov.equals("Gras")){
    				styl = Font.BOLD;
    			}
    			else if(prov.equals("Italique")){
    				styl = Font.ITALIC;
    			}
    			else if(prov.equals("Gras et Italique")){
    				styl = Font.BOLD+Font.ITALIC;
    			}
    			if(size.resultat.getText().equals("")==false){
    				font = new Font(fonte.resultat.getText(), styl, Integer.parseInt(size.resultat.getText()));
    				return font;
    			}
    			else{
    				JOptionPane.showMessageDialog(null, "Vous n'avez pas spécifié de taille !", "Erreur de saisIe", JOptionPane.ERROR_MESSAGE);
    				return null;
    			}
    		}
     
    		//Afficher un exemple pour les valeurs sélectionnées
    		public void exemple(){
    			Font prov_font = getter();
    			if(prov_font != null){
    				exemple.setFont(prov_font);
    			}
    			else{System.out.println("Erreur : Impossible d'afficher l'exemple, l'appel de getter() a retourné une valeur nulle");}
    		}
     
    		//Gestion des évènements Action
    		public void actionPerformed(ActionEvent e){
    			if(e.getSource()==ok){
    				//Faire disparaître la boîte de dialogue sans la détruire
    				//pour pouvoir continuer à utiliser getter() de l'extérieur
    				arg1.setVisible(false);
    			}
    			else if(e.getSource()==annuler){
    				//Remettre les valeurs de départ puis
    				//faire disparaître la boîte de dialogue sans la détruire
    				//pour pouvoir continuer à utiliser getter() de l'extérieur
    				setter(arg0);
    				arg1.setVisible(false);
    			}
    			else if(e.getSource()==size.resultat){
    				exemple();
    			}
    		}
     
    		String [] tailles, polices, styles; Box settings, entier, valid, prov_valid; Vertical fonte, style, size;
    		Font font; int styl; JTextField exemple; JButton ok, annuler; Font arg0; JDialog arg1;
    	}
    }
     
    //Type créant un ensemble JTextField + JList servant au choix
    @SuppressWarnings("serial")
    class Vertical extends Box implements ListSelectionListener{
    	//Créer un Box vertical contenant le champ de texte et la liste
    	public Vertical(int i, String[] contenu, boolean edition){
    		super(1);
    		resultat = new JTextField();
    		resultat.setEditable(edition);
    		choix = new JList(contenu);
    		choix.setSelectionMode(0);
    		choix.setVisibleRowCount(10);
    		choix.addListSelectionListener(this);
    		defil = new JScrollPane(choix);
     
    		//Ajouter les composants au Box
    		add(resultat);
    		add(Box.createVerticalStrut(3));
    		add(defil);
    	}
     
    	//Remplir le champ de texte avec la valeur sélectionnée dans la liste
    	public void valueChanged(ListSelectionEvent e){
    		if(!e.getValueIsAdjusting()){
    			resultat.setText((String)choix.getSelectedValue());
    			ChoixDePolice.polices.exemple();
    		}
    	}
    	JTextField resultat; JList choix; JScrollPane defil;
    }
    Toutes vos remarques et suggestions sont les bienvenues !
    Images attachées Images attachées  
      0  0

  9. #109
    Membre averti
    Avatar de anadoncamille
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juillet 2007
    Messages
    395
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2007
    Messages : 395
    Points : 310
    Points
    310
    Billets dans le blog
    1
    Par défaut Un synthétiseur facile à intégrer
    Bonjour !

    voici un synthétiseur MIDI facile à utiliser et à intégrer.
    Il peut servir par exemple à faire des menus musicaux, comme dans AnAcondA.

    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
     
    import java.util.*;
    import javax.sound.midi.*;
     
    /* Un synthétiseur facile à utiliser
     *
     * 2011 Sylvain Tournois - http://sylv.tournois.free.fr/
     */
     
    public class Synthe {
     
      public static void main(String[] args) {
        Synthe synth = new Synthe(); // construction et initialisation du synthétiseur (16 canaux)
        synth.program(0, "Crystal"); // programmation du canal 0 avec l'instrument "Crystal"
        synth.play(0, 60, 127); // jouer le DO du milieu
     
        System.out.println("Liste des instrumets disponibles :");
        String[] instrus = synth.getInstrumentsList(); // afficahge de la liste des instruments disponibles
        for (int i = 0 ; i < instrus.length ; i++) // pour chaque instrument
          System.out.println(instrus[i]); // écrire son nom
     
        synth.play(0, 62, 127); // jouer le RE du milieu (2 demis-tons au-dessus du DO)
     
        // affichage d'un message d'attente de clavier
        System.out.println("\n2011 Sylvain Tournois - www.anadoncamille.com\n\nAppuyez sur la touche Entree pour terminer...");
        try {
          while (System.in.available() == 0); // tant que la touche Entrée n'est pas pressée, attendre
        }
        catch (Exception e) {
        }
     
        synth.close(); // cloture du synthétiseur
      }
     
      private Synthesizer synthesizer; // le synthétiseur
      private String[] instrumentsList; // liste des noms d'instruments disponibles
      private MidiChannel[] channels; // liste des canaux du synthétiseur (16, habituellement)
      private Hashtable instruments; // table de correspondance entre les noms d'instruments et leurs données
     
      // Construction et initialisation du synthétiseur
      public Synthe() {
        try {
          synthesizer = MidiSystem.getSynthesizer(); // récupération du synthétiseur standard
          synthesizer.open(); // ouverture du synthétiseur (obligatoire avant toute opération)
          synthesizer.loadAllInstruments(synthesizer.getDefaultSoundbank()); // chargement de la banque d'instruments par défaut
    //      synthesizer.loadAllInstruments(getSoundbank(new File("maBanque.gm"))); // chargement d'une banque d'instruments spécifique
          Instrument[] is = synthesizer.getLoadedInstruments(); // récupération de la liste des instruments disponibles
          instruments = new Hashtable(); // préparation de la table de correspondance "nom <-> instrument"
          instrumentsList = new String[is.length]; // préparation de la liste des noms d'instruments disponibles
          for (int i = 0 ; i < is.length ; i++) { // pour chaque instrument de la liste
            instrumentsList[i] = is[i].getName(); // récupération du nom de l'instrument
            instruments.put(instrumentsList[i], is[i]); // création de la correspondance "nom <-> instrument"
          }
          channels = synthesizer.getChannels(); // récupération de la liste des canaux disponibles
        }
        catch (Exception e) { // gestion des excpetion
          e.printStackTrace(); // écriture de la trace d'exception
          synthesizer = null; // annulation du fonctionnement correct du synthétiseur
        }
      }
     
      // programmer l'instrument in sur le canal ch
      public void program(int ch, String in) {
        if (synthesizer == null) // si le synthétiseur n'a pas été correctement initialisé
          return; // court-circuiter la commande
        Instrument is = (Instrument)instruments.get(in); // recherche de l'inctrument correspondant au nom indiqué
        if (is == null) // si l'instrument est inconnu
          return; // court-circuiter la commande
        Patch p = is.getPatch(); // récupération des paramètres de l'instrument
        channels[ch].programChange(p.getBank(), p.getProgram()); // programmation du canal avec les paramètres de l'instrument
      }
     
      // jouer la note nt[0..127] avec la vélocité ve[0..127] sur le canal ch
      public void play(int ch, int nt, int ve) {
        if (synthesizer == null) // si le synthétiseur n'a pas été correctement initialisé
          return; // court-circuiter la commande
        channels[ch].noteOn(nt, ve); // jouer la note nt avec la vélocité ve sur le canal ch
      }
     
      public void close() {
        if (synthesizer == null) // si le synthétiseur n'a pas été correctement initialisé
          return; // court-circuiter la commande
        synthesizer.close(); // fermeture du synthétiseur
      }
     
      public String[] getInstrumentsList() {
        return instrumentsList;
      }
     
    }
    __________________________________
    | +
    | Sylvain Tournois - Création logicielle
    |
    | sylv.tournois.free.fr
    |
      0  0

  10. #110
    Expert éminent

    Avatar de mlny84
    Profil pro
    Inscrit en
    Septembre 2007
    Messages
    4 023
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2007
    Messages : 4 023
    Points : 8 107
    Points
    8 107
    Par défaut
    Bonjour,

    Une nouvelle application vous permettant de mettre en ligne vos sources directement à été mise en place.
    Ce sujet est donc fermé et n'acceptera plus de nouveaux messages.

    Je vous invite donc à mettre vos sources ici.

    Merci à tous pour vos contributions.
      0  0

Discussions similaires

  1. Page Code Source, mettez vos codes ici
    Par Bovino dans le forum Contribuez
    Réponses: 8
    Dernier message: 05/12/2008, 13h11
  2. Participez à la FAQ VBA ou à la page Sources
    Par Nightfall dans le forum Contribuez
    Réponses: 1
    Dernier message: 04/08/2006, 18h34

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