Java Tutorial/2D Graphics — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 15:25, 31 мая 2010
- AlphaComposite
- Animation
- Antialiasing
- Arc
- Area
- Buffer Paint
- BufferedImage
- Clip
- Color
- Curve
- Dimension
- Draw Text
- Ellipse
- Full Screen
- GIF
- Gradient Paint
- Graphic Path
- Graphics
- GraphicsEnvironment
- GrayFilter
- Image
- ImageIO
- ImageIcon
- ImageReader
- ImageWriter
- JPEG
- Line
- LineBreakMeasurer
- MemoryImageSource
- Mouse Draw
- Oval
- PNG
- Pen
- Point
- Polygon
- Print Service
- PrintJob
- PrinterJob
- RGBImageFilter
- Rectangle
- RenderHints
- Screen Capture
- Shape
- Stroke
- TextLayout
- TexturePaint
- Tranformation
Содержание
- 1 calls stringWidth (String) to center several text messages
- 2 Center text.
- 3 Create Bold and Italic font
- 4 Create font from true type font
- 5 Creating Serif Font
- 6 Display a text in 3 dimensions
- 7 Display font in a grid
- 8 Display font info.
- 9 Draw font metrics
- 10 Draw text to the center
- 11 Draw text to the left
- 12 Draw text to the right
- 13 Font base line
- 14 Font Metrics: the wealth of dimensional data about a font
- 15 Fonts exercise: a font chooser
- 16 Getting Char with based on current font
- 17 java.awt.Font
- 18 Obtain FontMetrics of different fonts
- 19 Show all Fonts installed in your system
- 20 Show fonts with mouse click
- 21 System fonts display
- 22 Text justify
- 23 The Three Font Styles
- 24 To change the size and/or style of a font, you call its deriveFont() method
- 25 To get all available fonts in your system
- 26 To get the font names
- 27 Use fonts in paint
- 28 Using FontRenderContext
calls stringWidth (String) to center several text messages
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FontMetricsStringWidth extends JPanel {
public static void main(String[] a) {
JFrame f = new JFrame();
f.setSize(400, 400);
f.add(new FontMetricsStringWidth());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public void paint(Graphics g) {
String[] msgs = { "AAAAAAAAA", "VVVVVVVVVVVVVVVVV", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" };
FontMetrics fm = g.getFontMetrics();
for (int i = 0; i < msgs.length; i++) {
int x = (getSize().width - fm.stringWidth(msgs[i])) / 2;
int y = fm.getHeight() * (i + 1);
g.drawString(msgs[i], x, y);
}
}
}
Center text.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JFrame;
public class CenterTextRectangle extends JFrame {
public static void main(String[] a) {
CenterTextRectangle f = new CenterTextRectangle();
f.setSize(300, 300);
f.setVisible(true);
}
final Font f = new Font("SansSerif", Font.BOLD, 18);
public void paint(Graphics g) {
Dimension d = this.getSize();
g.setColor(Color.white);
g.fillRect(0, 0, d.width, d.height);
g.setColor(Color.black);
g.setFont(f);
drawCenteredString("This is centered.", d.width, d.height, g);
g.drawRect(0, 0, d.width - 1, d.height - 1);
}
public void drawCenteredString(String s, int w, int h, Graphics g) {
FontMetrics fm = g.getFontMetrics();
int x = (w - fm.stringWidth(s)) / 2;
int y = (fm.getAscent() + (h - (fm.getAscent() + fm.getDescent())) / 2);
g.drawString(s, x, y);
}
}
Create Bold and Italic font
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
public class CreatingSerifItalicBoldFont {
public static void main(String args[]) {
JFrame f = new JFrame("JColorChooser Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton button = new JButton("Pick to Change Background");
Font myFont = new Font("Serif", Font.ITALIC | Font.BOLD, 12);
button.setFont(myFont);
f.add(button, BorderLayout.CENTER);
f.setSize(300, 200);
f.setVisible(true);
}
}
Create font from true type font
import java.awt.Font;
import java.io.File;
import java.io.FileInputStream;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
public static void main(String[] args) throws Exception {
File f = new File("your.ttf");
FileInputStream in = new FileInputStream(f);
Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, in);
Font dynamicFont32Pt = dynamicFont.deriveFont(32f);
JLabel testLabel = new JLabel("Dynamically loaded font \"" + dynamicFont.getName() + "\"");
testLabel.setFont(dynamicFont32Pt);
JFrame frame = new JFrame("Font Loading Demo");
frame.getContentPane().add(testLabel);
frame.pack();
frame.setVisible(true);
}
}
Creating Serif Font
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
public class CreatingSerifItalicFont {
public static void main(String args[]) {
JFrame f = new JFrame("JColorChooser Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton button = new JButton("Pick to Change Background");
Font myFont = new Font("Serif", Font.ITALIC, 12);
button.setFont(myFont);
f.add(button, BorderLayout.CENTER);
f.setSize(300, 200);
f.setVisible(true);
}
}
Display a text in 3 dimensions
// This example is from the book _Java AWT Reference_ by John Zukowski.
// Written by John Zukowski. Copyright (c) 1997 O"Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.SystemColor;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TextBox3D extends JPanel{
String text;
public TextBox3D (String s, int width, int height) {
super();
text=s;
setSize(width, height);
}
public synchronized void paint (Graphics g) {
FontMetrics fm = g.getFontMetrics();
Dimension size=getSize();
int x = (size.width - fm.stringWidth(text))/2;
int y = (size.height - fm.getHeight())/2;
g.setColor (SystemColor.control);
g.fillRect (0, 0, size.width, size.height);
g.setColor (SystemColor.controlShadow);
g.drawLine (0, 0, 0, size.height-1);
g.drawLine (0, 0, size.width-1, 0);
g.setColor (SystemColor.controlDkShadow);
g.drawLine (0, size.height-1, size.width-1, size.height-1);
g.drawLine (size.width-1, 0, size.width-1, size.height-1);
g.setColor (SystemColor.controlText);
g.drawString (text, x, y);
}
public static void main (String[] args) {
JFrame f = new JFrame();
f.add(new TextBox3D ("Help Me", 200, 200));
f.setSize(300,300);
f.setVisible(true);
}
}
Display font in a grid
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
final int w = 20;
final int side = 25;
final int[][] grid = new int[50][w];
JPanel panel = new JPanel() {
public void paintComponent(Graphics g) {
Font font = new Font("WingDings", Font.PLAIN, 14);
g.setFont(font);
int off = 0;
for (int i = 0; i < 256 * 256; i++) {
if (font.canDisplay((char) i)) {
off++;
grid[off / w][off % w] = i;
int x = off % w * side;
int y = (off / w) * side + side;
g.drawString("" + (char) i, x, y);
}
}
}
};
JFrame frame = new JFrame();
panel.setSize(300, 300);
frame.getContentPane().add(panel);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
Display font info.
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JFrame;
public class MainClass extends JFrame {
public static void main(String[] a) {
MainClass f = new MainClass();
f.setSize(300, 300);
f.setVisible(true);
}
public void paint(Graphics g) {
Font f = g.getFont();
String fontName = f.getName();
String fontFamily = f.getFamily();
int fontSize = f.getSize();
int fontStyle = f.getStyle();
String msg = "Family: " + fontName;
msg += ", Font: " + fontFamily;
msg += ", Size: " + fontSize + ", Style: ";
if ((fontStyle & Font.BOLD) == Font.BOLD)
msg += "Bold ";
if ((fontStyle & Font.ITALIC) == Font.ITALIC)
msg += "Italic ";
if ((fontStyle & Font.PLAIN) == Font.PLAIN)
msg += "Plain ";
g.drawString(msg, 4, 16);
}
}
Draw font metrics
// This example is from the book _Java AWT Reference_ by John Zukowski.
// Written by John Zukowski. Copyright (c) 1997 O"Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class metrics extends JPanel {
metrics () {
setFont (new Font ("TimesRoman", Font.BOLD | Font.ITALIC, 48));
setSize (225, 175);
}
public void paint (Graphics g) {
g.translate (100, 100);
FontMetrics fm = null;
int ascent, descent, leading, width1, width2, height;
String string1 = "dsdas";
String string2 = "asdf";
int xPos = 25, yPos = 50;
fm = g.getFontMetrics();
ascent = fm.getAscent();
descent = fm.getDescent();
leading = fm.getLeading();
height = fm.getHeight();
width1 = fm.stringWidth (string1);
width2 = fm.stringWidth (string2);
g.drawString (string1, xPos, yPos);
g.drawLine (xPos, yPos - ascent - leading,
xPos + width1, yPos - ascent - leading);
g.drawLine (xPos, yPos - ascent,
xPos + width1, yPos - ascent);
g.drawLine (xPos, yPos,
xPos + width1, yPos);
g.drawLine (xPos, yPos + descent,
xPos + width1, yPos + descent);
g.drawString (string2, xPos, yPos+height);
g.drawLine (xPos, yPos - ascent - leading + height,
xPos + width2, yPos - ascent - leading + height);
g.drawLine (xPos, yPos - ascent + height,
xPos + width2, yPos - ascent + height);
g.drawLine (xPos, yPos + height,
xPos + width2, yPos + height);
g.drawLine (xPos, yPos + descent + height,
xPos + width2, yPos + descent + height);
}
public static void main (String[] args) {
JFrame f = new JFrame();
f.add(new metrics());
f.setSize(300,300);
f.setVisible(true);
}
}
Draw text to the center
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.util.StringTokenizer;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TextLayoutCenter extends JPanel {
Dimension d;
Font f = new Font("fontname", Font.PLAIN, 20);
FontMetrics fm;
int fh, ascent;
int space;
public static void main(String[] a) {
JFrame f = new JFrame();
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new TextLayoutCenter());
f.setVisible(true);
}
public void paint(Graphics g) {
d = getSize();
g.setFont(f);
if (fm == null) {
fm = g.getFontMetrics();
ascent = fm.getAscent();
fh = ascent + fm.getDescent();
space = fm.stringWidth(" ");
}
g.setColor(Color.black);
StringTokenizer st = new StringTokenizer("this is a text. this is a test <BR> this is a text. this is a test");
int x = 0;
int nextx;
int y = 0;
String word, sp;
int wordCount = 0;
String line = "";
while (st.hasMoreTokens()) {
word = st.nextToken();
if (word.equals("<BR>")) {
drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
line = "";
wordCount = 0;
x = 0;
y = y + (fh * 2);
} else {
int w = fm.stringWidth(word);
if ((nextx = (x + space + w)) > d.width) {
drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
line = "";
wordCount = 0;
x = 0;
y = y + fh;
}
if (x != 0) {
sp = " ";
} else {
sp = "";
}
line = line + sp + word;
x = x + space + w;
wordCount++;
}
}
drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
}
public void drawString(Graphics g, String line, int wc, int lineW, int y) {
g.drawString(line, (d.width - lineW) / 2, y);//center
}
}
Draw text to the left
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.util.StringTokenizer;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TextLayoutLeft extends JPanel {
Dimension d;
Font f = new Font("fontname", Font.PLAIN, 20);
FontMetrics fm;
int fh, ascent;
int space;
public static void main(String[] a) {
JFrame f = new JFrame();
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new TextLayoutLeft());
f.setVisible(true);
}
public void paint(Graphics g) {
d = getSize();
g.setFont(f);
if (fm == null) {
fm = g.getFontMetrics();
ascent = fm.getAscent();
fh = ascent + fm.getDescent();
space = fm.stringWidth(" ");
}
g.setColor(Color.black);
StringTokenizer st = new StringTokenizer("this is a text. this is a test <BR> this is a text. this is a test");
int x = 0;
int nextx;
int y = 0;
String word, sp;
int wordCount = 0;
String line = "";
while (st.hasMoreTokens()) {
word = st.nextToken();
if (word.equals("<BR>")) {
drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
line = "";
wordCount = 0;
x = 0;
y = y + (fh * 2);
} else {
int w = fm.stringWidth(word);
if ((nextx = (x + space + w)) > d.width) {
drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
line = "";
wordCount = 0;
x = 0;
y = y + fh;
}
if (x != 0) {
sp = " ";
} else {
sp = "";
}
line = line + sp + word;
x = x + space + w;
wordCount++;
}
}
drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
}
public void drawString(Graphics g, String line, int wc, int lineW, int y) {
g.drawString(line, 0, y);
}
}
Draw text to the right
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.util.StringTokenizer;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TextLayoutRight extends JPanel {
Dimension d;
Font f = new Font("fontname", Font.PLAIN, 20);
FontMetrics fm;
int fh, ascent;
int space;
public static void main(String[] a) {
JFrame f = new JFrame();
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new TextLayoutRight());
f.setVisible(true);
}
public void paint(Graphics g) {
d = getSize();
g.setFont(f);
if (fm == null) {
fm = g.getFontMetrics();
ascent = fm.getAscent();
fh = ascent + fm.getDescent();
space = fm.stringWidth(" ");
}
g.setColor(Color.black);
StringTokenizer st = new StringTokenizer("this is a text. this is a test <BR> this is a text. this is a test");
int x = 0;
int nextx;
int y = 0;
String word, sp;
int wordCount = 0;
String line = "";
while (st.hasMoreTokens()) {
word = st.nextToken();
if (word.equals("<BR>")) {
drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
line = "";
wordCount = 0;
x = 0;
y = y + (fh * 2);
} else {
int w = fm.stringWidth(word);
if ((nextx = (x + space + w)) > d.width) {
drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
line = "";
wordCount = 0;
x = 0;
y = y + fh;
}
if (x != 0) {
sp = " ";
} else {
sp = "";
}
line = line + sp + word;
x = x + space + w;
wordCount++;
}
}
drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
}
public void drawString(Graphics g, String line, int wc, int lineW, int y) {
g.drawString(line, d.width - lineW, y); //right
}
}
Font base line
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class FontShow extends JComponent {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Font font = new Font("Dialog", Font.PLAIN, 96);
g2.setFont(font);
int width = getSize().width;
int height = getSize().height;
String message = "jexp";
FontRenderContext frc = g2.getFontRenderContext();
LineMetrics metrics = font.getLineMetrics(message, frc);
float messageWidth = (float) font.getStringBounds(message, frc).getWidth();
// center text
float ascent = metrics.getAscent();
float descent = metrics.getDescent();
float x = (width - messageWidth) / 2;
float y = (height + metrics.getHeight()) / 2 - descent;
int PAD = 25;
g2.setPaint(getBackground());
g2.fillRect(0, 0, width, height);
g2.setPaint(getForeground());
g2.drawString(message, x, y);
g2.setPaint(Color.white); // Base lines
drawLine(g2, x - PAD, y, x + messageWidth + PAD, y);
drawLine(g2, x, y + PAD, x, y - ascent - PAD);
g2.setPaint(Color.green); // Ascent line
drawLine(g2, x - PAD, y - ascent, x + messageWidth + PAD, y - ascent);
g2.setPaint(Color.red); // Descent line
drawLine(g2, x - PAD, y + descent, x + messageWidth + PAD, y + descent);
}
private void drawLine(Graphics2D g2, double x0, double y0, double x1, double y1) {
Shape line = new java.awt.geom.Line2D.Double(x0, y0, x1, y1);
g2.draw(line);
}
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setSize(420, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new FontShow());
frame.setVisible(true);
}
}
Font Metrics: the wealth of dimensional data about a font
import java.awt.FontMetrics;
import javax.swing.JFrame;
public class GettingFontMetrics {
public static void main(String args[]) {
JFrame f = new JFrame("JColorChooser Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FontMetrics metrics = f.getFontMetrics(f.getFont());
f.setSize(300, 200);
f.setVisible(true);
}
}
Fonts exercise: a font chooser
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class FontStyleSizeFamilyChooser extends JFrame {
public static void main(String[] args) {
new FontStyleSizeFamilyChooser();
}
private JLabel sampleText = new JLabel("Label");
private JComboBox fontComboBox;
private JComboBox sizeComboBox;
private JCheckBox boldCheck, italCheck;
private String[] fonts;
public FontStyleSizeFamilyChooser() {
this.setSize(500, 150);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FontListener fl = new FontListener();
this.add(sampleText, BorderLayout.NORTH);
GraphicsEnvironment g = GraphicsEnvironment.getLocalGraphicsEnvironment();
fonts = g.getAvailableFontFamilyNames();
JPanel controlPanel = new JPanel();
fontComboBox = new JComboBox(fonts);
fontComboBox.addActionListener(fl);
controlPanel.add(new JLabel("Family: "));
controlPanel.add(fontComboBox);
Integer[] sizes = { 7, 8, 9, 10, 11, 12, 14, 18, 20, 22, 24, 36 };
sizeComboBox = new JComboBox(sizes);
sizeComboBox.setSelectedIndex(5);
sizeComboBox.addActionListener(fl);
controlPanel.add(new JLabel("Size: "));
controlPanel.add(sizeComboBox);
boldCheck = new JCheckBox("Bold");
boldCheck.addActionListener(fl);
controlPanel.add(boldCheck);
italCheck = new JCheckBox("Ital");
italCheck.addActionListener(fl);
controlPanel.add(italCheck);
this.add(controlPanel, BorderLayout.SOUTH);
fl.updateText();
this.setVisible(true);
}
private class FontListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
updateText();
}
public void updateText() {
String name = (String) fontComboBox.getSelectedItem();
Integer size = (Integer) sizeComboBox.getSelectedItem();
int style;
if (boldCheck.isSelected() && italCheck.isSelected())
style = Font.BOLD | Font.ITALIC;
else if (boldCheck.isSelected())
style = Font.BOLD;
else if (italCheck.isSelected())
style = Font.ITALIC;
else
style = Font.PLAIN;
Font f = new Font(name, style, size.intValue());
sampleText.setFont(f);
}
}
}
Getting Char with based on current font
import java.awt.FontMetrics;
import javax.swing.JFrame;
public class GettingFontMetrics {
public static void main(String args[]) {
JFrame f = new JFrame("JColorChooser Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300, 200);
f.setVisible(true);
FontMetrics metrics = f.getFontMetrics(f.getFont());
int widthX = metrics.charWidth("X");
System.out.println(widthX);
}
}
7
java.awt.Font
A Font object represents a font. Here is a constructor of the Font class.
public Font (java.lang.String name, int style, int size)
Obtain FontMetrics of different fonts
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class Main extends JFrame {
public Main() {
super("Demonstrating FontMetrics");
setSize(510, 210);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g) {
g.setFont(new Font("SansSerif", Font.BOLD, 12));
FontMetrics fm = g.getFontMetrics();
g.drawString("Current font: " + g.getFont(), 10, 40);
g.drawString("Ascent: " + fm.getAscent(), 10, 55);
g.drawString("Descent: " + fm.getDescent(), 10, 70);
g.drawString("Height: " + fm.getHeight(), 10, 85);
g.drawString("Leading: " + fm.getLeading(), 10, 100);
Font font = new Font("Serif", Font.ITALIC, 14);
fm = g.getFontMetrics(font);
g.setFont(font);
g.drawString("Current font: " + font, 10, 130);
g.drawString("Ascent: " + fm.getAscent(), 10, 145);
g.drawString("Descent: " + fm.getDescent(), 10, 160);
g.drawString("Height: " + fm.getHeight(), 10, 175);
g.drawString("Leading: " + fm.getLeading(), 10, 190);
}
public static void main(String args[]) {
Main app = new Main();
}
}
Show all Fonts installed in your system
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PaintAllFontsFromGraphicEvironment extends JPanel {
public static void main(String[] a){
JFrame f = new JFrame();
f.setSize(400,400);
f.add(new PaintAllFontsFromGraphicEvironment());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public void paint(Graphics g) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] allFonts = ge.getAllFonts();
for (int i = 0; i < allFonts.length; i++) {
Font f = allFonts[i].deriveFont(10.0f);
g.setFont(f);
g.setColor(Color.black);
g.drawString("Hello!", 10, 20*i);
}
}
}
Show fonts with mouse click
import java.applet.Applet;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MainClass extends Applet {
int next = 0;
Font f;
String msg;
public void init() {
f = new Font("Dialog", Font.PLAIN, 12);
msg = "Dialog";
setFont(f);
addMouseListener(new MyMouseAdapter(this));
}
public void paint(Graphics g) {
g.drawString(msg, 4, 20);
}
}
class MyMouseAdapter extends MouseAdapter {
MainClass sampleFonts;
public MyMouseAdapter(MainClass sampleFonts) {
this.sampleFonts = sampleFonts;
}
public void mousePressed(MouseEvent me) {
sampleFonts.next++;
switch (sampleFonts.next) {
case 0:
sampleFonts.f = new Font("Dialog", Font.PLAIN, 12);
sampleFonts.msg = "Dialog";
break;
case 1:
sampleFonts.f = new Font("DialogInput", Font.PLAIN, 12);
sampleFonts.msg = "DialogInput";
break;
case 2:
sampleFonts.f = new Font("SansSerif", Font.PLAIN, 12);
sampleFonts.msg = "SansSerif";
break;
case 3:
sampleFonts.f = new Font("Serif", Font.PLAIN, 12);
sampleFonts.msg = "Serif";
break;
case 4:
sampleFonts.f = new Font("Monospaced", Font.PLAIN, 12);
sampleFonts.msg = "Monospaced";
break;
}
if (sampleFonts.next == 4)
sampleFonts.next = -1;
sampleFonts.setFont(sampleFonts.f);
sampleFonts.repaint();
}
}
System fonts display
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SystemFontDisplayer extends JFrame {
DisplayPanel displayPanel;
String[] fontStyleLabels = { "Plain", "Bold", "Italic", "Bold&Italic" };
int BOLDITALIC = Font.BOLD | Font.ITALIC;
int[] fontStyles = { Font.PLAIN, Font.BOLD, Font.ITALIC, BOLDITALIC };
String[] fontSizeLabels = { "8", "9", "10", "11", "12", "14", "18", "25",
"36", "72" };
JComboBox fontsBox,
fontStylesBox = new JComboBox(fontStyleLabels), fontSizesBox = new JComboBox(fontSizeLabels);
public SystemFontDisplayer() {
Container container = getContentPane();
displayPanel = new DisplayPanel();
container.add(displayPanel);
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(1, 3));
fontsBox= new JComboBox(displayPanel.fontFamilyNames);
fontsBox.setSelectedItem("Arial");
fontsBox.addActionListener(new ComboBoxListener());
fontStylesBox.addActionListener(new ComboBoxListener());
fontSizesBox.setSelectedItem("36");
fontSizesBox.addActionListener(new ComboBoxListener());
controlPanel.add(fontsBox);
controlPanel.add(fontStylesBox);
controlPanel.add(fontSizesBox);
container.add(BorderLayout.SOUTH, controlPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setSize(400, 250);
setVisible(true);
}
public static void main(String arg[]) {
new SystemFontDisplayer();
}
class ComboBoxListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JComboBox tempBox = (JComboBox) e.getSource();
if (tempBox.equals(fontsBox)) {
displayPanel.fontFamilyName = (String) tempBox.getSelectedItem();
displayPanel.repaint();
} else if (tempBox.equals(fontStylesBox)) {
displayPanel.fontStyle = fontStyles[tempBox.getSelectedIndex()];
displayPanel.repaint();
} else if (tempBox.equals(fontSizesBox)) {
displayPanel.fontSize = Integer.parseInt((String) tempBox
.getSelectedItem());
displayPanel.repaint();
}
}
}
class DisplayPanel extends JPanel {
String fontFamilyName;
int fontStyle;
int fontSize;
String[] fontFamilyNames;
public DisplayPanel() {
fontFamilyName = "Arial";
fontStyle = Font.PLAIN;
fontSize = 36;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
fontFamilyNames = ge.getAvailableFontFamilyNames();
setSize(400, 225);
}
public void update(Graphics g) {
g.clearRect(0, 0, getWidth(), getHeight());
paintComponent(g);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
g2D.setFont(new Font(fontFamilyName, fontStyle, fontSize));
g2D.drawString("Java 2D Fonts", 25, 100);
}
}
}
Text justify
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.util.StringTokenizer;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TextLayoutJustify extends JPanel {
Dimension d;
Font f = new Font("fontname", Font.PLAIN, 20);
FontMetrics fm;
int fh, ascent;
int space;
public static void main(String[] a) {
JFrame f = new JFrame();
f.setSize(300, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new TextLayoutJustify());
f.setVisible(true);
}
public void paint(Graphics g) {
d = getSize();
g.setFont(f);
if (fm == null) {
fm = g.getFontMetrics();
ascent = fm.getAscent();
fh = ascent + fm.getDescent();
space = fm.stringWidth(" ");
}
g.setColor(Color.black);
StringTokenizer st = new StringTokenizer("this is a text. this is a test <BR> this is a text. this is a test");
int x = 0;
int nextx;
int y = 0;
String word, sp;
int wordCount = 0;
String line = "";
while (st.hasMoreTokens()) {
word = st.nextToken();
if (word.equals("<BR>")) {
drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
line = "";
wordCount = 0;
x = 0;
y = y + (fh * 2);
} else {
int w = fm.stringWidth(word);
if ((nextx = (x + space + w)) > d.width) {
drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
line = "";
wordCount = 0;
x = 0;
y = y + fh;
}
if (x != 0) {
sp = " ";
} else {
sp = "";
}
line = line + sp + word;
x = x + space + w;
wordCount++;
}
}
drawString(g, line, wordCount, fm.stringWidth(line), y + ascent);
}
public void drawString(Graphics g, String line, int wc, int lineWidth, int y) {
if (lineWidth < (int) (d.width * .75)) {
g.drawString(line, 0, y);
} else {
int toFill = (int) ((d.width - lineWidth) / wc);
int nudge = d.width - lineWidth - (toFill * wc);
StringTokenizer st = new StringTokenizer(line);
int x = 0;
while (st.hasMoreTokens()) {
String word = st.nextToken();
g.drawString(word, x, y);
if (nudge > 0) {
x = x + fm.stringWidth(word) + space + toFill + 1;
nudge--;
} else {
x = x + fm.stringWidth(word) + space + toFill;
}
}
}
}
}
The Three Font Styles
ConstantDescriptionFont.BOLDThe bold style constantFont.ITALICThe italicized style constantFont.PLAINThe plain style constant
To change the size and/or style of a font, you call its deriveFont() method
- deriveFont(int Style): Creates a new Font object with the style specified - one of PLAIN, BOLD, ITALIC, or BOLD+ITALIC
- deriveFont(float size): Creates a new Font object with the size specified
- deriveFont(int Style, float size): Creates a new Font object with the style and size specified
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
public class DrivedFont {
public static void main(String args[]) {
JFrame f = new JFrame("JColorChooser Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton button = new JButton("Pick to Change Background");
Font myFont = new Font("Serif", Font.ITALIC | Font.BOLD, 12);
Font newFont = myFont.deriveFont(50F);
button.setFont(newFont);
f.add(button, BorderLayout.CENTER);
f.setSize(300, 200);
f.setVisible(true);
}
}
To get all available fonts in your system
import java.awt.Font;
import java.awt.GraphicsEnvironment;
public class MainClass {
public static void main(String[] a) {
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] fonts = e.getAllFonts(); // Get the fonts
for (Font f : fonts) {
System.out.println(f.getFontName());
}
}
}
Agency FB Agency FB Bold Arial Arial Black Arial Black Italic Arial Bold Arial Bold Italic Arial Italic Arial Narrow Arial Narrow Bold Arial Narrow Bold Italic Arial Narrow Italic Arial Rounded MT Bold Arial-SM Blackadder ITC Bodoni MT Bodoni MT Black Bodoni MT Black Italic Bodoni MT Bold Bodoni MT Bold Italic Bodoni MT Condensed Bodoni MT Condensed Bold Bodoni MT Condensed Bold Italic Bodoni MT Condensed Italic Bodoni MT Italic Book Antiqua Book Antiqua Bold Book Antiqua Bold Italic Book Antiqua Italic Bookman Old Style Bookman Old Style Bold Bookman Old Style Bold Italic Bookman Old Style Italic Bookshelf Symbol 7 Bradley Hand ITC Calisto MT Calisto MT Bold Calisto MT Bold Italic Calisto MT Italic Castellar Century Gothic Century Gothic Bold Century Gothic Bold Italic Century Gothic Italic Century Schoolbook Century Schoolbook Bold Century Schoolbook Bold Italic Century Schoolbook Italic Comic Sans MS Comic Sans MS Bold Copperplate Gothic Bold Copperplate Gothic Light Courier New Courier New Bold Courier New Bold Italic Courier New Italic Curlz MT Dialog.bold Dialog.bolditalic Dialog.italic Dialog.plain DialogInput.bold DialogInput.bolditalic DialogInput.italic DialogInput.plain Edwardian Script ITC Elephant Elephant Italic Engravers MT Eras Bold ITC Eras Demi ITC Eras Light ITC Eras Medium ITC Estrangelo Edessa Felix Titling Forte Franklin Gothic Book Franklin Gothic Book Italic Franklin Gothic Demi Franklin Gothic Demi Cond Franklin Gothic Demi Italic Franklin Gothic Heavy Franklin Gothic Heavy Italic Franklin Gothic Medium Franklin Gothic Medium Cond Franklin Gothic Medium Italic French Script MT Garamond Garamond Bold Garamond Italic Gautami Georgia Georgia Bold Georgia Bold Italic Georgia Italic Gigi Gill Sans MT Gill Sans MT Bold Gill Sans MT Bold Italic Gill Sans MT Condensed Gill Sans MT Ext Condensed Bold Gill Sans MT Italic Gill Sans Ultra Bold Gill Sans Ultra Bold Condensed Gloucester MT Extra Condensed Goudy Old Style Goudy Old Style Bold Goudy Old Style Italic Goudy Stout Haettenschweiler Impact Imprint MT Shadow Kartika Latha Lucida Bright Demibold Lucida Bright Demibold Italic Lucida Bright Italic Lucida Bright Regular Lucida Console Lucida Sans Demibold Lucida Sans Demibold Italic Lucida Sans Demibold Roman Lucida Sans Italic Lucida Sans Regular Lucida Sans Typewriter Bold Lucida Sans Typewriter Bold Oblique Lucida Sans Typewriter Oblique Lucida Sans Typewriter Regular Lucida Sans Unicode MS Outlook MS Reference Sans Serif MS Reference Specialty MV Boli Maiandra GD Mangal Marlett Microsoft Sans Serif Monospaced.bold Monospaced.bolditalic Monospaced.italic Monospaced.plain Monotype Corsiva OCR A Extended Palace Script MT Palatino Linotype Palatino Linotype Bold Palatino Linotype Bold Italic Palatino Linotype Italic Papyrus Perpetua Perpetua Bold Perpetua Bold Italic Perpetua Italic Perpetua Titling MT Bold Perpetua Titling MT Light Pristina Raavi Rage Italic Rockwell Rockwell Bold Rockwell Bold Italic Rockwell Condensed Rockwell Condensed Bold Rockwell Extra Bold Rockwell Italic SansSerif.bold SansSerif.bolditalic SansSerif.italic SansSerif.plain Script MT Bold Serif.bold Serif.bolditalic Serif.italic Serif.plain Shruti Sylfaen Symbol Tahoma Tahoma Bold Tera Special Times New Roman Times New Roman Bold Times New Roman Bold Italic Times New Roman Italic Trebuchet MS Trebuchet MS Bold Trebuchet MS Bold Italic Trebuchet MS Italic Tunga Tw Cen MT Tw Cen MT Bold Tw Cen MT Bold Italic Tw Cen MT Condensed Tw Cen MT Condensed Bold Tw Cen MT Condensed Extra Bold Tw Cen MT Italic Verdana Verdana Bold Verdana Bold Italic Verdana Italic Vrinda Webdings Wingdings Wingdings 2 Wingdings 3
To get the font names
import java.awt.Font;
import java.awt.GraphicsEnvironment;
public class MainClass {
public static void main(String[] a) {
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames = e.getAvailableFontFamilyNames();
for (String s : fontnames) {
System.out.println(s);
}
}
}
Agency FB Arial Arial Black Arial Narrow Arial Rounded MT Bold Arial-SM Blackadder ITC Bodoni MT Bodoni MT Black Bodoni MT Condensed Book Antiqua Bookman Old Style Bookshelf Symbol 7 Bradley Hand ITC Calisto MT Castellar Century Gothic Century Schoolbook Comic Sans MS Copperplate Gothic Bold Copperplate Gothic Light Courier New Curlz MT Dialog DialogInput Edwardian Script ITC Elephant Engravers MT Eras Bold ITC Eras Demi ITC Eras Light ITC Eras Medium ITC Estrangelo Edessa Felix Titling Forte Franklin Gothic Book Franklin Gothic Demi Franklin Gothic Demi Cond Franklin Gothic Heavy Franklin Gothic Medium Franklin Gothic Medium Cond French Script MT Garamond Gautami Georgia Gigi Gill Sans MT Gill Sans MT Condensed Gill Sans MT Ext Condensed Bold Gill Sans Ultra Bold Gill Sans Ultra Bold Condensed Gloucester MT Extra Condensed Goudy Old Style Goudy Stout Haettenschweiler Impact Imprint MT Shadow Kartika Latha Lucida Bright Lucida Console Lucida Sans Lucida Sans Typewriter Lucida Sans Unicode Maiandra GD Mangal Marlett Microsoft Sans Serif Monospaced Monotype Corsiva MS Outlook MS Reference Sans Serif MS Reference Specialty MV Boli OCR A Extended Palace Script MT Palatino Linotype Papyrus Perpetua Perpetua Titling MT Pristina Raavi Rage Italic Rockwell Rockwell Condensed Rockwell Extra Bold SansSerif Script MT Bold Serif Shruti Sylfaen Symbol Tahoma Tera Special Times New Roman Trebuchet MS Tunga Tw Cen MT Tw Cen MT Condensed Tw Cen MT Condensed Extra Bold Verdana Vrinda Webdings Wingdings Wingdings 2 Wingdings 3
Use fonts in paint
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
public void paint(Graphics g) {
Font courier = new Font ("Courier", Font.PLAIN, 12);
Font system = new Font ("System", Font.BOLD, 16);
Font helvetica = new Font ("Helvetica", Font.BOLD, 18);
g.setFont (courier);
g.drawString ("Courier", 10, 30);
g.setFont (system);
g.drawString ("System", 10, 70);
g.setFont (helvetica);
g.drawString ("Helvetica", 10, 90);
}
}
public class SettingFont {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
Using FontRenderContext
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FontRenderContextRenderingHints extends JFrame {
public FontRenderContextRenderingHints() {
getContentPane().add(new DrawingCanvas());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
}
public static void main(String arg[]) {
new FontRenderContextRenderingHints();
}
}
class DrawingCanvas extends JPanel {
Font font = new Font("Dialog", Font.BOLD, 40);
FontMetrics fontMetrics;
DrawingCanvas() {
setSize(300, 300);
setBackground(Color.white);
fontMetrics = getFontMetrics(font);
}
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
int w = getSize().width;
int h = getSize().height;
RenderingHints qualityHints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
qualityHints.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2D.setRenderingHints(qualityHints);
AffineTransform at = new AffineTransform();
at.setToTranslation(-300, -400);
at.shear(-0.5, 0.0);
FontRenderContext frc = new FontRenderContext(at, false, false);
TextLayout tl = new TextLayout("World!", font, frc);
Shape outline = tl.getOutline(null);
g2D.setColor(Color.blue);
BasicStroke wideStroke = new BasicStroke(2.0f);
g2D.setStroke(wideStroke);
g2D.draw(outline);
}
}