I want to draw some text on a JFrame (later it'll change to a JPanel), but not have the text necessarily be horizontal. I've found some decent examples online that have worked well, but they've all been 500+ lines long. I'm hoping it can be done in a way that's shorter.
My understanding is that I can't use plain old drawString
directly onto the JFrame if I don't want the text to be horizontal. Instead I need to create an image, then tilt the image, then draw the image onto the the JFrame. My attempt so far creates an image and draws it onto the JFrame, but it's horizontal.
Does anyone know a way to tilt the image to get sideways text or how to get sideways text some other way that doesn't require several hundred more lines of code? I'm pretty much of a noob when it comes to images. Thanks. Here's my attempt so far that makes the text horizontal.
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.font.*;
public class RotateDemo extends JFrame
{
Font font;
Font font2;
String title;
String title2;
Image image;
Image image2;
RotatorCanvas rotator;
public static void main(String args[])
{
new RotateDemo();
}
public RotateDemo()
{
setVisible(true);
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
font = new Font("Helvetica", Font.BOLD, 20);
font2 = new Font("Courier", Font.BOLD, 35);
title = "Hello";
title2 = "Hi";
image = this.createRotatedImage(Color.black, font, title);
image2 = this.createRotatedImage(Color.red, font2, title2);
rotator = new RotatorCanvas(image, image2);
add(rotator);
validate();
}
private Image createRotatedImage(Color c, Font afont, String theText)
{
FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics(afont);
int width = fm.stringWidth(theText);
int height = fm.getHeight();
int ascent = fm.getMaxAscent();
int leading = fm.getLeading();
Image animage = this.createImage (width + 8, height);
Graphics gr = animage.getGraphics();
gr.setColor(Color.white);
gr.fillRect(0, 0, animage.getWidth(this), animage.getHeight (this));
gr.setFont(afont);
gr.setColor(c);
gr.drawString(theText, 4, ascent + leading);
ImageFilter filter = new ImageFilter();
ImageProducer producer = new FilteredImageSource (animage.getSource(), filter);
animage = createImage(producer);
return animage;
}
}
class RotatorCanvas extends Canvas
{
Image image;
Image image2;
public RotatorCanvas(Image im1, Image im2)
{
super();
this.image = im1;
this.image2 = im2;
}
public void paint(Graphics g)
{
g.setColor(Color.BLACK);
g.drawRect(19, 19, image.getWidth(this) + 2, image.getHeight(this) + 2);
g.drawImage(image, 20, 20, this);
g.drawRect(99, 99, image2.getWidth(this) + 2, image2.getHeight(this) + 2);
g.drawImage(image2, 100, 100, this);
}
}