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

AWT/Swing Java Discussion :

JCombobox pour choisir une couleur


Sujet :

AWT/Swing Java

  1. #1
    Membre à l'essai
    Profil pro
    Inscrit en
    Mai 2006
    Messages
    16
    Détails du profil
    Informations personnelles :
    Âge : 37
    Localisation : Suisse

    Informations forums :
    Inscription : Mai 2006
    Messages : 16
    Points : 12
    Points
    12
    Par défaut JCombobox pour choisir une couleur
    Hello!

    je cherche le moyen de faire un bouton qui permet de changer de couleur. L'élément a utiliser est probablement un jcombobox mais je le trouve assez loud; je souhaiterais un petit bouton comme dans word par exemple pour changer la couleur de son texte... qqn aurait-il une idée comment faire ça?

    Merci d'avance

  2. #2
    Membre éclairé
    Avatar de seiryujay
    Profil pro
    Inscrit en
    Mars 2004
    Messages
    950
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2004
    Messages : 950
    Points : 722
    Points
    722
    Par défaut
    Crée un bouton qui t'ouvre un JColorChooser sur le clic.
    http://javasearch.developpez.com/sun...orChooser.html

  3. #3
    Membre à l'essai
    Profil pro
    Inscrit en
    Mai 2006
    Messages
    16
    Détails du profil
    Informations personnelles :
    Âge : 37
    Localisation : Suisse

    Informations forums :
    Inscription : Mai 2006
    Messages : 16
    Points : 12
    Points
    12
    Par défaut
    J'y ai pensé bien entendu mais la cahier des charges qui m'est imposé me contraint à 5 couleurs dans le choix, je dois donc éviter le JColorChooser....

    un autre idée?

  4. #4
    Membre régulier Avatar de _KB_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mars 2006
    Messages
    110
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Mars 2006
    Messages : 110
    Points : 92
    Points
    92
    Par défaut
    Faire un JColorChooser perso ?

    Un bouton, au clic ca ouvre un JFrame avec tes 5 couleurs représentées par 5 icônes...
    Comme le disait Heisenberg « Chérie, j’ai garé la voiture, mais je sais plus où »

  5. #5
    Membre éclairé
    Avatar de seiryujay
    Profil pro
    Inscrit en
    Mars 2004
    Messages
    950
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2004
    Messages : 950
    Points : 722
    Points
    722
    Par défaut
    Ce que je verrai bien :
    1) Tu te crées un DropDownButton (codes ici)
    2) Dans ton menu déroulant, tu rajoutes des ImageIcon représentant tes couleurs (avec un petit texte si tu veux)
    3) Sur le clic dans le menu déroulant, tu affectes la couleur correspondant au JMenuItem cliqué.

  6. #6
    Membre éclairé
    Avatar de bbclone
    Profil pro
    Inscrit en
    Mai 2006
    Messages
    537
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Mai 2006
    Messages : 537
    Points : 704
    Points
    704
    Par défaut
    mais nan les gars.
    c'est simple ce qu'il demande.
    j'ai fais un rapide code (10minuttes) et j'ai un peu commenter mais en anglais

    je copie-colle ici ensuite si t'a des question pose les moi direct par mail ou je passerai peutetre ce soir.


    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
     
    import javax.swing.JFrame;
    import javax.swing.JComboBox;
    import javax.swing.SwingUtilities;
    import java.util.ArrayList;
    import java.awt.Color;
    import java.awt.FlowLayout;
     
    /**
     * Created by IntelliJ IDEA.
     * User: bebe
     * Date: Jun 1, 2006
     * Time: 6:58:12 PM
     * To change this template use File | Settings | File Templates.
     */
    public class MyBootTest {
     
        public static void main(String[] args) {
            Runnable runnable = new Runnable() {
                public void run() {
     
     
                    /* A (array)list of colors. */
                    ArrayList colors = new ArrayList();
                    colors.add(Color.BLUE);
                    colors.add(Color.BLACK);
                    colors.add(Color.WHITE);
                    colors.add(Color.RED);
                    colors.add(Color.PINK);
     
                    /*
                       With this list, I create my combobox model. A combobox's model
                       contains the data. All you will need is to render these data correctly
                       and that's what we're going to do with the renderer.
                    */
                    MyModel colorsNeeded = new MyModel(colors);
     
                    JComboBox myComboBox = new JComboBox(colorsNeeded);
     
                    /*
                        Look the code of this renderer. It's very simple to understand.
                    */
                    myComboBox.setRenderer(new MyRenderer());
     
     
                    /* some basic stuff needed to show the combobox. */
                    JFrame myFrame = new JFrame("Testing a simple combobox chooser");
                    myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    myFrame.setLayout(new FlowLayout());
                    myFrame.add(myComboBox);
     
                    myFrame.pack();
                    myFrame.setLocationRelativeTo(null);
                    myFrame.setVisible(true);
                }
            };
     
            SwingUtilities.invokeLater(runnable);
        }
    }

    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
     
    import javax.swing.ComboBoxModel;
    import javax.swing.event.ListDataListener;
    import java.util.ArrayList;
    import java.awt.Color;
     
    /**
     * Created by IntelliJ IDEA.
     * User: bebe
     * Date: Jun 1, 2006
     * Time: 6:59:05 PM
     * To change this template use File | Settings | File Templates.
     */
    public class MyModel implements ComboBoxModel {
     
        /*
           My model.
           Really, think about a model as the data your combobox should contain. how these data should be displayed visually doesn't matter for the moment.
        */
        private ArrayList colors = null;
     
        private Color selectedColor = null;
     
        /* You need to specify some colors in the constructor. */
        public MyModel(ArrayList colors) {
            if (colors == null) {
                /*
                   if you don't specify any color, you will be notified ;-)
                */
                throw new IllegalArgumentException("I need an arraylist of colors to make my job correctly.");
            }
            this.colors = colors;
        }
     
        /*  @see javadoc ComboBoxModel.
     
            This is a method called by an internal mechanism of Swing.
            When, why, how comes... The short version is Swing rocks and he knows
            when and how to do his job!
     
            Anyway, thanks to this methid you can keep a reference on the choosen item.
        */
        public void setSelectedItem(Object anItem) {
            this.selectedColor = (Color)anItem;
        }
     
        /*
            Also called by Swing.
            In the previous method, you kept a reference on the selected item.
            Now, when swing ask you wich item has been choosen, you tell him.
     
            @see javadoc ComboBoxModel.
        */
        public Object getSelectedItem() {
            return selectedColor;
        }
     
        /*
          Swing needs to know how many item you combobox contains, or if you
          prefer, how many Color exists in you model.
     
          @see javadoc ComboBoxModel.
        */
        public int getSize() {
            return colors.size();
        }
     
        /*
          Don't you think you need to tell Swing what are the datas ?
         @see javadoc ComboBoxModel.
        */
        public Object getElementAt(int index) {
            return colors.get(index);
        }
     
        /*
           These two next methods are imposed by ComboBoxModel
           We don't need them for what you need.
        */
        public void addListDataListener(ListDataListener l) {
            //To change body of implemented methods use File | Settings | File Templates.
        }
     
        public void removeListDataListener(ListDataListener l) {
            //To change body of implemented methods use File | Settings | File Templates.
        }
    }
    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
     
    import javax.swing.JLabel;
    import javax.swing.ListCellRenderer;
    import javax.swing.JList;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Color;
    import java.awt.Graphics;
     
    /**
     * Created by IntelliJ IDEA.
     * User: bebe
     * Date: Jun 1, 2006
     * Time: 7:01:53 PM
     * To change this template use File | Settings | File Templates.
     */
    public class MyRenderer extends JLabel implements ListCellRenderer {
     
        /* The background color that will be used to paint the label. */
        private Color backgroundColor = null;
     
        public MyRenderer() {
            /*
              each color is rendered as a label.  [width = 200 and height = 50].
            */
            setPreferredSize(new Dimension(200, 50));
            setOpaque(true);
        }
     
        /*
           This is also a method called by Swing. Like in the model. When why... swing knows when ;-)
     
           For each value of you model, for each colors, swing asks :"you how should I display this item ?"
           And what you have to do is to answer his question returning him a whatever Component (jlabel, jPanel, jTextField...).
           here, you return this himself because I extended JLabel, but before doing that, you need to repaint
           the label using the selected color.
        */
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            if (value != null) {
                backgroundColor = (Color) value;
            } else {
                backgroundColor = null;
            }
     
            return this;
        }
     
        /* Paint the label with the selected color. */
        @Override
        public void paint(Graphics g) {
            setBackground(backgroundColor);
            super.paint(g);
        }
    }

  7. #7
    Membre à l'essai
    Profil pro
    Inscrit en
    Mai 2006
    Messages
    16
    Détails du profil
    Informations personnelles :
    Âge : 37
    Localisation : Suisse

    Informations forums :
    Inscription : Mai 2006
    Messages : 16
    Points : 12
    Points
    12
    Par défaut
    Yeah les gars merci bcp!

    je crois qu'avec les réponses de seiryujay et bbclone je vais pouvoir réaliser exactement ce que je veux!

    Génial ces forum quand même, je connais pas depuis longtemps et j'en sui déjà dépendant!

    A+

    Garry

  8. #8
    Rédacteur
    Avatar de Arnaud F.
    Homme Profil pro
    Développeur COBOL
    Inscrit en
    Août 2005
    Messages
    5 183
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France

    Informations professionnelles :
    Activité : Développeur COBOL
    Secteur : Finance

    Informations forums :
    Inscription : Août 2005
    Messages : 5 183
    Points : 8 873
    Points
    8 873
    Par défaut
    Vu que t'es débutant, pense à mettre le tag qui se trouve tout en bas de la page

    C'est une bonne habitude à prendre, dès que ton problème a trouvé sa réponse, tu met ce tag
    C'est par l'adresse que vaut le bûcheron, bien plus que par la force. Homère

    Installation de Code::Blocks sous Debian à partir de Nightly Builds

  9. #9
    Membre du Club
    Inscrit en
    Juillet 2005
    Messages
    95
    Détails du profil
    Informations forums :
    Inscription : Juillet 2005
    Messages : 95
    Points : 52
    Points
    52
    Par défaut
    j'ai appliqué ce jcombobox avec le renderer et le model mais maintenant je ne sais pas où mettre ni sur quoi appliquer mes

    addActionListener(new StyledEditorKit.ForegroundAction(couleur.toString(),couleur));

    merci

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

Discussions similaires

  1. choisir une couleur pour la date affichée dans un datetimepicker
    Par AngeAbstraction dans le forum Débuter
    Réponses: 0
    Dernier message: 28/09/2012, 13h03
  2. une liste déroulante pour choisir une couleur ?
    Par Ekimasu dans le forum Balisage (X)HTML et validation W3C
    Réponses: 2
    Dernier message: 26/02/2009, 12h44
  3. Réponses: 9
    Dernier message: 09/11/2004, 11h41

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