Java AWT Graphics2D draw String left alignment
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.font.FontRenderContext; import java.awt.geom.Rectangle2D; import java.util.Random; import javax.swing.JFrame; import javax.swing.JPanel; public class Main extends JPanel { Random rnd = new Random(); @Override/*from w w w. jav a2 s .c o m*/ public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setBackground(Color.WHITE); g2d.clearRect(0, 0, getParent().getWidth(), getParent().getHeight()); // antialising g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // SanSerif g2d.setPaint(Color.BLUE); Font serif = new Font(Font.SERIF, Font.PLAIN, 30); g2d.setFont(serif); String sentence1 = "The quick brown fox jumped"; String sentence2 = "over the lazy dog."; int y = 50; int x = 0; FontMetrics fm = g2d.getFontMetrics(); int spaceRow = fm.getDescent() + fm.getLeading() + fm.getAscent(); g2d.drawString(sentence1, x, y); g2d.drawString(sentence2, x, y + spaceRow); } public static void main(String[] args) { // create frame for Main JFrame frame = new JFrame("java2s.com"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Main Main = new Main(); frame.add(Main); frame.setSize(300, 210); frame.setVisible(true); } }