Java/2D Graphics GUI/Text

Материал из Java эксперт
Перейти к: навигация, поиск

Create a shadowed text

   
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.TextLayout;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ShadowText extends JLabel {
  public void paint(Graphics g) {
    String text = "Hello World";
    int x = 10;
    int y = 100;
    Font font = new Font("Georgia", Font.ITALIC, 50);
    Graphics2D g1 = (Graphics2D) g;
    TextLayout textLayout = new TextLayout(text, font, g1.getFontRenderContext());
    g1.setPaint(new Color(150, 150, 150));
    textLayout.draw(g1, x + 3, y + 3);
    g1.setPaint(Color.BLACK);
    textLayout.draw(g1, x, y);
  }
  public static void main(String[] args) throws IOException {
    JFrame f = new JFrame();
    f.add(new ShadowText());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(450, 150);
    f.setVisible(true);
  }
}



Display some lyrics on the panel.

   
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PrintLineByLine extends JPanel {
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2d.setRenderingHints(rh);
    g2d.setFont(new Font("Purisa", Font.PLAIN, 13));
    g2d.drawString("Line 1", 20, 30);
    g2d.drawString("Line 2", 20, 60);
    g2d.drawString("Line 3", 20, 90);
    g2d.drawString("Line 4", 20, 120);
    g2d.drawString("Line 5", 20, 150);
    g2d.drawString("Line 6", 20, 180);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.add(new PrintLineByLine());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(420, 250);
    frame.setVisible(true);
  }
}



Display underlined text

   
import java.awt.Graphics;
import javax.swing.JPanel;
public class Main extends JPanel{
  String s = "Underlined text";
  int x = 10;
  int y = 10;
  public void init() {
  }
  public void paint(Graphics g) {
    g.drawString(s, x, y);
    g.drawLine(x, y + 2, x + getFontMetrics(getFont()).stringWidth(s), y + 2);
  }
}



Display unicode text

   
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class RussiaUnicode extends JPanel {
  public void paint(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.drawString("\u0424\u0451\u0434\u043e\u0440.", 20, 30);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("Unicode");
    frame.add(new RussiaUnicode());
    frame.setSize(520, 220);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}



Display vertical text

   
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel{
  String s = "Vertical text";
  int v;
  public void paint(Graphics g) {
    v = g.getFontMetrics(getFont()).getHeight() + 1;
    int j = 0;
    int k = s.length();
    while (j < k + 1) {
      if (j == k)
        g.drawString(s.substring(j), 10, 10 + (j * v));
      else
        g.drawString(s.substring(j, j + 1), 10, 10 + (j * v));
      j++;
    }
  }
  public static void main(String[] a){
    JFrame f = new JFrame();
    f.add(new Main());
    f.setSize(300,300);
    f.setVisible(true);
  }
}



Draw 2D Text

   
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel {
  public Main() {
    setBackground(Color.white);
  }
  public void paint(Graphics g) {
    Graphics2D g2D;
    g2D = (Graphics2D) g;
    FontRenderContext frc = g2D.getFontRenderContext();
    Font font1 = new Font("Courier", Font.BOLD, 24);
    String str1 = new String("Java");
    TextLayout tl = new TextLayout(str1, font1, frc);
    g2D.setColor(Color.gray);
    tl.draw(g2D, 70, 150);
  }
  public static void main(String s[]) {
    JFrame frame1 = new JFrame("2D Text");
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame1.getContentPane().add("Center", new Main());
    frame1.pack();
    frame1.setSize(new Dimension(500, 300));
    frame1.setVisible(true);
  }
}



Drawing Rotated Text

   
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class BasicDraw {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.add(new MyComponent());
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class MyComponent extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D)g;
    
    g2d.drawString("aString", 100, 100);
    AffineTransform at = new AffineTransform();
    at.setToRotation(Math.PI / 4.0);
    g2d.setTransform(at);
    g2d.drawString("aString", 100, 100);
  }
}



