Bonjour,
Je veux mprimer une table sans laisser de marge à gauche et à droite, et aussi changer la position de message headerForma. J'utilise pour l'impression ces codes là:

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
table = new JTable(){
			  public java.awt.print.Printable getPrintable(PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat) {
	        		return new printtable(table, printMode, headerFormat, footerFormat);
	        	};
	        };
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
 
btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
 
 
 
	               try {
						table.print(PrintMode.NORMAL, new MessageFormat("<html><body><p><i> LE "+date.getText()+ "  --  "+ heure.getText()+"</i></p><p><i>Liste des clients du projet :"+comboBox.getSelectedItem().toString()+"</i></p><p>Nombre des clients:"+ textField.getText()+"</p></body></html>"),new MessageFormat("") );
					} catch (PrinterException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} 
 
 
 
 
			}
		});
Classe Styledtext:
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
 
package training1;
 
 
 
//package training1;
 
//package javax.swing.jtable;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
 
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Document;
import javax.swing.text.EditorKit;
import javax.swing.text.Element;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.html.HTMLEditorKit;
 
/**
 * 
 */
 
/*
 * This class is adapted from java 1.7 TablePrintable source & PStyledText (author: Lance Good) from Piccolo2D API.
 * 
 * Copyright (c) 2002-@year@, University of Maryland
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided
 * that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of conditions
 * and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
 * and the following disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the University of Maryland nor the names of its contributors may be used to
 * endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Piccolo was written at the Human-Computer Interaction Laboratory www.cs.umd.edu/hcil by Jesse Grosjean
 * under the supervision of Ben Bederson. The Piccolo website is www.cs.umd.edu/hcil/piccolo.
 */
public class StyledText {
 
	private List<AttributedString> stringContents;
	private LineInfo[] lines;
	private Document document;
	private double width;
	private double height;
 
