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

EDT/SwingWorker Java Discussion :

Focus et CardLayout


Sujet :

EDT/SwingWorker Java

  1. #1
    Membre régulier
    Homme Profil pro
    Dévelopeur Cobol + Java J2SE
    Inscrit en
    Novembre 2007
    Messages
    72
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Dévelopeur Cobol + Java J2SE
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2007
    Messages : 72
    Points : 77
    Points
    77
    Par défaut Focus et CardLayout
    bonjour,
    je cherche à résoudre un problème de prise de focus quand je navigue entre jpanels d'un cardLayout, peut être ne suis je pas dans le bon forum à vous de me dire s'il vous plaît.

    requestFocusInWindow() doit être invoqué après que le composant soit "realized" mais avant que la frame soit affichée.

    Ok mais qu'en est il dans le cas suivant :
    - frame contient un panelTop en haut et un cardlayout en bas.
    - panelTop contient tfTop
    - cardlayout contient card1 et card2
    - card1 contient cbBot1 et cbBot2
    - card2 contient tfBot1 et tfBot2.

    quand je fais "F1" et que card1 est actif je veux
    - activer card2 et avec curseur sur tfBot2 directement, sans que focusGained() de tfBot1 n'ait été invoqué.
    Et si le focus était sur un champ de card1, sans que focusGained() de tfTop n'ait été invoqué non plus.

    En fait je veux que mon focus aille directement où je lui dis sans passer ailleurs.

    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
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
     
    public class CardLayoutDemoFocus {
     
        String current = COMBO_PANEL;
        JPanel conteneur; //a panel that uses CardLayout
        final static String COMBO_PANEL = "Card with combos";
        final static String TEXTPANEL = "Card with JTextField";
        JComboBox cbBot1, cbBot2;
        JTextField tftop, tfBot1, tfBot2;
     
        public void addComponentToPane(Container pane) {
            String sActionF1 = "f1";
            String sActionReleaseF1 = "rf1";
            ((JPanel) pane).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).
                    put(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0, false), sActionF1);
            ((JPanel) pane).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).
                    put(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0, true), sActionReleaseF1);
            ((JPanel) pane).getActionMap().put(sActionF1, new ActionF1());
            ((JPanel) pane).getActionMap().put(sActionReleaseF1, new ActionF1Release());
            JPanel topPane = new JPanel(); //use FlowLayout
            cbBot1 = new JComboBox(new String[]{"cb1"});
            cbBot2 = new JComboBox(new String[]{"cb2"});
            tftop = new JTextField("tfTop",20);
            tfBot1 = new JTextField("tfBot1", 20);
            tfBot2 = new JTextField("tfBot2", 20);
            tftop.addFocusListener(new FocusAdapter() {
                @Override
                public void focusGained(FocusEvent e) {
                    System.out.println("perdu ...");
                }
            });
            topPane.add(tftop);
     
            //Create the "contenu 1".
            JPanel card1 = new JPanel();
            card1.add(cbBot1);
            card1.add(cbBot2);
     
            //Create the "contenu 2".
            JPanel card2 = new JPanel();
            card2.add(tfBot1);
            card2.add(tfBot2);
     
            //Create the panel that contains the "conteneur".
            conteneur = new JPanel(new CardLayout());
            conteneur.add(card1, COMBO_PANEL);
            conteneur.add(card2, TEXTPANEL);
     
            pane.add(topPane, BorderLayout.PAGE_START);
            pane.add(conteneur, BorderLayout.CENTER);
        }
     
        /**
         * Create the GUI and show it. For thread safety, this method should be
         * invoked from the event dispatch thread.
         */
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("CardLayoutDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            //Create and set up the content pane.
            CardLayoutDemoFocus demo = new CardLayoutDemoFocus();
            demo.addComponentToPane(frame.getContentPane());
     
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        }
     
        public static void main(String[] args) {
            /* Use an appropriate Look and Feel */
            try {
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            } catch (UnsupportedLookAndFeelException ex) {
            } catch (IllegalAccessException ex) {
            } catch (InstantiationException ex) {
            } catch (ClassNotFoundException ex) {
            }
            /* Turn off metal's use of bold fonts */
            UIManager.put("swing.boldMetal", Boolean.FALSE);
     
            //Schedule a job for the event dispatch thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    createAndShowGUI();
                }
            });
        }
     
        class ActionF1 extends AbstractAction {
     
            @Override
            public void actionPerformed(ActionEvent e) {
                if (first_f1) {
                    first_f1 = false;
                    CardLayout cl = (CardLayout) (conteneur.getLayout());
                    Component toBeFocused = null;
                    if (current.contains(COMBO_PANEL)) {
                        current = TEXTPANEL;
                        toBeFocused = tfBot1;
                    } else if (current.contains(TEXTPANEL)) {
                        current = COMBO_PANEL;
                        toBeFocused = cbBot2;
                    }
                    toBeFocused.requestFocusInWindow();
                    cl.show(conteneur, current);
                }
            }
        }
     
        class ActionF1Release extends AbstractAction {
     
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                first_f1 = true;
            }
        }
        boolean first_f1 = true;
    }

  2. #2
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 481
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : Belgique

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

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 481
    Points : 48 806
    Points
    48 806
    Par défaut
    Vu la précision de ton besoin, je crois que tu va devoir fournir un FocusTraversalPolicy personnaliser qui force tfBot2 à recevoir le focus en premier dans card2.

  3. #3
    Membre régulier
    Homme Profil pro
    Dévelopeur Cobol + Java J2SE
    Inscrit en
    Novembre 2007
    Messages
    72
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Dévelopeur Cobol + Java J2SE
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2007
    Messages : 72
    Points : 77
    Points
    77
    Par défaut
    Citation Envoyé par tchize_ Voir le message
    Vu la précision de ton besoin, je crois que tu va devoir fournir un FocusTraversalPolicy personnaliser qui force tfBot2 à recevoir le focus en premier dans card2.
    oui merci pour la suggestion, effectivement je viens de le faire et j'ai aussi utilisé un RequestFocusListener() voir sujet ici https://tips4java.wordpress.com/2010.../dialog-focus/.

    Du coup ça marche comme je veux et le focus ne passe jamais dans le tf du haut quand on presse f1.

    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
    import java.awt.BorderLayout;
    import java.awt.CardLayout;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FocusTraversalPolicy;
    import java.awt.event.ActionEvent;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.awt.event.KeyEvent;
    import java.util.ArrayList;
    import javax.swing.AbstractAction;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
     
    public class CardLayoutDemoFocus {
     
        static ArrayList<Component> lstCbPnl = new ArrayList<Component>();
        static ArrayList<Component> lstTfPnl = new ArrayList<Component>();
        String current = COMBO_PANEL;
        JPanel conteneur;
        final static String COMBO_PANEL = "Card with combos";
        final static String TEXTPANEL = "Card with JTextFields";
        JComboBox cbBot1, cbBot2;
        JTextField tftop, tfBot1, tfBot2;
        static JFrame frame;
     
        public void addComponentToPane(Container pane) {
            String sActionF1 = "f1";
            String sActionReleaseF1 = "rf1";
            ((JPanel) pane).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).
                    put(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0, false), sActionF1);
            ((JPanel) pane).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).
                    put(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0, true), sActionReleaseF1);
            ((JPanel) pane).getActionMap().put(sActionF1, new ActionF1());
            ((JPanel) pane).getActionMap().put(sActionReleaseF1, new ActionF1Release());
            JPanel topPane = new JPanel(); //use FlowLayout
            cbBot1 = new JComboBox(new String[]{"cb1"});
            cbBot2 = new JComboBox(new String[]{"cb2"});
            tfBot1 = new JTextField("tfBot1", 9);
            tfBot2 = new JTextField("tfBot2", 9);
            // https://tips4java.wordpress.com/2010/03/14/dialog-focus/
            tfBot2.addAncestorListener(new RequestFocusListener(false));
            cbBot2.addAncestorListener(new RequestFocusListener(false));
     
            tftop = new JTextField("tfTop", 19);
            tftop.addFocusListener(new FocusAdapter() {
                @Override
                public void focusGained(FocusEvent e) {
                    System.out.println("perdu ...");
                }
            });
            topPane.add(tftop);
     
            //Create "contenu 1".
            JPanel card1 = new JPanel();
            card1.add(cbBot1);
            card1.add(cbBot2);
            lstCbPnl.add(cbBot2);
            lstCbPnl.add(cbBot1);
            lstCbPnl.add(tftop);
     
            //Create "contenu 2".
            JPanel card2 = new JPanel();
            card2.add(tfBot1);
            card2.add(tfBot2);
            lstTfPnl.add(tfBot2);
            lstTfPnl.add(tfBot1);
            lstTfPnl.add(tftop);
     
            //Create the container that contains the "cardLayout".
            conteneur = new JPanel(new CardLayout());
            conteneur.add(card1, COMBO_PANEL);
            conteneur.add(card2, TEXTPANEL);
     
            pane.add(topPane, BorderLayout.PAGE_START);
            pane.add(conteneur, BorderLayout.CENTER);
        }
     
        /**
         * Create the GUI and show it. For thread safety, this method should be
         * invoked from the event dispatch thread.
         */
        private static void createAndShowGUI() {
            frame = new JFrame("CardLayoutDemo");
            frame.setPreferredSize(new Dimension(260, 130));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            CardLayoutDemoFocus demo = new CardLayoutDemoFocus();
            demo.addComponentToPane(frame.getContentPane());
     
            //Display the window.
            frame.pack();
            frame.setFocusTraversalPolicy(new MyOwnFocusTraversalPolicy(lstCbPnl));
            frame.setVisible(true);
     
        }
     
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    createAndShowGUI();
                }
            });
        }
     
        boolean first_f1 = true;
     
        class ActionF1 extends AbstractAction {
     
            @Override
            public void actionPerformed(ActionEvent e) {
                if (first_f1) {
                    first_f1 = false;
                    CardLayout cl = (CardLayout) (conteneur.getLayout());
                    ArrayList lFocus = null;
                    if (current.contains(COMBO_PANEL)) {
                        current = TEXTPANEL;
                        lFocus = lstTfPnl;
                    } else if (current.contains(TEXTPANEL)) {
                        current = COMBO_PANEL;
                        lFocus = lstCbPnl;
                    }
                    frame.setFocusTraversalPolicy(
                            new MyOwnFocusTraversalPolicy(lFocus));
                    cl.show(conteneur, current);
                }
            }
        }
     
        class ActionF1Release extends AbstractAction {
     
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                first_f1 = true;
            }
        }
     
        public static class MyOwnFocusTraversalPolicy
                extends FocusTraversalPolicy {
     
            ArrayList<Component> order;
     
            public MyOwnFocusTraversalPolicy(ArrayList<Component> order) {
                this.order = new ArrayList<Component>(order.size());
                this.order.addAll(order);
            }
     
            @Override
            public Component getComponentAfter(Container focusCycleRoot,
                    Component aComponent) {
                int idx = (order.indexOf(aComponent) + 1) % order.size();
                return order.get(idx);
            }
     
            @Override
            public Component getComponentBefore(Container focusCycleRoot,
                    Component aComponent) {
                int idx = order.indexOf(aComponent) - 1;
                if (idx < 0) {
                    idx = order.size() - 1;
                }
                return order.get(idx);
            }
     
            @Override
            public Component getDefaultComponent(Container focusCycleRoot) {
                return order.get(0);
            }
     
            @Override
            public Component getLastComponent(Container focusCycleRoot) {
                return order.get(order.size() - 1);
            }
     
            @Override
            public Component getFirstComponent(Container focusCycleRoot) {
                return order.get(0);
            }
        }
    }

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

Discussions similaires

  1. Rajout du focus
    Par Claythest dans le forum Composants VCL
    Réponses: 2
    Dernier message: 10/06/2003, 17h10
  2. [SWING]jTable + Focus
    Par chady dans le forum Composants
    Réponses: 5
    Dernier message: 27/02/2003, 14h51
  3. Comment être sure que mon appli prenne le focus ?
    Par AmaX dans le forum Composants VCL
    Réponses: 2
    Dernier message: 21/12/2002, 15h00
  4. Créer une fenêtre flottante qui ne peut avoir le focus
    Par BestofMac dans le forum Composants VCL
    Réponses: 4
    Dernier message: 17/07/2002, 10h46
  5. focus en C
    Par killpilot dans le forum C
    Réponses: 8
    Dernier message: 19/04/2002, 19h19

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