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

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

Composants Java Discussion :

JTree : modifier le font du label du node parent


Sujet :

Composants Java

  1. #1
    Membre régulier
    Homme Profil pro
    Inscrit en
    Août 2012
    Messages
    145
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations forums :
    Inscription : Août 2012
    Messages : 145
    Points : 88
    Points
    88
    Par défaut JTree : modifier le font du label du node parent
    Bonjour,
    J'essaye de trouver comment modifier le label du nœud parent suite à un checkbox sélectionné. Je pensais pouvoir le modifier dans la class NodeSelectionListener, mais je n'ai pas réussi à avoir le label.
    Pouvez vous m'indiquer comment il faut s'y prendre

    Merci

    Drick

  2. #2
    Modérateur
    Avatar de joel.drigo
    Homme Profil pro
    Ingénieur R&D - Développeur Java
    Inscrit en
    Septembre 2009
    Messages
    12 430
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur R&D - Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2009
    Messages : 12 430
    Points : 29 131
    Points
    29 131
    Billets dans le blog
    2
    Par défaut
    Salut,

    Tout ce qui concerne le rendu (l'affichage) particulier des nœuds d'un JTree se fait par un TreeCellRenderer. Pour un nœud donné, il faut déterminer si l'un de ses fils est checked, et choisir la police en fonction, et l'appliquer au TreeCellRenderer. Il faut également penser à rafraichir l'affichage de tous les pères lors de l'édition, puisque la police ne change pas sur le nœud qui change, mais sur ses pères (le plus simple étant de repeindre l'arbre).

    Exemple (j'ai mis des commentaires là où se trouvent les parties importantes) :

    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
    public class TreeCellRendererDemo {
     
    	public static void main(String[] args) {
    		SwingUtilities.invokeLater(() -> new TreeCellRendererDemo());
    	}
     
    	public TreeCellRendererDemo() {
     
    		JFrame frame = new JFrame("Démo");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		frame.getContentPane().add(new JScrollPane(createTree()));
     
    		frame.setSize(300, 300);
    		frame.setLocationRelativeTo(null);
    		frame.setVisible(true);
     
    	}
     
    	private Component createTree() {
    		JTree tree = new JTree(createTreeNode(FileSystemView
    				.getFileSystemView().getDefaultDirectory().toPath()));
    		tree.setRootVisible(false);
    		tree.setShowsRootHandles(true);
    		tree.setCellRenderer(new PathNodeTreeCellRenderer());
    		PathNodeCellEditor editor = new PathNodeCellEditor();
    		tree.setCellEditor(editor);
    		editor.addCellEditorListener(new CellEditorListener() {
     
    			@Override
    			public void editingStopped(ChangeEvent e) {
    				// ******************************************************************************* POUR VOIR CHANGEMENT POLICE SI UN DES FILS EST SELECTIONNE
    				tree.repaint(); 
    				// ******************************************************************************* POUR VOIR CHANGEMENT POLICE SI UN DES FILS EST SELECTIONNE
    			}
     
    			@Override
    			public void editingCanceled(ChangeEvent e) {
    			}
    		});
    		tree.setEditable(true);
    		return tree;
    	}
     
    	private PathNode createTreeNode(Path parent) {
    		boolean isDirectory = Files.isDirectory(parent);
    		PathNode parentNode = new PathNode(parent, isDirectory);
    		if (isDirectory) {
    			Set<Path> paths = new TreeSet<>((p1, p2) -> {
    				boolean d1 = Files.isDirectory(p1);
    				boolean d2 = Files.isDirectory(p2);
    				if ((d1 && d2) || (!d1 && !d2)) {
    					return p1.toString().compareTo(p2.toString());
    				} else if (d1) {
    					return -1;
    				} else {
    					return 1;
    				}
    			});
    			try (DirectoryStream<Path> ds = Files.newDirectoryStream(parent)) {
    				for (Path child : ds) {
    					paths.add(child);
    				}
    				for (Path path : paths) {
    					parentNode.add(createTreeNode(path));
    				}
    			} catch (IOException e) {
    				// throw new RuntimeException(e);
    			}
    		}
    		return parentNode;
    	}
     
    	private static class PathNode extends DefaultMutableTreeNode {
     
    		private static final long serialVersionUID = 1L;
    		private Path path;
    		private boolean directory;
    		private boolean checked;
     
    		public PathNode(Path path, boolean directory) {
    			setUserObject(path);
    			this.directory = directory;
    		}
     
    		public boolean isChecked() {
    			return checked;
    		}
     
    		public void setChecked(boolean checked) {
    			this.checked = checked;
    		}
     
    		public String getName() {
    			return path.getFileName().toString();
    		}
     
    		public boolean isDirectory() {
    			return directory;
    		}
     
    		@Override
    		public void setUserObject(Object userObject) {
    			Objects.requireNonNull(userObject);
    			this.path = (Path) userObject;
    			super.setUserObject(userObject);
    		}
     
    		/*public Path getPathObject() {
    			return path;
    		}*/
     
    		public boolean isChecked(boolean deep) {
    			if ( deep ) {
    				boolean checked = false;
    				for(int i=0; i<getChildCount(); i++) {
    					PathNode child = (PathNode) getChildAt(i);
    					if ( child.isChecked() ) {
    						checked = true;
    						break;
    					}
    					if ( child.isChecked(true) ) {
    						checked = true;
    						break;
    					}
    				}
    				return checked;
    			}
    			else {
    				return isChecked();
    			}
    		}
     
    	}
     
    	private static class PathTreeCellRenderer extends DefaultTreeCellRenderer {
     
    		private static final long serialVersionUID = 1L;
     
    		@Override
    		public Component getTreeCellRendererComponent(JTree tree, Object value,
    				boolean selected, boolean expanded, boolean leaf, int row,
    				boolean hasFocus) {
    			PathNode node = (PathNode) value;
    			if (node.isDirectory()) {
    				leaf = false;
    			}
    			Component component = super.getTreeCellRendererComponent(tree,
    					value, selected, expanded, leaf, row, hasFocus);
    			setText(node.getName());
    			// ******************************************************************************* CHANGEMENT POLICE SI UN DES FILS EST SELECTIONNE
    			if ( node.isChecked(true) ) {
    				setFont(tree.getFont().deriveFont(Font.BOLD));
    			}
    			else {
    				setFont(null);
    			}
    			// ******************************************************************************* CHANGEMENT POLICE SI UN DES FILS EST SELECTIONNE
    			component.revalidate();
    			return component;
    		}
     
    	}
     
    	private static class PathNodeTreeCellRenderer extends PathTreeCellRenderer {
     
    		private static final long serialVersionUID = 1L;
    		private JCheckBox checkBox = new JCheckBox();
    		private JPanel panel;
    		private int workAroundWidth;
    		private int workAroundHeight;
     
    		PathNodeTreeCellRenderer() {
    			panel = new JPanel() {
    				@Override
    				public void reshape(int x, int y, int w, int h) {
    					w=workAroundWidth;
    					h=workAroundHeight;
    					super.reshape(x, y, w, h);
    				}
    			};
    			panel.setLayout(new FlowLayout(FlowLayout.LEADING, 0, 0));
    			panel.setOpaque(false);
    			checkBox.setOpaque(false);
    			panel.add(checkBox);
    			panel.add(this);
    			panel.revalidate();
    		}
     
    		@Override
    		public Component getTreeCellRendererComponent(JTree tree, Object value,
    				boolean selected, boolean expanded, boolean leaf, int row,
    				boolean hasFocus) {
    			PathNode node = (PathNode) value;
    			checkBox.setSelected(node.isChecked());
    			Component comp = super.getTreeCellRendererComponent(tree,
    					value, selected, expanded, leaf, row, hasFocus);
    			panel.revalidate();
    			Dimension dim = panel.getPreferredSize();
    			workAroundWidth=dim.width;
    			workAroundHeight=dim.height;
    			return panel;
    		}
     
    	}
     
    	private static class PathNodeCellEditor extends DefaultCellEditor {
     
    		private static final long serialVersionUID = 1L;
    		private PathNode node;
    		private PathTreeCellRenderer cellRenderer = new PathTreeCellRenderer();
    		private JPanel panel = new JPanel();
     
    		public PathNodeCellEditor() {
    			super(new JCheckBox());
    			panel.setLayout(new FlowLayout(FlowLayout.LEADING, 0, 0));
    			panel.setOpaque(false);
    			JCheckBox checkBox = (JCheckBox) (super.getComponent());
    			checkBox.setOpaque(false);
    			panel.add(checkBox);
    			panel.add(cellRenderer);
    			panel.revalidate();
    		}
     
    		public Component getTreeCellEditorComponent(JTree tree,
    				Object value, boolean selected, boolean expanded,
    				boolean leaf, int row) {
    			JCheckBox editor = null;
    			node = (PathNode) value;
    			if (node != null) {
    				editor = (JCheckBox) (super.getComponent());
    				editor.setSelected(node.isChecked());
    			}
    			cellRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, true);
    			panel.revalidate();
    			return panel;
    		}
     
    		public Object getCellEditorValue() {
    			JCheckBox editor = (JCheckBox) (super.getComponent());
    			node.setChecked(editor.isSelected());
    			return node.getUserObject();
    		}
     
    	}
     
    }
    L'expression "ça marche pas" ne veut rien dire. Indiquez l'erreur, et/ou les comportements attendus et obtenus, et donnez un Exemple Complet Minimal qui permet de reproduire le problème.
    La plupart des réponses à vos questions sont déjà dans les FAQs ou les Tutoriels, ou peut-être dans une autre discussion : utilisez la recherche interne.
    Des questions sur Java : consultez le Forum Java. Des questions sur l'EDI Eclipse ou la plateforme Eclipse RCP : consultez le Forum Eclipse.
    Une question correctement posée et rédigée et vous aurez plus de chances de réponses adaptées et rapides.
    N'oubliez pas de mettre vos extraits de code entre balises CODE (Voir Mode d'emploi de l'éditeur de messages).
    Nouveau sur le forum ? Consultez Les Règles du Club.

Discussions similaires

  1. Réponses: 1
    Dernier message: 06/07/2007, 13h46
  2. Modifier la fonte d'une dialogue
    Par rzayani dans le forum MFC
    Réponses: 3
    Dernier message: 03/10/2006, 13h49
  3. [D6] Modifier la Font d'un TTreeNode ?
    Par Lung dans le forum Composants VCL
    Réponses: 4
    Dernier message: 14/02/2006, 13h55
  4. [AWT] modifier la font d'un element d'une Liste
    Par toxyko dans le forum Composants
    Réponses: 5
    Dernier message: 05/11/2005, 12h50
  5. [JTree] modifier editer supprimer
    Par agougeon dans le forum Composants
    Réponses: 2
    Dernier message: 18/05/2005, 15h41

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