Drawing Simple Text

   
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class BasicDraw {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.add(new MyComponent());
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class MyComponent extends JComponent {
  public void paint(Graphics g) {
    Font font = new Font("Serif", Font.PLAIN, 12);
    g.setFont(font);
    g.drawString("a String", 10, 10);
    FontMetrics fontMetrics = g.getFontMetrics();
    g.drawString("aString", 10, 10 + fontMetrics.getAscent());
  }
}



Draw string rotated clockwise 45 degrees

   
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class BasicDraw {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.add(new MyComponent());
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class MyComponent extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D)g;
    
    g2d.drawString("aString", 100, 100);
    AffineTransform at = new AffineTransform();
    at.setToRotation(Math.PI / 4.0);
    g2d.setTransform(at);
    g2d.drawString("aString", 100, 100);
  }
}



Draw string rotated counter-clockwise 45 degrees

   
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class BasicDraw {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.add(new MyComponent());
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class MyComponent extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D)g;
    
    AffineTransform at = new AffineTransform();
    at.setToRotation(Math.PI/4.0);
    g2d.setTransform(at);
    g2d.drawString("aString", 200, 100);
  }
}



drawString(): specify the position of the text on the window area

   
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Text extends JPanel {
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2d.setRenderingHints(rh);
    Font font = new Font("New Roma", Font.BOLD, 40);
    g2d.setFont(font);
    g2d.drawString("text", 20, 30);
  }
  public static void main(String[] args) {
    Text text = new Text();
    JFrame frame = new JFrame("Sonnet 55");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(text);
    frame.setSize(500, 470);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}



Generate Shape From Text

 
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Shape;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
/*
 * $Id: ShapeUtils.java,v 1.4 2008/10/14 22:31:46 rah003 Exp $
 *
 * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle,
 * Santa Clara, California 95054, U.S.A. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
public class Utils {
  public static Shape generateShapeFromText(Font font, char ch) {
    return generateShapeFromText(font, String.valueOf(ch));
  }
  public static Shape generateShapeFromText(Font font, String string) {
    BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = img.createGraphics();
    try {
      GlyphVector vect = font.createGlyphVector(g2.getFontRenderContext(), string);
      Shape shape = vect.getOutline(0f, (float) -vect.getVisualBounds().getY());
      return shape;
    } finally {
      g2.dispose();
    }
  }
}



Getting the Dimensions of Text

   
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class BasicDraw {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.add(new MyComponent());
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class MyComponent extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    FontMetrics fontMetrics = g2d.getFontMetrics();
    int width = fontMetrics.stringWidth("aString");
    int height = fontMetrics.getHeight();
    System.out.println(width);
    System.out.println(height);
  }
}



Have a Label with underlined text

   
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JLabel;
class UnderlinedLabel extends JLabel {
  public UnderlinedLabel() {
    this("");
  }
  public UnderlinedLabel(String text) {
    super(text);
  }
  public void paint(Graphics g) {
    Rectangle r;
    super.paint(g);
    r = g.getClipBounds();
    g.drawLine(0, r.height - getFontMetrics(getFont()).getDescent(), getFontMetrics(getFont())
        .stringWidth(getText()), r.height - getFontMetrics(getFont()).getDescent());
  }
}



Rotate a line of character (String)

   
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.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class RotatedText extends JPanel {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    String s = "111111111111111111111111111111";
    Font font = new Font("Courier", Font.PLAIN, 12);
    g2d.translate(20, 20);
    FontRenderContext frc = g2d.getFontRenderContext();
    GlyphVector gv = font.createGlyphVector(frc, s);
    int length = gv.getNumGlyphs();
    for (int i = 0; i < length; i++) {
      Point2D p = gv.getGlyphPosition(i);
      AffineTransform at = AffineTransform.getTranslateInstance(p.getX(), p.getY());
      at.rotate((double) i / (double) (length - 1) * Math.PI / 3);
      Shape glyph = gv.getGlyphOutline(i);
      Shape transformedGlyph = at.createTransformedShape(glyph);
      g2d.fill(transformedGlyph);
    }
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("Rotated text");
    frame.add(new RotatedText());
    frame.setSize(400, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}



Use AffineTransform to draw vertical text

   
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    AffineTransform at = new AffineTransform();
    at.setToRotation(-Math.PI / 2.0, getWidth() / 2.0, getHeight() / 2.0);
    g2d.setTransform(at);
    g2d.drawString("Vertical text", 10, 10);
  }
  public static void main(String[] a) {
    JFrame f = new JFrame();
    f.add(new Main());
    f.setSize(300, 300);
    f.setVisible(true);
  }
}