Re: Graphics2D in a DefaultStyleDocument
In article <CGEfn.834$sx5.509@newsfe16.iad>,
Daniel Pitts <newsgroup.spamfilter@virtualinfinity.net> wrote:
On 2/19/2010 10:45 AM, John B. Matthews wrote:
In article
<96cfec27-1e60-4075-ab72-16cd8e61b22d@y26g2000vbb.googlegroups.com>,
Elliot<eselick@gmail.com> wrote:
I currently use a lot of code to parse and print a multi-page
document with a lot of Graphics2D objects. I need to display the
same document in a JTextPane. I would like to create a new class
that could be used by either the repaginate() and print() routines
for the print job or by a new paint() routine for the Swing
components.
I would like to add the Graphics2D objects to a
DefaultStyledDocument and then add the styled document to a
JTextPane. I think this would be the fastest way to draw
everything. First, is it possible to add paint graphic 2d on a
StyledDocument?
Second, I do not want to duplicate any of the existing complex
parsing code for the print job. I need to figure out how to create
a new class containing this logic that could be used by either the
current repaginate() and print() methods or new paint() method.
Any ideas would be really welcome.
If a Graphics2D instance is associated with a Component you can use
the insertComponent() method of JTextPane:
<http://java.sun.com/javase/6/docs/api/javax/swing/JTextPane.html
#insertComponent(java.awt.Component)>
If it's a BufferedImage, you can wrap it in a JComponent and
override the paintComponent() method to call drawImage().
Or use a JLabel with an ImageIcon, instead of writing custom
paintComponent :-)
Even better!
Somewhere between the two approaches, I like to implement the Icon
interface. As an example, here's a handy component for seeing the
effect of various layout managers:
/**
* A label having an icon showing the icon's center.
* @author John B. Matthews
*/
private static class SizeLabel extends JLabel implements Icon {
private static final Font FONT =
new Font("Serif", Font.PLAIN, 16);
private static final int WIDE = 72;
private static final int HIGH = 24;
public SizeLabel() {
this.setHorizontalAlignment(JLabel.CENTER);
this.setVerticalAlignment(JLabel.CENTER);
this.setHorizontalTextPosition(JLabel.CENTER);
this.setVerticalTextPosition(JLabel.TOP);
this.setIconTextGap(0);
this.setFont(FONT);
this.setPreferredSize(
new Dimension(4 * WIDE / 3, 8 * HIGH / 3));
this.setMinimumSize(this.getPreferredSize());
this.setIcon(this);
}
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(Color.darkGray);
g.fillRect(x, y, WIDE, HIGH);
int x2 = x + WIDE / 2;
int y2 = y + HIGH / 2;
String s = "(" + x2 + ", " + y2 + ")";
int w2 = g.getFontMetrics().stringWidth(s) / 2;
int h2 = g.getFontMetrics().getDescent() + 1;
g.setColor(Color.white);
g.drawString(s, x2 - w2, y2 + h2);
}
public int getIconWidth() {
return WIDE;
}
public int getIconHeight() {
return HIGH;
}
}
--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>