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 :

Héritage JButton : erreur setAction


Sujet :

AWT/Swing Java

  1. #1
    Membre du Club
    Homme Profil pro
    Développeur Java
    Inscrit en
    Septembre 2006
    Messages
    81
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur Java

    Informations forums :
    Inscription : Septembre 2006
    Messages : 81
    Points : 51
    Points
    51
    Par défaut Héritage JButton : erreur setAction
    Bonjour à tous,

    Voilà, j'ai cherché à créer un bouton rond pour une application et j'ai trouvé cette classe (sur ce forum) qui me convient très bien

    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
    package boutonRond;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Insets;
    import java.awt.RenderingHints;
    import java.awt.Shape;
    import java.awt.geom.Ellipse2D;
     
    import javax.swing.Action;
    import javax.swing.BorderFactory;
    import javax.swing.DefaultButtonModel;
    import javax.swing.Icon;
    import javax.swing.JButton;
     
     
    public class RoundButton extends JButton {
        public RoundButton() {
            this(null, null);
        }
        public RoundButton(Icon icon) {
            this(null, icon);
        }
        public RoundButton(String text) {
            this(text, null);
        }
        public RoundButton(Action a) {
            this();
            setAction(a);
        }
        public RoundButton(String text, Icon icon) {
            setModel(new DefaultButtonModel());
            init(text, icon);
            if(icon==null) {
                return;
            }
            setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
            setBackground(Color.BLACK);
            setContentAreaFilled(false);
            setFocusPainted(false);
            //setVerticalAlignment(SwingConstants.TOP);
            setAlignmentY(Component.TOP_ALIGNMENT);
            initShape();
        }
        @Override public Dimension getPreferredSize() {
            Icon icon = getIcon();
            Insets i = getInsets();
            int iw = Math.max(icon.getIconWidth(), icon.getIconHeight());
            return new Dimension(iw+i.right+i.left, iw+i.top+i.bottom);
        }
        protected Shape shape, base;
        protected void initShape() {
            if(!getBounds().equals(base)) {
                Dimension s = getPreferredSize();
                base = getBounds();
                shape = new Ellipse2D.Float(0, 0, s.width-1, s.height-1);
            }
        }
        @Override protected void paintBorder(Graphics g) {
            initShape();
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(getBackground());
            //g2.setStroke(new BasicStroke(1.0f));
            g2.draw(shape);
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
        }
        @Override public boolean contains(int x, int y) {
            initShape();
            return shape.contains(x, y);
        }
    }
    Malheureusement, lorsque je l'utilise et que j'aimerai lui attribué une action, j'obtiens toujours une erreur que je ne comprends vraiment pas. Et l'erreur ne vient que si j'ai ma ligne b1.setAction(new MonAction("rond 1")); (qui est quand meme capitale...)

    L'appel :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    .......
    RoundButton b1 = new RoundButton(new ImageIcon("D:/Temp/tst_boutons/001.png"));
    		b1.setPressedIcon(new ImageIcon("D:/Temp/tst_boutons/001d.png"));
            b1.setRolloverIcon(new ImageIcon("D:/Temp/tst_boutons/001g.png"));
            b1.setAction(new MonAction("rond 1"));
     
    	panel.add(b1);
    ......
    L'action :
    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
    public class MonAction extends AbstractAction {
     
    	private String txt;
     
    	public MonAction(String txt){
    		super();
    		this.txt = txt;
    	}
     
    	@Override
    	public void actionPerformed(ActionEvent e) {
    		System.out.println(txt);
     
    	}
     
    }
    Et l'erreur :
    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
    java.lang.NullPointerException
    	at boutonRond.RoundButton.getPreferredSize(RoundButton.java:50)
    	at java.awt.FlowLayout.layoutContainer(Unknown Source)
    	at java.awt.Container.layout(Unknown Source)
    	at java.awt.Container.doLayout(Unknown Source)
    	at java.awt.Container.validateTree(Unknown Source)
    	at java.awt.Container.validateTree(Unknown Source)
    	at java.awt.Container.validateTree(Unknown Source)
    	at java.awt.Container.validateTree(Unknown Source)
    	at java.awt.Container.validate(Unknown Source)
    	at java.awt.Container.validateUnconditionally(Unknown Source)
    	at java.awt.Window.show(Unknown Source)
    	at java.awt.Component.show(Unknown Source)
    	at java.awt.Component.setVisible(Unknown Source)
    	at java.awt.Window.setVisible(Unknown Source)
    	at test.MainTest.main(MainTest.java:19)
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at boutonRond.RoundButton.getPreferredSize(RoundButton.java:50)
    	at java.awt.FlowLayout.layoutContainer(Unknown Source)
    	at java.awt.Container.layout(Unknown Source)
    	at java.awt.Container.doLayout(Unknown Source)
    	at java.awt.Container.validateTree(Unknown Source)
    	at java.awt.Container.validateTree(Unknown Source)
    	at java.awt.Container.validateTree(Unknown Source)
    	at java.awt.Container.validateTree(Unknown Source)
    	at java.awt.Container.validate(Unknown Source)
    	at java.awt.Window.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    	at java.awt.EventQueue.access$000(Unknown Source)
    	at java.awt.EventQueue$3.run(Unknown Source)
    	at java.awt.EventQueue$3.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue$4.run(Unknown Source)
    	at java.awt.EventQueue$4.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue.dispatchEvent(Unknown Source)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.run(Unknown Source)
    C'est quoi le problème? Accès à mon bouton qui serait null? Pourtant instancié... je ne comprends pas! Merci d'avance si vous pouvez m'éclairer.

  2. #2
    Membre éprouvé
    Avatar de bpy1401
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mars 2003
    Messages
    505
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 63
    Localisation : France, Eure (Haute Normandie)

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

    Informations forums :
    Inscription : Mars 2003
    Messages : 505
    Points : 1 005
    Points
    1 005
    Par défaut
    Bonjour sebeee

    Ton problème est décrit dans la trace.

    at boutonRond.RoundButton.getPreferredSize(RoundButton.java:50)
    c'est en ligne 50 du fichier RoundButton.java

    Donc , si ton code est completement copié

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    int iw = Math.max(icon.getIconWidth(), icon.getIconHeight());
    Je pense fortement que c'est icon qui est null.

  3. #3
    Membre du Club
    Homme Profil pro
    Développeur Java
    Inscrit en
    Septembre 2006
    Messages
    81
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur Java

    Informations forums :
    Inscription : Septembre 2006
    Messages : 81
    Points : 51
    Points
    51
    Par défaut
    Citation Envoyé par bpy1401 Voir le message
    Je pense fortement que c'est icon qui est null.
    Salut bpy1401,

    Non pourtant pas du tout, mon bouton avec l'icone que j'ai sur D:/Temp/tst_boutons/001.png s'affiche correctement.

    C'est très mystérieux je trouve, par contre je viens de tester (hasardeusement) de mettre

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    b1.addActionListener(new MonAction("rond"));
    au lieu de

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    b1.setAction(new MonAction("rond 1"));
    et ca marche! Mais j'ai pas vraiment compris pourquoi, je suis en train de me renseigner là dessus!

  4. #4
    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
    Dans la classe MonAction; utilise le constructeur
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    public AbstractAction(String name, Icon icon)
    sinon tu n'auras pas d'icone associé à ton bouton. C'est l'action qui doit déterminer l'icone.

  5. #5
    Membre du Club
    Homme Profil pro
    Développeur Java
    Inscrit en
    Septembre 2006
    Messages
    81
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur Java

    Informations forums :
    Inscription : Septembre 2006
    Messages : 81
    Points : 51
    Points
    51
    Par défaut
    Mais je vois pas pourquoi ni comment, quand je construis MonAction je n'ai pas forcément d'icone à lui passer.

    Je comprends pas pourquoi ca serait à mon action de déterminer l'icone

  6. #6
    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
    Il est préférable de ne pas mélanger les actions et l'accès direct aux propriétés concernées du bouton.
    D'après la javadoc de AbstractButton.setAction
    Setting the Action results in immediately changing all the properties described in Swing Components Supporting Action.
    Subsequently, the button's properties are automatically updated as the Action's properties change.
    et dans "Swing Components Supporting Action" on trouve en particulier icon : ceci explique le comportement observé.

  7. #7
    Membre du Club
    Homme Profil pro
    Développeur Java
    Inscrit en
    Septembre 2006
    Messages
    81
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur Java

    Informations forums :
    Inscription : Septembre 2006
    Messages : 81
    Points : 51
    Points
    51
    Par défaut
    Ok je vois, c'est un peu plus clair maintenant.

    Merci beaucoup pour ces informations Hervé

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

Discussions similaires

  1. [SP-2007] Cassage d'héritage impossible, erreurs multiples
    Par nonoxp dans le forum SharePoint
    Réponses: 0
    Dernier message: 31/03/2010, 11h04
  2. Erreur d'héritage ou erreur du compilateur?
    Par Klaim dans le forum C++
    Réponses: 2
    Dernier message: 31/01/2010, 22h59
  3. Héritage - erreur de segmentation
    Par gletare dans le forum C++
    Réponses: 2
    Dernier message: 24/06/2006, 22h16
  4. Héritage JButton et methode setEnabled
    Par ceres02 dans le forum AWT/Swing
    Réponses: 3
    Dernier message: 21/05/2006, 18h53
  5. Réponses: 4
    Dernier message: 07/07/2005, 13h03

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