	/**
         * @throws IOException 
         * @throws BadLocationException 
         * 
         */
	public StyledText(String text, final Font defaultFont, FontRenderContext frc, float maxWidth, float maxHeight) throws IOException, BadLocationException {
 
		if ( text==null ) {
			text="";
		}
 
		try (Reader stringReader = new StringReader(text)) {
			EditorKit editorKit;
			if (text.startsWith("<html>")) {
				editorKit = new HTMLEditorKit();
				document = editorKit.createDefaultDocument(); 
			} else {
				editorKit = new StyledEditorKit();
				//document = editorKit.createDefaultDocument(); 
				StyleContext styles = new StyleContext();
				Style style = styles.addStyle(StyleContext.DEFAULT_STYLE, null); 
			    StyleConstants.setFontFamily(style, defaultFont.getFamily());
			    StyleConstants.setFontSize(style, defaultFont.getSize());
			    StyleConstants.setItalic(style, defaultFont.isItalic());
			    StyleConstants.setBold(style, defaultFont.isBold());
				document = new DefaultStyledDocument(styles);
			}
			editorKit.read(stringReader, document, 0);
		}
 
		// The paragraph start and end indices
		ArrayList<RunInfo> pEnds = null;
 
		// The current position in the specified range
		int pos = 0;
 
		// First get the actual text and stick it in an Attributed String
		try {
 
			stringContents = new ArrayList<>();
			pEnds = new ArrayList<>();
 
			String s = document.getText(0, document.getLength());
			StringTokenizer tokenizer = new StringTokenizer(s, "\n", true);
 
			// lastNewLine is used to detect the case when two newlines follow
			// in direct succession
			// & lastNewLine should be true to start in case the first character
			// is a newline
			boolean lastNewLine = true;
			for ( ; tokenizer.hasMoreTokens();  ) {
				String token = tokenizer.nextToken();
 
				// If the token
				if (token.equals("\n")) {
					if (lastNewLine) {
						stringContents.add(new AttributedString(" "));
						pEnds.add(new RunInfo(pos, pos + 1));
 
						pos = pos + 1;
 
						lastNewLine = true;
					} else {
						pos = pos + 1;
 
						lastNewLine = true;
					}
				}
				// If the token is empty - create an attributed string with a
				// single space
				// since LineBreakMeasurers don't work with an empty string
				// - note that this case should only arise if the document is
				// empty
				else if (token.equals("")) {
					stringContents.add(new AttributedString(" "));
					pEnds.add(new RunInfo(pos, pos));
 
					lastNewLine = false;
				}
				// This is the normal case - where we have some text
				else {
					stringContents.add(new AttributedString(token));
					pEnds.add(new RunInfo(pos, pos + token.length()));
 
					// Increment the position
					pos = pos + token.length();
 
					lastNewLine = false;
				}
			}
 
			// Add one more newline if the last character was a newline
			if (lastNewLine) {
				stringContents.add(new AttributedString(" "));
				pEnds.add(new RunInfo(pos, pos + 1));
 
				lastNewLine = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
 
		// The default style context - which will be reused
		StyleContext style = StyleContext.getDefaultStyleContext();
 
		RunInfo pEnd = null;
		for (int i = 0; i < stringContents.size(); i++) {
			pEnd = pEnds.get(i);
			pos = pEnd.runStart;
 
			// The current element will be used as a temp variable while
			// searching
			// for the leaf element at the current position
			Element curElement = null;
 
			// Small assumption here that there is one root element - can fix
			// for more general support later
			Element rootElement = document.getDefaultRootElement();
 
			// If the string is length 0 then we just need to add the attributes
			// once
			if (pEnd.runStart != pEnd.runLimit) {
				// OK, now we loop until we find all the leaf elements in the
				// range
				while (pos < pEnd.runLimit) {
 
					// Before each pass, start at the root
					curElement = rootElement;
 
					// Now we descend the hierarchy until we get to a leaf
					while (!curElement.isLeaf()) {
						curElement = curElement.getElement(curElement
								.getElementIndex(pos));
					}
 
					// These are the mandatory attributes
 
					AttributeSet attributes = curElement.getAttributes();
					Color foreground = style.getForeground(attributes);
 
					((AttributedString) stringContents.get(i)).addAttribute(
							TextAttribute.FOREGROUND, foreground, (int) Math
									.max(0, curElement.getStartOffset()
											- pEnd.runStart), (int) Math.min(
									pEnd.runLimit - pEnd.runStart,
									curElement.getEndOffset() - pEnd.runStart));
 
					Font font = (attributes.isDefined(StyleConstants.FontSize) || attributes
							.isDefined(StyleConstants.FontFamily)) ? style
							.getFont(attributes) : null;
					if (font == null) {
						if (document instanceof DefaultStyledDocument) {
							font = style
									.getFont(((DefaultStyledDocument) document)
											.getCharacterElement(pos)
											.getAttributes());
							if (font == null) {
								font = style
										.getFont(((DefaultStyledDocument) document)
												.getParagraphElement(pos)
												.getAttributes());
							}
							if (font == null) {
								font = style.getFont(rootElement
										.getAttributes());
							}
						} else {
							font = style.getFont(rootElement.getAttributes());
						}
					}
					if (font != null) {
						((AttributedString) stringContents.get(i))
								.addAttribute(
										TextAttribute.FONT,
										font,
										(int) Math.max(0,
												curElement.getStartOffset()
														- pEnd.runStart),
										(int) Math.min(pEnd.runLimit
												- pEnd.runStart,
												curElement.getEndOffset()
														- pEnd.runStart));
					}
 
					// These are the optional attributes
 
					Color background = (attributes
							.isDefined(StyleConstants.Background)) ? style
							.getBackground(attributes) : null;
					if (background != null) {
						((AttributedString) stringContents.get(i))
								.addAttribute(
										TextAttribute.BACKGROUND,
										background,
										(int) Math.max(0,
												curElement.getStartOffset()
														- pEnd.runStart),
										(int) Math.min(pEnd.runLimit
												- pEnd.runStart,
												curElement.getEndOffset()
														- pEnd.runStart));
					}
 
					boolean underline = StyleConstants.isUnderline(attributes);
					if (underline) {
						((AttributedString) stringContents.get(i))
								.addAttribute(
										TextAttribute.UNDERLINE,
										Boolean.TRUE,
										(int) Math.max(0,
												curElement.getStartOffset()
														- pEnd.runStart),
										(int) Math.min(pEnd.runLimit
												- pEnd.runStart,
												curElement.getEndOffset()
														- pEnd.runStart));
					}
 
					boolean strikethrough = StyleConstants
							.isStrikeThrough(attributes);
					if (strikethrough) {
						((AttributedString) stringContents.get(i))
								.addAttribute(
										TextAttribute.STRIKETHROUGH,
										Boolean.TRUE,
										(int) Math.max(0,
												curElement.getStartOffset()
														- pEnd.runStart),
										(int) Math.min(pEnd.runLimit
												- pEnd.runStart,
												curElement.getEndOffset()
														- pEnd.runStart));
					}
 
					// And set the position to the end of the given attribute
					pos = curElement.getEndOffset();
				}
			} else {
				// Before each pass, start at the root
				curElement = rootElement;
 
				// Now we descend the hierarchy until we get to a leaf
				while (!curElement.isLeaf()) {
					curElement = curElement.getElement(curElement
							.getElementIndex(pos));
				}
 
				// These are the mandatory attributes
 
				AttributeSet attributes = curElement.getAttributes();
				Color foreground = style.getForeground(attributes);
 
				((AttributedString) stringContents.get(i)).addAttribute(
						TextAttribute.FOREGROUND, foreground, (int) Math.max(0,
								curElement.getStartOffset() - pEnd.runStart),
						(int) Math.min(pEnd.runLimit - pEnd.runStart,
								curElement.getEndOffset() - pEnd.runStart));
 
				// These are the optional attributes
 
				Font font = (attributes.isDefined(StyleConstants.FontSize) || attributes
						.isDefined(StyleConstants.FontFamily)) ? style
						.getFont(attributes) : null;
				if (font == null) {
					if (document instanceof DefaultStyledDocument) {
						font = style.getFont(((DefaultStyledDocument) document)
								.getCharacterElement(pos).getAttributes());
						if (font == null) {
							font = style
									.getFont(((DefaultStyledDocument) document)
											.getParagraphElement(pos)
											.getAttributes());
						}
						if (font == null) {
							font = style.getFont(rootElement.getAttributes());
						}
					} else {
						font = style.getFont(rootElement.getAttributes());
					}
				}
				if (font != null) {
					((AttributedString) stringContents.get(i)).addAttribute(
							TextAttribute.FONT, font, (int) Math
									.max(0, curElement.getStartOffset()
											- pEnd.runStart), (int) Math.min(
									pEnd.runLimit - pEnd.runStart,
									curElement.getEndOffset() - pEnd.runStart));
				}
 
				Color background = (attributes
						.isDefined(StyleConstants.Background)) ? style
						.getBackground(attributes) : null;
				if (background != null) {
					((AttributedString) stringContents.get(i)).addAttribute(
							TextAttribute.BACKGROUND, background, (int) Math
									.max(0, curElement.getStartOffset()
											- pEnd.runStart), (int) Math.min(
									pEnd.runLimit - pEnd.runStart,
									curElement.getEndOffset() - pEnd.runStart));
				}
 
				boolean underline = StyleConstants.isUnderline(attributes);
				if (underline) {
					((AttributedString) stringContents.get(i)).addAttribute(
							TextAttribute.UNDERLINE, Boolean.TRUE, (int) Math
									.max(0, curElement.getStartOffset()
											- pEnd.runStart), (int) Math.min(
									pEnd.runLimit - pEnd.runStart,
									curElement.getEndOffset() - pEnd.runStart));
				}
 
				boolean strikethrough = StyleConstants
						.isStrikeThrough(attributes);
				if (strikethrough) {
					((AttributedString) stringContents.get(i)).addAttribute(
							TextAttribute.STRIKETHROUGH, Boolean.TRUE,
							(int) Math.max(0, curElement.getStartOffset()
									- pEnd.runStart), (int) Math.min(
									pEnd.runLimit - pEnd.runStart,
									curElement.getEndOffset() - pEnd.runStart));
				}
			}
		}
 
		recomputeLayout(frc, maxWidth, maxHeight);
	}
 
	public double getHeight() {
		return height;
	}
	public double getWidth() {
		return width;
	}
 
	public void recomputeLayout(FontRenderContext frc, float maxWidth, float maxHeight) {
 
		ArrayList<LineInfo> linesList = new ArrayList<>();
 
		double textWidth = 0;
		double textHeight = 0;
 
		for(int i=0; i<stringContents.size(); i++) {		
 
			AttributedString ats = (AttributedString)stringContents.get(i);
			AttributedCharacterIterator itr = ats.getIterator();
 
			LineBreakMeasurer measurer;
			ArrayList<Integer> breakList = null;
 
			// First we have to do an initial pass with a LineBreakMeasurer to
			// find out where Swing is going to break the lines - i.e.
			// because it doesn't use fractional metrics
 
			measurer = new LineBreakMeasurer(itr, frc);
			breakList = new ArrayList<>();
 
			measurer.nextLayout(Math.min(maxWidth, Float.MAX_VALUE));
			breakList.add(new Integer(measurer.getPosition()));
 
			measurer = new LineBreakMeasurer(itr, frc);
 
			// Need to change the lineinfo data structure to know about multiple
			// text layouts per line
 
			LineInfo lineInfo = null;
			boolean newLine = true;
			double lineWidth = 0;
			while (measurer.getPosition() < itr.getEndIndex()) {
				TextLayout aTextLayout = null;
 
				if (newLine) {
				    newLine = false;
 
				    // Add in the old line dimensions
				    double lineHeight = (lineInfo == null) ? 0 : lineInfo.maxAscent+lineInfo.maxDescent+lineInfo.leading;
				    textHeight = textHeight+lineHeight;
				    textWidth = Math.max(textWidth,lineWidth);
 
				    // Now create a new line
				    lineInfo = new LineInfo();
				    linesList.add(lineInfo);				    
				}
 
			    int lineEnd = ((Integer)breakList.get(0)).intValue();			    
			    if (lineEnd <= itr.getRunLimit()) {
			        breakList.remove(0);
			        newLine = true;
			    }
 
				aTextLayout = measurer.nextLayout(Float.MAX_VALUE,Math.min(lineEnd,itr.getRunLimit()),false);
 
				SegmentInfo sInfo = new SegmentInfo();
				sInfo.font = (Font)itr.getAttribute(TextAttribute.FONT);
				sInfo.foreground = (Color)itr.getAttribute(TextAttribute.FOREGROUND);
				sInfo.background = (Color)itr.getAttribute(TextAttribute.BACKGROUND);
				sInfo.underline = (Boolean)itr.getAttribute(TextAttribute.UNDERLINE);
				sInfo.layout = aTextLayout;
 
				FontMetrics metrics = StyleContext.getDefaultStyleContext().getFontMetrics((Font)itr.getAttribute(TextAttribute.FONT));
				lineInfo.maxAscent = Math.max(lineInfo.maxAscent,metrics.getMaxAscent());
				lineInfo.maxDescent = Math.max(lineInfo.maxDescent,metrics.getMaxDescent());
				lineInfo.leading = Math.max(lineInfo.leading,metrics.getLeading());
 
				lineInfo.segments.add(sInfo);
 
				itr.setIndex(measurer.getPosition());
				lineWidth = lineWidth+aTextLayout.getAdvance();
			}
 
		    double lineHeight = (lineInfo == null) ? 0 : lineInfo.maxAscent+lineInfo.maxDescent+lineInfo.leading;
		    textHeight = textHeight+lineHeight;
		    textWidth = Math.max(textWidth,lineWidth);
		}
 
		lines = linesList.toArray(new LineInfo[linesList.size()]);
 
		width = textWidth;
		height = Math.min( Math.max(textHeight,getInitialFontHeight()), maxHeight ); 
 
	}
 
	public double getInitialFontHeight() {
 
		// Small assumption here that there is one root element - can fix
		// for more general support later
		Element rootElement = document.getDefaultRootElement();
 
		// The current element will be used as a temp variable while searching
		// for the leaf element at the current position
		Element curElement = rootElement;
 
		// Now we descend the hierarchy until we get to a leaf
		while (!curElement.isLeaf()) {
			curElement = curElement.getElement(curElement.getElementIndex(0));
		}
 
		StyleContext context = StyleContext.getDefaultStyleContext();
		Font font = context.getFont(curElement.getAttributes());
 
		FontMetrics curFM = context.getFontMetrics(font);
 
		return curFM.getMaxAscent() + curFM.getMaxDescent() + curFM.getLeading();
	}
 
	protected static class RunInfo {
		public int runStart;
		public int runLimit;
 
		public RunInfo() {
		}
 
		public RunInfo(int runStart, int runLimit) {
			this.runStart = runStart;
			this.runLimit = runLimit;	
		}
	} 
 
	protected static class LineInfo {
	    public List<SegmentInfo> segments;
		public double maxAscent;
		public double	maxDescent;
		public double leading;
 
		public LineInfo() {
		    segments = new ArrayList<>();
		}
	}
 
	protected static class SegmentInfo {
		public TextLayout layout;
		public Font font;
		public Color foreground;
		public Color background;
		public Boolean underline;
 
		public SegmentInfo() {		    
		}
	}
 
	public void drawString(Graphics2D g2, int tx, int ty) {
 
		Line2D paintLine = new Line2D.Double();
 
		float x = tx;
		float y = ty;
		float bottomY = (float) (ty + getHeight() );
 
		if (lines == null || lines.length == 0) {
			return;
		} 
 
		float curX;
		for (int i=0; i<lines.length; i++) {
			y += lines[i].maxAscent;
			curX = x;
 
			if (bottomY < y) {
				return;
			}					
 
			for(int j=0; j<lines[i].segments.size(); j++) {			    
			    SegmentInfo sInfo = lines[i].segments.get(j);
				float width = sInfo.layout.getAdvance();
 
				if (sInfo.background != null) {
					g2.setPaint(sInfo.background);
					g2.fill(new Rectangle2D.Double(curX,y-lines[i].maxAscent,width,lines[i].maxAscent+lines[i].maxDescent+lines[i].leading));					
				}
 
				if (sInfo.font != null) {
				    g2.setFont(sInfo.font);
				}
 
				// Manually set the paint - this is specified in the AttributedString but seems to be
				// ignored by the TextLayout.  To handle multiple colors we should be breaking up the lines
				// but that functionality can be added later as needed
				g2.setPaint(sInfo.foreground);
				sInfo.layout.draw(g2, curX, y);
 
				// Draw the underline and the strikethrough after the text
				if (sInfo.underline != null) {
					paintLine.setLine(x,y+lines[i].maxDescent/2,x+width,y+lines[i].maxDescent/2);
					g2.draw(paintLine);	
				}
 
				curX = curX + width;
		    }
 
			y += lines[i].maxDescent + lines[i].leading;			
		}
	}
 
}
et une autre Printtable:
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
package training1;
 
 
 
//package training1;
 
//package javax.swing.jtable;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
 
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Document;
import javax.swing.text.EditorKit;
import javax.swing.text.Element;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.html.HTMLEditorKit;
 
/**
 * 
 */
 
/*
 * This class is adapted from java 1.7 TablePrintable source & PStyledText (author: Lance Good) from Piccolo2D API.
 * 
 * Copyright (c) 2002-@year@, University of Maryland
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided
 * that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of conditions
 * and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
 * and the following disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the University of Maryland nor the names of its contributors may be used to
 * endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Piccolo was written at the Human-Computer Interaction Laboratory www.cs.umd.edu/hcil by Jesse Grosjean
 * under the supervision of Ben Bederson. The Piccolo website is www.cs.umd.edu/hcil/piccolo.
 */
public class StyledText {
 
	private List<AttributedString> stringContents;
	private LineInfo[] lines;
	private Document document;
	private double width;
	private double height;
 
	/**
         * @throws IOException 
         * @throws BadLocationException 
         * 
         */
	public StyledText(String text, final Font defaultFont, FontRenderContext frc, float maxWidth, float maxHeight) throws IOException, BadLocationException {
 
		if ( text==null ) {
			text="";
		}
 
		try (Reader stringReader = new StringReader(text)) {
			EditorKit editorKit;
			if (text.startsWith("<html>")) {
				editorKit = new HTMLEditorKit();
				document = editorKit.createDefaultDocument(); 
			} else {
				editorKit = new StyledEditorKit();
				//document = editorKit.createDefaultDocument(); 
				StyleContext styles = new StyleContext();
				Style style = styles.addStyle(StyleContext.DEFAULT_STYLE, null); 
			    StyleConstants.setFontFamily(style, defaultFont.getFamily());
			    StyleConstants.setFontSize(style, defaultFont.getSize());
			    StyleConstants.setItalic(style, defaultFont.isItalic());
			    StyleConstants.setBold(style, defaultFont.isBold());
				document = new DefaultStyledDocument(styles);
			}
			editorKit.read(stringReader, document, 0);
		}
 
		// The paragraph start and end indices
		ArrayList<RunInfo> pEnds = null;
 
		// The current position in the specified range
		int pos = 0;
 
		// First get the actual text and stick it in an Attributed String
		try {
 
			stringContents = new ArrayList<>();
			pEnds = new ArrayList<>();
 
			String s = document.getText(0, document.getLength());
			StringTokenizer tokenizer = new StringTokenizer(s, "\n", true);
 
			// lastNewLine is used to detect the case when two newlines follow
			// in direct succession
			// & lastNewLine should be true to start in case the first character
			// is a newline
			boolean lastNewLine = true;
			for ( ; tokenizer.hasMoreTokens();  ) {
				String token = tokenizer.nextToken();
 
				// If the token
				if (token.equals("\n")) {
					if (lastNewLine) {
						stringContents.add(new AttributedString(" "));
						pEnds.add(new RunInfo(pos, pos + 1));
 
						pos = pos + 1;
 
						lastNewLine = true;
					} else {
						pos = pos + 1;
 
						lastNewLine = true;
					}
				}
				// If the token is empty - create an attributed string with a
				// single space
				// since LineBreakMeasurers don't work with an empty string
				// - note that this case should only arise if the document is
				// empty
				else if (token.equals("")) {
					stringContents.add(new AttributedString(" "));
					pEnds.add(new RunInfo(pos, pos));
 
					lastNewLine = false;
				}
				// This is the normal case - where we have some text
				else {
					stringContents.add(new AttributedString(token));
					pEnds.add(new RunInfo(pos, pos + token.length()));
 
					// Increment the position
					pos = pos + token.length();
 
					lastNewLine = false;
				}
			}
 
			// Add one more newline if the last character was a newline
			if (lastNewLine) {
				stringContents.add(new AttributedString(" "));
				pEnds.add(new RunInfo(pos, pos + 1));
 
				lastNewLine = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
 
		// The default style context - which will be reused
		StyleContext style = StyleContext.getDefaultStyleContext();
 
		RunInfo pEnd = null;
		for (int i = 0; i < stringContents.size(); i++) {
			pEnd = pEnds.get(i);
			pos = pEnd.runStart;
 
			// The current element will be used as a temp variable while
			// searching
			// for the leaf element at the current position
			Element curElement = null;
 
			// Small assumption here that there is one root element - can fix
			// for more general support later
			Element rootElement = document.getDefaultRootElement();
 
			// If the string is length 0 then we just need to add the attributes
			// once
			if (pEnd.runStart != pEnd.runLimit) {
				// OK, now we loop until we find all the leaf elements in the
				// range
				while (pos < pEnd.runLimit) {
 
					// Before each pass, start at the root
					curElement = rootElement;
 
					// Now we descend the hierarchy until we get to a leaf
					while (!curElement.isLeaf()) {
						curElement = curElement.getElement(curElement
								.getElementIndex(pos));
					}
 
					// These are the mandatory attributes
 
					AttributeSet attributes = curElement.getAttributes();
					Color foreground = style.getForeground(attributes);
 
					((AttributedString) stringContents.get(i)).addAttribute(
							TextAttribute.FOREGROUND, foreground, (int) Math
									.max(0, curElement.getStartOffset()
											- pEnd.runStart), (int) Math.min(
									pEnd.runLimit - pEnd.runStart,
									curElement.getEndOffset() - pEnd.runStart));
 
					Font font = (attributes.isDefined(StyleConstants.FontSize) || attributes
							.isDefined(StyleConstants.FontFamily)) ? style
							.getFont(attributes) : null;
					if (font == null) {
						if (document instanceof DefaultStyledDocument) {
							font = style
									.getFont(((DefaultStyledDocument) document)
											.getCharacterElement(pos)
											.getAttributes());
							if (font == null) {
								font = style
										.getFont(((DefaultStyledDocument) document)
												.getParagraphElement(pos)
												.getAttributes());
							}
							if (font == null) {
								font = style.getFont(rootElement
										.getAttributes());
							}
						} else {
							font = style.getFont(rootElement.getAttributes());
						}
					}
					if (font != null) {
						((AttributedString) stringContents.get(i))
								.addAttribute(
										TextAttribute.FONT,
										font,
										(int) Math.max(0,
												curElement.getStartOffset()
														- pEnd.runStart),
										(int) Math.min(pEnd.runLimit
												- pEnd.runStart,
												curElement.getEndOffset()
														- pEnd.runStart));
					}
 
					// These are the optional attributes
 
					Color background = (attributes
							.isDefined(StyleConstants.Background)) ? style
							.getBackground(attributes) : null;
					if (background != null) {
						((AttributedString) stringContents.get(i))
								.addAttribute(
										TextAttribute.BACKGROUND,
										background,
										(int) Math.max(0,
												curElement.getStartOffset()
														- pEnd.runStart),
										(int) Math.min(pEnd.runLimit
												- pEnd.runStart,
												curElement.getEndOffset()
														- pEnd.runStart));
					}
 
					boolean underline = StyleConstants.isUnderline(attributes);
					if (underline) {
						((AttributedString) stringContents.get(i))
								.addAttribute(
										TextAttribute.UNDERLINE,
										Boolean.TRUE,
										(int) Math.max(0,
												curElement.getStartOffset()
														- pEnd.runStart),
										(int) Math.min(pEnd.runLimit
												- pEnd.runStart,
												curElement.getEndOffset()
														- pEnd.runStart));
					}
 
					boolean strikethrough = StyleConstants
							.isStrikeThrough(attributes);
					if (strikethrough) {
						((AttributedString) stringContents.get(i))
								.addAttribute(
										TextAttribute.STRIKETHROUGH,
										Boolean.TRUE,
										(int) Math.max(0,
												curElement.getStartOffset()
														- pEnd.runStart),
										(int) Math.min(pEnd.runLimit
												- pEnd.runStart,
												curElement.getEndOffset()
														- pEnd.runStart));
					}
 
					// And set the position to the end of the given attribute
					pos = curElement.getEndOffset();
				}
			} else {
				// Before each pass, start at the root
				curElement = rootElement;
 
				// Now we descend the hierarchy until we get to a leaf
				while (!curElement.isLeaf()) {
					curElement = curElement.getElement(curElement
							.getElementIndex(pos));
				}
 
				// These are the mandatory attributes
 
				AttributeSet attributes = curElement.getAttributes();
				Color foreground = style.getForeground(attributes);
 
				((AttributedString) stringContents.get(i)).addAttribute(
						TextAttribute.FOREGROUND, foreground, (int) Math.max(0,
								curElement.getStartOffset() - pEnd.runStart),
						(int) Math.min(pEnd.runLimit - pEnd.runStart,
								curElement.getEndOffset() - pEnd.runStart));
 
				// These are the optional attributes
 
				Font font = (attributes.isDefined(StyleConstants.FontSize) || attributes
						.isDefined(StyleConstants.FontFamily)) ? style
						.getFont(attributes) : null;
				if (font == null) {
					if (document instanceof DefaultStyledDocument) {
						font = style.getFont(((DefaultStyledDocument) document)
								.getCharacterElement(pos).getAttributes());
						if (font == null) {
							font = style
									.getFont(((DefaultStyledDocument) document)
											.getParagraphElement(pos)
											.getAttributes());
						}
						if (font == null) {
							font = style.getFont(rootElement.getAttributes());
						}
					} else {
						font = style.getFont(rootElement.getAttributes());
					}
				}
				if (font != null) {
					((AttributedString) stringContents.get(i)).addAttribute(
							TextAttribute.FONT, font, (int) Math
									.max(0, curElement.getStartOffset()
											- pEnd.runStart), (int) Math.min(
									pEnd.runLimit - pEnd.runStart,
									curElement.getEndOffset() - pEnd.runStart));
				}
 
				Color background = (attributes
						.isDefined(StyleConstants.Background)) ? style
						.getBackground(attributes) : null;
				if (background != null) {
					((AttributedString) stringContents.get(i)).addAttribute(
							TextAttribute.BACKGROUND, background, (int) Math
									.max(0, curElement.getStartOffset()
											- pEnd.runStart), (int) Math.min(
									pEnd.runLimit - pEnd.runStart,
									curElement.getEndOffset() - pEnd.runStart));
				}
 
				boolean underline = StyleConstants.isUnderline(attributes);
				if (underline) {
					((AttributedString) stringContents.get(i)).addAttribute(
							TextAttribute.UNDERLINE, Boolean.TRUE, (int) Math
									.max(0, curElement.getStartOffset()
											- pEnd.runStart), (int) Math.min(
									pEnd.runLimit - pEnd.runStart,
									curElement.getEndOffset() - pEnd.runStart));
				}
 
				boolean strikethrough = StyleConstants
						.isStrikeThrough(attributes);
				if (strikethrough) {
					((AttributedString) stringContents.get(i)).addAttribute(
							TextAttribute.STRIKETHROUGH, Boolean.TRUE,
							(int) Math.max(0, curElement.getStartOffset()
									- pEnd.runStart), (int) Math.min(
									pEnd.runLimit - pEnd.runStart,
									curElement.getEndOffset() - pEnd.runStart));
				}
			}
		}
 
		recomputeLayout(frc, maxWidth, maxHeight);
	}
 
	public double getHeight() {
		return height;
	}
	public double getWidth() {
		return width;
	}
 
	public void recomputeLayout(FontRenderContext frc, float maxWidth, float maxHeight) {
 
		ArrayList<LineInfo> linesList = new ArrayList<>();
 
		double textWidth = 0;
		double textHeight = 0;
 
		for(int i=0; i<stringContents.size(); i++) {		
 
			AttributedString ats = (AttributedString)stringContents.get(i);
			AttributedCharacterIterator itr = ats.getIterator();
 
			LineBreakMeasurer measurer;
			ArrayList<Integer> breakList = null;
 
			// First we have to do an initial pass with a LineBreakMeasurer to
			// find out where Swing is going to break the lines - i.e.
			// because it doesn't use fractional metrics
 
			measurer = new LineBreakMeasurer(itr, frc);
			breakList = new ArrayList<>();
 
			measurer.nextLayout(Math.min(maxWidth, Float.MAX_VALUE));
			breakList.add(new Integer(measurer.getPosition()));
 
			measurer = new LineBreakMeasurer(itr, frc);
 
			// Need to change the lineinfo data structure to know about multiple
			// text layouts per line
 
			LineInfo lineInfo = null;
			boolean newLine = true;
			double lineWidth = 0;
			while (measurer.getPosition() < itr.getEndIndex()) {
				TextLayout aTextLayout = null;
 
				if (newLine) {
				    newLine = false;
 
				    // Add in the old line dimensions
				    double lineHeight = (lineInfo == null) ? 0 : lineInfo.maxAscent+lineInfo.maxDescent+lineInfo.leading;
				    textHeight = textHeight+lineHeight;
				    textWidth = Math.max(textWidth,lineWidth);
 
				    // Now create a new line
				    lineInfo = new LineInfo();
				    linesList.add(lineInfo);				    
				}
 
			    int lineEnd = ((Integer)breakList.get(0)).intValue();			    
			    if (lineEnd <= itr.getRunLimit()) {
			        breakList.remove(0);
			        newLine = true;
			    }
 
				aTextLayout = measurer.nextLayout(Float.MAX_VALUE,Math.min(lineEnd,itr.getRunLimit()),false);
 
				SegmentInfo sInfo = new SegmentInfo();
				sInfo.font = (Font)itr.getAttribute(TextAttribute.FONT);
				sInfo.foreground = (Color)itr.getAttribute(TextAttribute.FOREGROUND);
				sInfo.background = (Color)itr.getAttribute(TextAttribute.BACKGROUND);
				sInfo.underline = (Boolean)itr.getAttribute(TextAttribute.UNDERLINE);
				sInfo.layout = aTextLayout;
 
				FontMetrics metrics = StyleContext.getDefaultStyleContext().getFontMetrics((Font)itr.getAttribute(TextAttribute.FONT));
				lineInfo.maxAscent = Math.max(lineInfo.maxAscent,metrics.getMaxAscent());
				lineInfo.maxDescent = Math.max(lineInfo.maxDescent,metrics.getMaxDescent());
				lineInfo.leading = Math.max(lineInfo.leading,metrics.getLeading());
 
				lineInfo.segments.add(sInfo);
 
				itr.setIndex(measurer.getPosition());
				lineWidth = lineWidth+aTextLayout.getAdvance();
			}
 
		    double lineHeight = (lineInfo == null) ? 0 : lineInfo.maxAscent+lineInfo.maxDescent+lineInfo.leading;
		    textHeight = textHeight+lineHeight;
		    textWidth = Math.max(textWidth,lineWidth);
		}
 
		lines = linesList.toArray(new LineInfo[linesList.size()]);
 
		width = textWidth;
		height = Math.min( Math.max(textHeight,getInitialFontHeight()), maxHeight ); 
 
	}
 
	public double getInitialFontHeight() {
 
		// Small assumption here that there is one root element - can fix
		// for more general support later
		Element rootElement = document.getDefaultRootElement();
 
		// The current element will be used as a temp variable while searching
		// for the leaf element at the current position
		Element curElement = rootElement;
 
		// Now we descend the hierarchy until we get to a leaf
		while (!curElement.isLeaf()) {
			curElement = curElement.getElement(curElement.getElementIndex(0));
		}
 
		StyleContext context = StyleContext.getDefaultStyleContext();
		Font font = context.getFont(curElement.getAttributes());
 
		FontMetrics curFM = context.getFontMetrics(font);
 
		return curFM.getMaxAscent() + curFM.getMaxDescent() + curFM.getLeading();
	}
 
	protected static class RunInfo {
		public int runStart;
		public int runLimit;
 
		public RunInfo() {
		}
 
		public RunInfo(int runStart, int runLimit) {
			this.runStart = runStart;
			this.runLimit = runLimit;	
		}
	} 
 
	protected static class LineInfo {
	    public List<SegmentInfo> segments;
		public double maxAscent;
		public double	maxDescent;
		public double leading;
 
		public LineInfo() {
		    segments = new ArrayList<>();
		}
	}
 
	protected static class SegmentInfo {
		public TextLayout layout;
		public Font font;
		public Color foreground;
		public Color background;
		public Boolean underline;
 
		public SegmentInfo() {		    
		}
	}
 
	public void drawString(Graphics2D g2, int tx, int ty) {
 
		Line2D paintLine = new Line2D.Double();
 
		float x = tx;
		float y = ty;
		float bottomY = (float) (ty + getHeight() );
 
		if (lines == null || lines.length == 0) {
			return;
		} 
 
		float curX;
		for (int i=0; i<lines.length; i++) {
			y += lines[i].maxAscent;
			curX = x;
 
			if (bottomY < y) {
				return;
			}					
 
			for(int j=0; j<lines[i].segments.size(); j++) {			    
			    SegmentInfo sInfo = lines[i].segments.get(j);
				float width = sInfo.layout.getAdvance();
 
				if (sInfo.background != null) {
					g2.setPaint(sInfo.background);
					g2.fill(new Rectangle2D.Double(curX,y-lines[i].maxAscent,width,lines[i].maxAscent+lines[i].maxDescent+lines[i].leading));					
				}
 
				if (sInfo.font != null) {
				    g2.setFont(sInfo.font);
				}
 
				// Manually set the paint - this is specified in the AttributedString but seems to be
				// ignored by the TextLayout.  To handle multiple colors we should be breaking up the lines
				// but that functionality can be added later as needed
				g2.setPaint(sInfo.foreground);
				sInfo.layout.draw(g2, curX, y);
 
				// Draw the underline and the strikethrough after the text
				if (sInfo.underline != null) {
					paintLine.setLine(x,y+lines[i].maxDescent/2,x+width,y+lines[i].maxDescent/2);
					g2.draw(paintLine);	
				}
 
				curX = curX + width;
		    }
 
			y += lines[i].maxDescent + lines[i].leading;			
		}
	}
 
}